Programs & Examples On #Image recognition

Classification of a detected object into different known categories.

error: (-215) !empty() in function detectMultiScale

You just need to add proper path of the haarcascade_frontalface_default.xml file i.e. you only have to add prefix (cv2.data.haarcascades)

face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_eye.xml')

Algorithm to compare two images

This is just a suggestion, it might not work and I'm prepared to be called on this.

This will generate false positives, but hopefully not false negatives.

  1. Resize both of the images so that they are the same size (I assume that the ratios of widths to lengths are the same in both images).

  2. Compress a bitmap of both images with a lossless compression algorithm (e.g. gzip).

  3. Find pairs of files that have similar file sizes. For instance, you could just sort every pair of files you have by how similar the file sizes are and retrieve the top X.

As I said, this will definitely generate false positives, but hopefully not false negatives. You can implement this in five minutes, whereas the Porikil et. al. would probably require extensive work.

Reading data from XML

as per @Jon Skeet 's comment, you should use a XmlReader only if your file is very big. Here's how to use it. Assuming you have a Book class

public class Book {
    public string Title {get; set;}
    public string Author {get; set;}
}

you can read the XML file line by line with a small memory footprint, like this:

public static class XmlHelper {
    public static IEnumerable<Book> StreamBooks(string uri) {
        using (XmlReader reader = XmlReader.Create(uri)) {
            string title = null;
            string author = null;

            reader.MoveToContent();
            while (reader.Read()) {
                if (reader.NodeType == XmlNodeType.Element
                    && reader.Name == "Book") {
                    while (reader.Read()) {
                        if (reader.NodeType == XmlNodeType.Element &&
                            reader.Name == "Title") {
                            title = reader.ReadString();
                            break;
                        }
                    }
                    while (reader.Read()) {
                        if (reader.NodeType == XmlNodeType.Element &&
                            reader.Name == "Author") {
                            author =reader.ReadString();
                            break;
                        }
                    }
                    yield return new Book() {Title = title, Author = author};
                }
            }       
        }
    }

Example of usage:

string uri = @"c:\test.xml"; // your big XML file

foreach (var book in XmlHelper.StreamBooks(uri)) {
    Console.WriteLine("Title, Author: {0}, {1}", book.Title, book.Author);  
}

mysql error 2005 - Unknown MySQL server host 'localhost'(11001)

I have passed through that error today and did everything described above but didn't work for me. So I decided to view the core problem and logged onto the MySQL root folder in Windows 7 and did this solution:

  1. Go to folder:

    C:\AppServ\MySQL
    
  2. Right click and Run as Administrator these files:

    mysql_servicefix.bat
    
    mysql_serviceinstall.bat
    
    mysql_servicestart.bat
    

Then close the entire explorer window and reopen it or clear cache then login to phpMyAdmin again.

Sqlite: CURRENT_TIMESTAMP is in GMT, not the timezone of the machine

I think this might help.

SELECT datetime(strftime('%s','now'), 'unixepoch', 'localtime');

How do I increase memory on Tomcat 7 when running as a Windows Service?

//ES/tomcat -> This may not work if you have changed the service name during the installation.

Either run the command without any service name

.\bin\tomcat7w.exe //ES

or with exact service name

.\bin\tomcat7w.exe //ES/YourServiceName

Running JAR file on Windows 10

How do I run an executable JAR file? If you have a jar file called Example.jar, follow these rules:

Open a notepad.exe.
Write : java -jar Example.jar.
Save it with the extension .bat.
Copy it to the directory which has the .jar file.
Double click it to run your .jar file.

close fancy box from function from within open 'fancybox'

yes in Virtuemart its must be button CLOSe-continue shopping, not element, because after click you can redirect.. i found this redirect bug on my ajax website.

" netsh wlan start hostednetwork " command not working no matter what I try

This was a real issue for me, and quite a sneaky problem to try and remedy...

The problem I had was that a module that was installed on my WiFi adapter was conflicting with the Microsoft Virtual Adapter (or whatever it's actually called).

To fix it:

  1. Hold the Windows Key + Push R
  2. Type: ncpa.cpl in to the box, and hit OK.
  3. Identify the network adapter you want to use for the hostednetwork, right-click it, and select Properties.
  4. You'll see a big box in the middle of the properties window, under the heading The connection uses the following items:. Look down the list for anything that seems out of the ordinary, and uncheck it. Hit OK.
  5. Try running the netsh wlan start hostednetwork command again.
  6. Repeat steps 4 and 5 as necessary.

In my case my adapter was running a module called SoftEther Lightweight Network Protocol, which I believe is used to help connect to VPN Gate VPN servers via the SoftEther software.

If literally nothing else works, then I'd suspect something similar to the problem I encountered, namely that a module on your network adapter is interfering with the hostednetwork aspect of your driver.

What is Func, how and when is it used

Both C# and Java don't have plain functions only member functions (aka methods). And the methods are not first-class citizens. First-class functions allow us to create beautiful and powerful code, as seen in F# or Clojure languages. (For instance, first-class functions can be passed as parameters and can return functions.) Java and C# ameliorate this somewhat with interfaces/delegates.

Func<int, int, int> randInt = (n1, n2) => new Random().Next(n1, n2); 

So, Func is a built-in delegate which brings some functional programming features and helps reduce code verbosity.

Disable back button in android

if you are using FragmentActivity. then do like this

first call This inside your Fragment.

public void callParentMethod(){
    getActivity().onBackPressed();
}

and then Call onBackPressed method in side your parent FragmentActivity class.

@Override
public void onBackPressed() {
  //super.onBackPressed();
  //create a dialog to ask yes no question whether or not the user wants to exit
  ...
}

XmlSerializer giving FileNotFoundException at constructor

Troubleshooting compilation errors on the other hand is very complicated. These problems manifest themselves in a FileNotFoundException with the message:

File or assembly name abcdef.dll, or one of its dependencies, was not found. File name: "abcdef.dll"
   at System.Reflection.Assembly.nLoad( ... )
   at System.Reflection.Assembly.InternalLoad( ... )
   at System.Reflection.Assembly.Load(...)
   at System.CodeDom.Compiler.CompilerResults.get_CompiledAssembly() 

You may wonder what a file not found exception has to do with instantiating a serializer object, but remember: the constructor writes C# files and tries to compile them. The call stack of this exception provides some good information to support that suspicion. The exception occurred while the XmlSerializer attempted to load an assembly generated by CodeDOM calling the System.Reflection.Assembly.Load method. The exception does not provide an explanation as to why the assembly that the XmlSerializer was supposed to create was not present. In general, the assembly is not present because the compilation failed, which may happen because, under rare circumstances, the serialization attributes produce code that the C# compiler fails to compile.

Note This error also occurs when the XmlSerializer runs under an account or a security environment that is not able to access the temp directory.

Source: http://msdn.microsoft.com/en-us/library/aa302290.aspx

How to align title at center of ActionBar in default theme(Theme.Holo.Light)

After two days of going through the web, this is what I came up with in Kotlin. Tested and works on my app

  private fun setupActionBar() {
    supportActionBar?.apply {
        displayOptions = ActionBar.DISPLAY_SHOW_CUSTOM
        displayOptions = ActionBar.DISPLAY_SHOW_TITLE
        setDisplayShowCustomEnabled(true)
        title = ""


        val titleTextView = AppCompatTextView(this@MainActivity)
        titleTextView.text = getText(R.string.app_name)
        titleTextView.setSingleLine()
        titleTextView.textSize = 24f
        titleTextView.setTextColor(ContextCompat.getColor(this@MainActivity, R.color.appWhite))

        val layoutParams = ActionBar.LayoutParams(
            ActionBar.LayoutParams.WRAP_CONTENT,
            ActionBar.LayoutParams.WRAP_CONTENT
        )
        layoutParams.gravity = Gravity.CENTER
        setCustomView(titleTextView, layoutParams)

        setBackgroundDrawable(
            ColorDrawable(
                ContextCompat.getColor(
                    this@MainActivity,
                    R.color.appDarkBlue
                )
            )
        )

    }
}

Sass Variable in CSS calc() function

Here is a really simple solution using SASS/SCSS and a math formula style:

/* frame circle */
.container {
    position: relative;
    border-radius: 50%;
    background-color: white;
    overflow: hidden;
    width: 400px;
    height: 400px; }

/* circle sectors */
.menu-frame-sector {
    position: absolute;
    width: 50%;
    height: 50%;
    z-index: 10000;
    transform-origin: 100% 100%;
  }

$sector_count: 8;
$sector_width: 360deg / $sector_count;

.sec0 {
    transform: rotate(0 * $sector_width) skew($sector_width);
    background-color: red; }
.sec1 {
    transform: rotate(1 * $sector_width) skew($sector_width);
    background-color: blue; }
.sec2 {
    transform: rotate(2 * $sector_width) skew($sector_width);
    background-color: red; }
.sec3 {
    transform: rotate(3 * $sector_width) skew($sector_width);
    background-color: blue; }
.sec4 {
    transform: rotate(4 * $sector_width) skew($sector_width);
    background-color: red; }
.sec5 {
    transform: rotate(5 * $sector_width) skew($sector_width);
    background-color: blue; }
.sec6 {
    transform: rotate(6 * $sector_width) skew($sector_width);
    background-color: red; }
.sec7 {
    transform: rotate(7 * $sector_width) skew($sector_width);
    background-color: blue; }

To conclude, I strongly suggest you to understand transform-origin, rotate() and skew():

https://tympanus.net/codrops/2013/08/09/building-a-circular-navigation-with-css-transforms/

Is there a way to get rid of accents and convert a whole string to regular letters?

The solution by @virgo47 is very fast, but approximate. The accepted answer uses Normalizer and a regular expression. I wondered what part of the time was taken by Normalizer versus the regular expression, since removing all the non-ASCII characters can be done without a regex:

import java.text.Normalizer;

public class Strip {
    public static String flattenToAscii(String string) {
        StringBuilder sb = new StringBuilder(string.length());
        string = Normalizer.normalize(string, Normalizer.Form.NFD);
        for (char c : string.toCharArray()) {
            if (c <= '\u007F') sb.append(c);
        }
        return sb.toString();
    }
}

Small additional speed-ups can be obtained by writing into a char[] and not calling toCharArray(), although I'm not sure that the decrease in code clarity merits it:

public static String flattenToAscii(String string) {
    char[] out = new char[string.length()];
    string = Normalizer.normalize(string, Normalizer.Form.NFD);
    int j = 0;
    for (int i = 0, n = string.length(); i < n; ++i) {
        char c = string.charAt(i);
        if (c <= '\u007F') out[j++] = c;
    }
    return new String(out);
}

This variation has the advantage of the correctness of the one using Normalizer and some of the speed of the one using a table. On my machine, this one is about 4x faster than the accepted answer, and 6.6x to 7x slower that @virgo47's (the accepted answer is about 26x slower than @virgo47's on my machine).

Deny access to one specific folder in .htaccess

You can do this dynamically that way:

mkdir($dirname);
@touch($dirname . "/.htaccess");
  $f = fopen($dirname . "/.htaccess", "w");
  fwrite($f, "deny from all");
fclose($f);

getting the table row values with jquery

$(document).ready(function () {
        $("#tbl_Customer tbody tr .companyname").click(function () {

            var comapnyname = $(this).closest(".trclass").find(".companyname").text();
            var CompanyAddress = $(this).closest(".trclass").find(".CompanyAddress").text();
            var CompanyEmail = $(this).closest(".trclass").find(".CompanyEmail").text();
            var CompanyContactNumber = $(this).closest(".trclass").find(".CompanyContactNumber").text();
            var CompanyContactPerson = $(this).closest(".trclass").find(".CompanyContactPerson").text();
           // var clickedCell = $(this);
            alert(comapnyname);
            alert(CompanyAddress);
            alert(CompanyEmail);
            alert(CompanyContactNumber);
            alert(CompanyContactPerson);

            //alert(clickedCell.text());
        });
    });

How to print_r $_POST array?

You are adding the $_POST array as the first element to $myarray. If you wish to reference it, just do:

$myarray = $_POST;

However, this is probably not necessary, as you can just call it via $_POST in your script.

How to list installed packages from a given repo using yum

On newer versions of yum, this information is stored in the "yumdb" when the package is installed. This is the only 100% accurate way to get the information, and you can use:

yumdb search from_repo repoid

(or repoquery and grep -- don't grep yum output). However the command "find-repos-of-install" was part of yum-utils for a while which did the best guess without that information:

http://james.fedorapeople.org/yum/commands/find-repos-of-install.py

As floyd said, a lot of repos. include a unique "dist" tag in their release, and you can look for that ... however from what you said, I guess that isn't the case for you?

Issue with Task Scheduler launching a task

As far as I know you will need to give the domain account the proper "User Rights" such as "Log on as a Batch Job". You can check that in your Local Policies. Also, you might have a Domain GPO which is overwriting your local policies. I bet if you add this Domain Account into the local admin group of that machine, your problem will go away. A few articles for you to check:

http://social.technet.microsoft.com/Forums/en/windowsserver2008r2general/thread/9edcb63a-d133-45a0-9e8c-f1b774765531 http://social.technet.microsoft.com/Forums/lv/winservergen/thread/68019b24-78a5-4db0-a150-ada921930924 http://sqlsolace.blogspot.com/2009/08/task-scheduler-task-does-not-run-error.html?m=1 http://technet.microsoft.com/en-us/library/cc722152.aspx

Domain Account keeping locking out with correct password every few minutes

Finally i found my problem. SQL Reporting Service was causing my account lockout. Stop and try, after confirm no more passwords bad attempts i should reconfigure reporting services service account ---Not at Service Properties, it is in Reporting Service own config--.

Default background color of SVG root element

Found this works in Safari. SVG only colors in with background-color where an element's bounding box covers. So, give it a border (stroke) with a zero pixel boundary. It fills in the whole thing for you with your background-color.

<svg style='stroke-width: 0px; background-color: blue;'> </svg>

mailto link multiple body lines

This is what I do, just add \n and use encodeURIComponent

Example

var emailBody = "1st line.\n 2nd line \n 3rd line";

emailBody = encodeURIComponent(emailBody);

href = "mailto:[email protected]?body=" + emailBody;

Check encodeURIComponent docs

Is a view faster than a simple query?

My understanding is that a while back, a view would be faster because SQL Server could store an execution plan and then just use it instead of trying to figure one out on the fly. I think the performance gains nowadays is probably not as great as it once was, but I would have to guess there would be some marginal improvement to use the view.

$(document).ready(function() is not working

I have same issue ... at http://www.xaluan.com .. but after log. I find out that after jQuery run I make a function using one element id which not exists ..

Eg:

$('#aaa').remove()  <span class="aaa">sss</spam> 

so the id="aaa" did not exist .. then jQuery stops running.. because errors like that

How to increase the gap between text and underlining in CSS

@last-child's answer is a great answer!

However, adding a border to my H2 produced an underline longer than the text.

If you're dynamically writing your CSS, or if like me you're lucky and know what the text will be, you can do the following:

  1. change the content to something the right length (ie the same

  2. text) set the font color to transparent (or rgba(0,0,0,0) )

to underline <h2>Processing</h2> (for example), change last-child's code to be:

a {
    text-decoration: none;
    position: relative;
}
a:after {
    content: 'Processing';
    color: transparent;

    width: 100%;
    position: absolute;
    left: 0;
    bottom: 1px;

    border-width: 0 0 1px;
    border-style: solid;
}

Oracle - Insert New Row with Auto Incremental ID

ELXAN@DB1> create table cedvel(id integer,ad varchar2(15));

Table created.

ELXAN@DB1> alter table cedvel add constraint pk_ad primary key(id);

Table altered.

ELXAN@DB1> create sequence test_seq start with 1 increment by 1;

Sequence created.

ELXAN@DB1> create or replace trigger ad_insert
before insert on cedvel
REFERENCING NEW AS NEW OLD AS OLD
for each row
begin
    select test_seq.nextval into :new.id from dual;
end;
/  2    3    4    5    6    7    8 

Trigger created.

ELXAN@DB1> insert into cedvel (ad) values ('nese');

1 row created.

VS 2017 Git Local Commit DB.lock error on every commit

Step 1:
Add .vs/ to your .gitignore file (as said in other answers).

Step 2:
It is important to understand, that step 1 WILL NOT remove files within .vs/ from your current branch index, if they have already been added to it. So clear your active branch by issuing:

git rm --cached -r .vs/*

Step 3:
Best to immediately repeat steps 1 and 2 for all other active branches of your project as well.
Otherwise you will easily face the same problems again when switching to an uncleaned branch.

Pro tip:
Instead of step 1 you may want to to use this official .gitingore template for VisualStudio that covers much more than just the .vs path:
https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
(But still don't forget steps 2 and 3.)

How to set all elements of an array to zero or any same value?

If your array is static or global it's initialized to zero before main() starts. That would be the most efficient option.

Round integers to the nearest 10

Slightly simpler:

def round_int(x):
    return 10 * ((x + 5) // 10)

OrderBy pipe issue

Updated OrderByPipe: fixed not sorting strings.

create a OrderByPipe class:

import { Pipe, PipeTransform } from "@angular/core";
@Pipe( {
name: 'orderBy'
} )
export class OrderByPipe implements PipeTransform {
transform( array: Array<any>, orderField: string, orderType: boolean ): Array<string> {
    array.sort( ( a: any, b: any ) => {
        let ae = a[ orderField ];
        let be = b[ orderField ];
        if ( ae == undefined && be == undefined ) return 0;
        if ( ae == undefined && be != undefined ) return orderType ? 1 : -1;
        if ( ae != undefined && be == undefined ) return orderType ? -1 : 1;
        if ( ae == be ) return 0;
        return orderType ? (ae.toString().toLowerCase() > be.toString().toLowerCase() ? -1 : 1) : (be.toString().toLowerCase() > ae.toString().toLowerCase() ? -1 : 1);
    } );
    return array;
  }
}

in your controller:

@Component({
pipes: [OrderByPipe]
})

or in your

 declarations: [OrderByPipe]

in your html:

<tr *ngFor="let obj of objects | orderBy : ObjFieldName: OrderByType">

ObjFieldName: object field name you want to sort;

OrderByType: boolean; true: descending order; false: ascending;

How to download source in ZIP format from GitHub?

I was facing same problem but accidentlty I sorted this problem. 1) Login in github 2) Click on Fork Button at Top Right. 3) After above step you can see Clone or download in Green color under <> Code Tab.

Is there a standard sign function (signum, sgn) in C/C++?

Why use ternary operators and if-else when you can simply do this

#define sgn(x) x==0 ? 0 : x/abs(x)

What is difference between functional and imperative programming languages?

Imperative programming style was practiced in web development from 2005 all the way to 2013.

With imperative programming, we wrote out code that listed exactly what our application should do, step by step.

The functional programming style produces abstraction through clever ways of combining functions.

There is mention of declarative programming in the answers and regarding that I will say that declarative programming lists out some rules that we are to follow. We then provide what we refer to as some initial state to our application and we let those rules kind of define how the application behaves.

Now, these quick descriptions probably don’t make a lot of sense, so lets walk through the differences between imperative and declarative programming by walking through an analogy.

Imagine that we are not building software, but instead we bake pies for a living. Perhaps we are bad bakers and don’t know how to bake a delicious pie the way we should.

So our boss gives us a list of directions, what we know as a recipe.

The recipe will tell us how to make a pie. One recipe is written in an imperative style like so:

  1. Mix 1 cup of flour
  2. Add 1 egg
  3. Add 1 cup of sugar
  4. Pour the mixture into a pan
  5. Put the pan in the oven for 30 minutes and 350 degrees F.

The declarative recipe would do the following:

1 cup of flour, 1 egg, 1 cup of sugar - initial State

Rules

  1. If everything mixed, place in pan.
  2. If everything unmixed, place in bowl.
  3. If everything in pan, place in oven.

So imperative approaches are characterized by step by step approaches. You start with step one and go to step 2 and so on.

You eventually end up with some end product. So making this pie, we take these ingredients mix them, put it in a pan and in the oven and you got your end product.

In a declarative world, its different.In the declarative recipe we would separate our recipe into two separate parts, start with one part that lists the initial state of the recipe, like the variables. So our variables here are the quantities of our ingredients and their type.

We take the initial state or initial ingredients and apply some rules to them.

So we take the initial state and pass them through these rules over and over again until we get a ready to eat rhubarb strawberry pie or whatever.

So in a declarative approach, we have to know how to properly structure these rules.

So the rules we might want to examine our ingredients or state, if mixed, put them in a pan.

With our initial state, that doesn’t match because we haven’t yet mixed our ingredients.

So rule 2 says, if they not mixed then mix them in a bowl. Okay yeah this rule applies.

Now we have a bowl of mixed ingredients as our state.

Now we apply that new state to our rules again.

So rule 1 says if ingredients are mixed place them in a pan, okay yeah now rule 1 does apply, lets do it.

Now we have this new state where the ingredients are mixed and in a pan. Rule 1 is no longer relevant, rule 2 does not apply.

Rule 3 says if the ingredients are in a pan, place them in the oven, great that rule is what applies to this new state, lets do it.

And we end up with a delicious hot apple pie or whatever.

Now, if you are like me, you may be thinking, why are we not still doing imperative programming. This makes sense.

Well, for simple flows yes, but most web applications have more complex flows that cannot be properly captured by imperative programming design.

In a declarative approach, we may have some initial ingredients or initial state like textInput=“”, a single variable.

Maybe text input starts off as an empty string.

We take this initial state and apply it to a set of rules defined in your application.

  1. If a user enters text, update text input. Well, right now that doesn’t apply.

  2. If template is rendered, calculate the widget.

  3. If textInput is updated, re render the template.

Well, none of this applies so the program will just wait around for an event to happen.

So at some point a user updates the text input and then we might apply rule number 1.

We may update that to “abcd”

So we just updated our text and textInput updates, rule number 2 does not apply, rule number 3 says if text input is update, which just occurred, then re render the template and then we go back to rule 2 thats says if template is rendered, calculate the widget, okay lets calculate the widget.

In general, as programmers, we want to strive for more declarative programming designs.

Imperative seems more clear and obvious, but a declarative approach scales very nicely for larger applications.

Linux find and grep command together

Or maybe even easier

grep -R put **/*bills*

The ** glob syntax means "any depth of directories". It will work in Zsh, and I think recent versions of Bash too.

How to combine two lists in R

c can be used on lists (and not only on vectors):

# you have
l1 = list(2, 3)
l2 = list(4)

# you want
list(2, 3, 4)
[[1]]
[1] 2

[[2]]
[1] 3

[[3]]
[1] 4

# you can do
c(l1, l2)
[[1]]
[1] 2

[[2]]
[1] 3

[[3]]
[1] 4

If you have a list of lists, you can do it (perhaps) more comfortably with do.call, eg:

do.call(c, list(l1, l2))

How do I create a unique constraint that also allows nulls?

SQL Server 2008 +

You can create a unique index that accept multiple NULLs with a WHERE clause. See the answer below.

Prior to SQL Server 2008

You cannot create a UNIQUE constraint and allow NULLs. You need set a default value of NEWID().

Update the existing values to NEWID() where NULL before creating the UNIQUE constraint.

Automapper missing type map configuration or unsupported mapping - Error

I had same issue in .Net Core. Because my base dto class(i give it as a type in startup for automapper assembly) was in different project. Automapper tried to search for profiles in base class project. But my dto's were in different project. I moved my base class. And problem solved. This may help for some persons.

How to trigger the window resize event in JavaScript?

I wasn't actually able to get this to work with any of the above solutions. Once I bound the event with jQuery then it worked fine as below:

$(window).bind('resize', function () {
    resizeElements();
}).trigger('resize');

How to create an infinite loop in Windows batch file?

How about using good(?) old goto?

:loop

echo Ooops

goto loop

See also this for a more useful example.

How to make rounded percentages add up to 100%

I wrote a C# version rounding helper, the algorithm is same as Varun Vohra's answer, hope it helps.

public static List<decimal> GetPerfectRounding(List<decimal> original,
    decimal forceSum, int decimals)
{
    var rounded = original.Select(x => Math.Round(x, decimals)).ToList();
    Debug.Assert(Math.Round(forceSum, decimals) == forceSum);
    var delta = forceSum - rounded.Sum();
    if (delta == 0) return rounded;
    var deltaUnit = Convert.ToDecimal(Math.Pow(0.1, decimals)) * Math.Sign(delta);

    List<int> applyDeltaSequence; 
    if (delta < 0)
    {
        applyDeltaSequence = original
            .Zip(Enumerable.Range(0, int.MaxValue), (x, index) => new { x, index })
            .OrderBy(a => original[a.index] - rounded[a.index])
            .ThenByDescending(a => a.index)
            .Select(a => a.index).ToList();
    }
    else
    {
        applyDeltaSequence = original
            .Zip(Enumerable.Range(0, int.MaxValue), (x, index) => new { x, index })
            .OrderByDescending(a => original[a.index] - rounded[a.index])
            .Select(a => a.index).ToList();
    }

    Enumerable.Repeat(applyDeltaSequence, int.MaxValue)
        .SelectMany(x => x)
        .Take(Convert.ToInt32(delta/deltaUnit))
        .ForEach(index => rounded[index] += deltaUnit);

    return rounded;
}

It pass the following Unit test:

[TestMethod]
public void TestPerfectRounding()
{
    CollectionAssert.AreEqual(Utils.GetPerfectRounding(
        new List<decimal> {3.333m, 3.334m, 3.333m}, 10, 2),
        new List<decimal> {3.33m, 3.34m, 3.33m});

    CollectionAssert.AreEqual(Utils.GetPerfectRounding(
        new List<decimal> {3.33m, 3.34m, 3.33m}, 10, 1),
        new List<decimal> {3.3m, 3.4m, 3.3m});

    CollectionAssert.AreEqual(Utils.GetPerfectRounding(
        new List<decimal> {3.333m, 3.334m, 3.333m}, 10, 1),
        new List<decimal> {3.3m, 3.4m, 3.3m});


    CollectionAssert.AreEqual(Utils.GetPerfectRounding(
        new List<decimal> { 13.626332m, 47.989636m, 9.596008m, 28.788024m }, 100, 0),
        new List<decimal> {14, 48, 9, 29});
    CollectionAssert.AreEqual(Utils.GetPerfectRounding(
        new List<decimal> { 16.666m, 16.666m, 16.666m, 16.666m, 16.666m, 16.666m }, 100, 0),
        new List<decimal> { 17, 17, 17, 17, 16, 16 });
    CollectionAssert.AreEqual(Utils.GetPerfectRounding(
        new List<decimal> { 33.333m, 33.333m, 33.333m }, 100, 0),
        new List<decimal> { 34, 33, 33 });
    CollectionAssert.AreEqual(Utils.GetPerfectRounding(
        new List<decimal> { 33.3m, 33.3m, 33.3m, 0.1m }, 100, 0),
        new List<decimal> { 34, 33, 33, 0 });
}

Programmatically getting the MAC of an Android device

You can get mac address:

WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
WifiInfo wInfo = wifiManager.getConnectionInfo();
String mac = wInfo.getMacAddress();

Set Permission in Menifest.xml

<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission>

Add string in a certain position in Python

This seems very easy:

>>> hash = "355879ACB6"
>>> hash = hash[:4] + '-' + hash[4:]
>>> print hash
3558-79ACB6

However if you like something like a function do as this:

def insert_dash(string, index):
    return string[:index] + '-' + string[index:]

print insert_dash("355879ACB6", 5)

An error occurred while collecting items to be installed (Access is denied)

I just solved this problem by unchecking Read only checkbox of the Program Files/eclipse folder on win7.

Apply to all files and folders.

Django set field value after a form is initialized

Something like Nigel Cohen's would work if you were adding data to a copy of the collected set of form data:

form = FormType(request.POST)
if request.method == "POST":
    formcopy = form(request.POST.copy())
    formcopy.data['Email'] = GetEmailString()

Parsing command-line arguments in C

#include <stdio.h>

int main(int argc, char **argv)
{
    size_t i;
    size_t filename_i = -1;

    for (i = 0; i < argc; i++)
    {
        char const *option =  argv[i];
        if (option[0] == '-')
        {
            printf("I am a flagged option");
            switch (option[1])
            {
                case 'a':
                    /*someting*/
                    break;
                case 'b':
                    break;
                case '-':
                    /* "--" -- the next argument will be a file.*/
                    filename_i = i;
                    i = i + 1;
                    break;
                default:
                    printf("flag not recognised %s", option);
                    break;
            }
        }
        else
        {   
            printf("I am a positional argument");
        }

        /* At this point, if -- was specified, then filename_i contains the index
         into argv that contains the filename. If -- was not specified, then filename_i will be -1*/
     }
  return 0;
}

Do HTTP POST methods send data as a QueryString?

The best way to visualize this is to use a packet analyzer like Wireshark and follow the TCP stream. HTTP simply uses TCP to send a stream of data starting with a few lines of HTTP headers. Often this data is easy to read because it consists of HTML, CSS, or XML, but it can be any type of data that gets transfered over the internet (Executables, Images, Video, etc).

For a GET request, your computer requests a specific URL and the web server usually responds with a 200 status code and the the content of the webpage is sent directly after the HTTP response headers. This content is the same content you would see if you viewed the source of the webpage in your browser. The query string you mentioned is just part of the URL and gets included in the HTTP GET request header that your computer sends to the web server. Below is an example of an HTTP GET request to http://accel91.citrix.com:8000/OA_HTML/OALogout.jsp?menu=Y, followed by a 302 redirect response from the server. Some of the HTTP Headers are wrapped due to the size of the viewing window (these really only take one line each), and the 302 redirect includes a simple HTML webpage with a link to the redirected webpage (Most browsers will automatically redirect any 302 response to the URL listed in the Location header instead of displaying the HTML response):

HTTP GET with 302 redirect

For a POST request, you may still have a query string, but this is uncommon and does not have anything to do with the data that you are POSTing. Instead, the data is included directly after the HTTP headers that your browser sends to the server, similar to the 200 response that the web server uses to respond to a GET request. In the case of POSTing a simple web form this data is encoded using the same URL encoding that a query string uses, but if you are using a SOAP web service it could also be encoded using a multi-part MIME format and XML data.

For example here is what an HTTP POST to an XML based SOAP web service located at http://192.168.24.23:8090/msh looks like in Wireshark Follow TCP Stream:

HTTP POST TCP Stream

How do I reset the setInterval timer?

Once you clear the interval using clearInterval you could setInterval once again. And to avoid repeating the callback externalize it as a separate function:

var ticker = function() {
    console.log('idle');
};

then:

var myTimer = window.setInterval(ticker, 4000);

then when you decide to restart:

window.clearInterval(myTimer);
myTimer = window.setInterval(ticker, 4000);

How to convert (transliterate) a string from utf8 to ASCII (single byte) in c#?

This was in response to your other question, that looks like it's been deleted....the point still stands.

Looks like a classic Unicode to ASCII issue. The trick would be to find where it's happening.

.NET works fine with Unicode, assuming it's told it's Unicode to begin with (or left at the default).

My guess is that your receiving app can't handle it. So, I'd probably use the ASCIIEncoder with an EncoderReplacementFallback with String.Empty:

using System.Text;

string inputString = GetInput();
var encoder = ASCIIEncoding.GetEncoder();
encoder.Fallback = new EncoderReplacementFallback(string.Empty);

byte[] bAsciiString = encoder.GetBytes(inputString);

// Do something with bytes...
// can write to a file as is
File.WriteAllBytes(FILE_NAME, bAsciiString);
// or turn back into a "clean" string
string cleanString = ASCIIEncoding.GetString(bAsciiString); 
// since the offending bytes have been removed, can use default encoding as well
Assert.AreEqual(cleanString, Default.GetString(bAsciiString));

Of course, in the old days, we'd just loop though and remove any chars greater than 127...well, those of us in the US at least. ;)

How do I change the number of open files limit in Linux?

1) Add the following line to /etc/security/limits.conf

webuser hard nofile 64000

then login as webuser

su - webuser

2) Edit following two files for webuser

append .bashrc and .bash_profile file by running

echo "ulimit -n 64000" >> .bashrc ; echo "ulimit -n 64000" >> .bash_profile

3) Log out, then log back in and verify that the changes have been made correctly:

$ ulimit -a | grep open
open files                      (-n) 64000

Thats it and them boom, boom boom.

Send a base64 image in HTML email

Support, unfortunately, is brutal at best. Here's a post on the topic:

https://www.campaignmonitor.com/blog/email-marketing/2013/02/embedded-images-in-html-email/

And the post content: enter image description here

Getting the Facebook like/share count for a given URL

UPDATE: This solution is no longer valid. FQLs are deprecated since August 7th, 2016.


https://api.facebook.com/method/fql.query?query=select%20%20like_count%20from%20link_stat%20where%20url=%22http://www.techlila.com%22

Also http://api.facebook.com/restserver.php?method=links.getStats&urls=http://www.techlila.com will show you all the data like 'Share Count', 'Like Count' and 'Comment Count' and total of all these.

Change the URL (i.e. http://www.techlila.com) as per your need.

This is the correct URL, I'm getting right results.

EDIT (May 2017): as of v2.9 you can make a graph API call where ID is the URL and select the 'engagement' field, below is a link with the example from the graph explorer.

https://developers.facebook.com/tools/explorer/?method=GET&path=%3Fid%3Dhttp%3A%2F%2Fcomunidade.edp.pt%26fields%3Dengagement&version=v2.9

How to connect SQLite with Java?

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import javax.swing.JOptionPane;   


public class Connectdatabase {

        Connection con = null;

        public static Connection ConnecrDb(){

            try{
                //String dir = System.getProperty("user.dir");
                Class.forName("org.sqlite.JDBC");
                Connection con = DriverManager.getConnection("jdbc:sqlite:D:\\testdb.db");
                return con;
            }
            catch(ClassNotFoundException | SQLException e){
                JOptionPane.showMessageDialog(null,"Problem with connection of database");
                return null;
            }
        }

    }

Fatal error: Cannot use object of type stdClass as array in

if you really want an array instead you can use:

$getvidids->result_array()

which would return the same information as an associative array.

ASP.NET Temporary files cleanup

Just an update on more current OS's (Vista, Win7, etc.) - the temp file path has changed may be different based on several variables. The items below are not definitive, however, they are a few I have encountered:

"temp" environment variable setting - then it would be:

%temp%\Temporary ASP.NET Files

Permissions and what application/process (VS, IIS, IIS Express) is running the .Net compiler. Accessing the C:\WINDOWS\Microsoft.NET\Framework folders requires elevated permissions and if you are not developing under an account with sufficient permissions then this folder might be used:

c:\Users\[youruserid]\AppData\Local\Temp\Temporary ASP.NET Files

There are also cases where the temp folder can be set via config for a machine or site specific using this:

<compilation tempDirectory="d:\MyTempPlace" />

I even have a funky setup at work where we don't run Admin by default, plus the IT guys have login scripts that set %temp% and I get temp files in 3 different locations depending on what is compiling things! And I'm still not certain about how these paths get picked....sigh.

Still, dthrasher is correct, you can just delete these and VS and IIS will just recompile them as needed.

Detect if an element is visible with jQuery

if($('#testElement').is(':visible')){
    //what you want to do when is visible
}

Change the default base url for axios

From axios docs you have baseURL and url

baseURL will be prepended to url when making requests. So you can define baseURL as http://127.0.0.1:8000 and make your requests to /url

 // `url` is the server URL that will be used for the request
 url: '/user',

 // `baseURL` will be prepended to `url` unless `url` is absolute.
 // It can be convenient to set `baseURL` for an instance of axios to pass relative URLs
 // to methods of that instance.
 baseURL: 'https://some-domain.com/api/',

php multidimensional array get values

This is the way to iterate on this array:

foreach($hotels as $row) {
       foreach($row['rooms'] as $k) {
             echo $k['boards']['board_id'];
             echo $k['boards']['price'];
       }
}

You want to iterate on the hotels and the rooms (the ones with numeric indexes), because those seem to be the "collections" in this case. The other arrays only hold and group properties.

Best/Most Comprehensive API for Stocks/Financial Data

Some of the brokerage firms like TDAmeritrade have APIs you can use to get streaming data from their servers:

http://www.tdameritrade.com/tradingtools/partnertools/api_dev.html

Is there an advantage to use a Synchronized Method instead of a Synchronized Block?

I suppose this question is about the difference between Thread Safe Singleton and Lazy initialization with Double check locking. I always refer to this article when I need to implement some specific singleton.

Well, this is a Thread Safe Singleton:

// Java program to create Thread Safe 
// Singleton class 
public class GFG  
{ 
  // private instance, so that it can be 
  // accessed by only by getInstance() method 
  private static GFG instance; 

  private GFG()  
  { 
    // private constructor 
  } 

 //synchronized method to control simultaneous access 
  synchronized public static GFG getInstance()  
  { 
    if (instance == null)  
    { 
      // if instance is null, initialize 
      instance = new GFG(); 
    } 
    return instance; 
  } 
} 

Pros:

  1. Lazy initialization is possible.

  2. It is thread safe.

Cons:

  1. getInstance() method is synchronized so it causes slow performance as multiple threads can’t access it simultaneously.

This is a Lazy initialization with Double check locking:

// Java code to explain double check locking 
public class GFG  
{ 
  // private instance, so that it can be 
  // accessed by only by getInstance() method 
  private static GFG instance; 

  private GFG()  
  { 
    // private constructor 
  } 

  public static GFG getInstance() 
  { 
    if (instance == null)  
    { 
      //synchronized block to remove overhead 
      synchronized (GFG.class) 
      { 
        if(instance==null) 
        { 
          // if instance is null, initialize 
          instance = new GFG(); 
        } 

      } 
    } 
    return instance; 
  } 
} 

Pros:

  1. Lazy initialization is possible.

  2. It is also thread safe.

  3. Performance reduced because of synchronized keyword is overcome.

Cons:

  1. First time, it can affect performance.

  2. As cons. of double check locking method is bearable so it can be used for high performance multi-threaded applications.

Please refer to this article for more details:

https://www.geeksforgeeks.org/java-singleton-design-pattern-practices-examples/

@ variables in Ruby on Rails

A tutorial about What is Variable Scope? presents some details quite well, just enclose the related here.


+------------------+----------------------+
| Name Begins With |    Variable Scope    |
+------------------+----------------------+
| $                | A global variable    |
| @                | An instance variable |
| [a-z] or _       | A local variable     |
| [A-Z]            | A constant           |
| @@               | A class variable     |
+------------------+----------------------+

Appending HTML string to the DOM

The right way is using insertAdjacentHTML. In Firefox earlier than 8, you can fall back to using Range.createContextualFragment if your str contains no script tags.

If your str contains script tags, you need to remove script elements from the fragment returned by createContextualFragment before inserting the fragment. Otherwise, the scripts will run. (insertAdjacentHTML marks scripts unexecutable.)

What processes are using which ports on unix?

netstat -l (assuming it comes with that version of UNIX)

React ignores 'for' attribute of the label element

The for attribute is called htmlFor for consistency with the DOM property API. If you're using the development build of React, you should have seen a warning in your console about this.

Inline elements shifting when made bold on hover

I had a problem similar to yours. I wanted my links to get bold when you hover over them but not only in the menu but also in the text. As you cen guess it would be a real chore figuring out all the different widths. The solution is pretty simple:

Create a box that contains the link text in bold but coloured like your background and but your real link above it. Here's an example from my page:

CSS:

.hypo { font-weight: bold; color: #FFFFE0; position: static; z-index: 0; }
.hyper { position: absolute; z-index: 1; }

Of course you need to replace #FFFFE0 by the background colour of your page. The z-indices don't seem to be necessary but I put them anyway (as the "hypo" element will occur after the "hyper" element in the HTML-Code). Now, to put a link on your page, include the following:

HTML:

You can find foo <a href="http://bar.com" class="hyper">here</a><span class="hypo">here</span>

The second "here" will be invisible and hidden below your link. As this is a static box with your link text in bold, the rest of your text won't shift any longer as it is already shifted before you hover over the link.

Hope I was able to help :).

So long

Disabling the long-running-script message in Internet Explorer

This message displays when Internet Explorer reaches the maximum number of synchronous instructions for a piece of JavaScript. The default maximum is 5,000,000 instructions, you can increase this number on a single machine by editing the registry.

Internet Explorer now tracks the total number of executed script statements and resets the value each time that a new script execution is started, such as from a timeout or from an event handler, for the current page with the script engine. Internet Explorer displays a "long-running script" dialog box when that value is over a threshold amount.

The only way to solve the problem for all users that might be viewing your page is to break up the number of iterations your loop performs using timers, or refactor your code so that it doesn't need to process as many instructions.

Breaking up a loop with timers is relatively straightforward:

var i=0;
(function () {
    for (; i < 6000000; i++) {
        /*
            Normal processing here
        */

        // Every 100,000 iterations, take a break
        if ( i > 0 && i % 100000 == 0) {
            // Manually increment `i` because we break
            i++;
            // Set a timer for the next iteration 
            window.setTimeout(arguments.callee);
            break;
        }
    }
})();

MySQL: How to set the Primary Key on phpMyAdmin?

You can't set the field having data-type "text". Only because of that thing you are getting this error. Try to change the data-type with int

C# Set collection?

I use a wrapper around a Dictionary<T, object>, storing nulls in the values. This gives O(1) add, lookup and remove on the keys, and to all intents and purposes acts like a set.

How to get the difference (only additions) between two files in linux

You can try this

diff --changed-group-format='%>' --unchanged-group-format='' A1 A2

The options are documented in man diff:

       --GTYPE-group-format=GFMT
              format GTYPE input groups with GFMT

and:

       LTYPE is 'old', 'new', or 'unchanged'.
              GTYPE is LTYPE or 'changed'.

and:

              GFMT (only) may contain:

       %<     lines from FILE1

       %>     lines from FILE2

       [...]

Cannot set property 'display' of undefined

document.getElementsByClassName('btn-pageMenu') delivers a nodeList. You should use: document.getElementsByClassName('btn-pageMenu')[0].style.display (if it's the first element from that list you want to change.

If you want to change style.display for all nodes loop through the list:

var elems = document.getElementsByClassName('btn-pageMenu');
for (var i=0;i<elems.length;i+=1){
  elems[i].style.display = 'block';
}

to be complete: if you use jquery it is as simple as:

?$('.btn-pageMenu').css('display'???????????????????????????,'block');??????

Embedding VLC plugin on HTML page

Unfortunately, IE and VLC don't really work right now... I found this on the vlc forums:

VLC included activex support up until version 0.8.6, I believe. At that time, you could
access a cab on the videolan and therefore 'automatic' installation into IE and Firefox
family browsers was fine. Thereafter support for activex seemed to stop; no cab, no
activex component.

VLC 1.0.* once again contains activex support, and that's brilliant. A good decision in
my opinion. What's lacking is a cab installer for the latest version.

This basically means that even if you found a way to make it work, anyone trying to view the video on your site in IE would have to download and install the entire VLC player program to have it work in IE, and users probably don't want to do that. I can't get your code to work in firefox or IE8 on my boyfriends computer, although I might not have been putting the video address in properly... I get some message about no video output...

I'll take a guess and say it probably works for you locally because you have VLC installed, but your server doesn't. Unfortunately you'll probably have to use Windows media player or something similar (Microsoft is great at forcing people to use their stuff!)

And if you're wondering, it appears that the reason there is no cab file is because of the cost of having an active-x control signed.

It's rather simple to have your page use VLC for firefox and chrome users, and Windows Media Player for IE users, if that would work for you.

HTML5 Pre-resize images before uploading

Yes, use the File API, then you can process the images with the canvas element.

This Mozilla Hacks blog post walks you through most of the process. For reference here's the assembled source code from the blog post:

// from an input element
var filesToUpload = input.files;
var file = filesToUpload[0];

var img = document.createElement("img");
var reader = new FileReader();  
reader.onload = function(e) {img.src = e.target.result}
reader.readAsDataURL(file);

var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);

var MAX_WIDTH = 800;
var MAX_HEIGHT = 600;
var width = img.width;
var height = img.height;

if (width > height) {
  if (width > MAX_WIDTH) {
    height *= MAX_WIDTH / width;
    width = MAX_WIDTH;
  }
} else {
  if (height > MAX_HEIGHT) {
    width *= MAX_HEIGHT / height;
    height = MAX_HEIGHT;
  }
}
canvas.width = width;
canvas.height = height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0, width, height);

var dataurl = canvas.toDataURL("image/png");

//Post dataurl to the server with AJAX

How to get the command line args passed to a running process on unix/linux systems?

In addition to all the above ways to convert the text, if you simply use 'strings', it will make the output on separate lines by default. With the added benefit that it may also prevent any chars that may scramble your terminal from appearing.

Both output in one command:

strings /proc//cmdline /proc//environ

The real question is... is there a way to see the real command line of a process in Linux that has been altered so that the cmdline contains the altered text instead of the actual command that was run.

Oracle SQL - REGEXP_LIKE contains characters other than a-z or A-Z

if you want that not contains any of a-z and A-Z:

SELECT * FROM mytable WHERE NOT REGEXP_LIKE(column_1, '[A-Za-z]')

something like:

"98763045098" or "!%436%$7%$*#"

or other languages like persian, arabic and ... like this:

"???? ????"

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

I found the xmessage command, which is sort of good enough.

How do I read all classes from a Java package in the classpath?

If you have Spring in you classpath then the following will do it.

Find all classes in a package that are annotated with XmlRootElement:

private List<Class> findMyTypes(String basePackage) throws IOException, ClassNotFoundException
{
    ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
    MetadataReaderFactory metadataReaderFactory = new CachingMetadataReaderFactory(resourcePatternResolver);

    List<Class> candidates = new ArrayList<Class>();
    String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX +
                               resolveBasePackage(basePackage) + "/" + "**/*.class";
    Resource[] resources = resourcePatternResolver.getResources(packageSearchPath);
    for (Resource resource : resources) {
        if (resource.isReadable()) {
            MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(resource);
            if (isCandidate(metadataReader)) {
                candidates.add(Class.forName(metadataReader.getClassMetadata().getClassName()));
            }
        }
    }
    return candidates;
}

private String resolveBasePackage(String basePackage) {
    return ClassUtils.convertClassNameToResourcePath(SystemPropertyUtils.resolvePlaceholders(basePackage));
}

private boolean isCandidate(MetadataReader metadataReader) throws ClassNotFoundException
{
    try {
        Class c = Class.forName(metadataReader.getClassMetadata().getClassName());
        if (c.getAnnotation(XmlRootElement.class) != null) {
            return true;
        }
    }
    catch(Throwable e){
    }
    return false;
}

Open another page in php

Use the following code:

if(processing == success) {
  header("Location:filename");
  exit();
}

And you are good to go.

How to configure nginx to enable kinda 'file browser' mode?

1. List content of all directories

Set autoindex option to on. It is off by default.

Your configuration file ( vi /etc/nginx/sites-available/default ) should be like this

location /{ 
   ... ( some other lines )
   autoindex on;
   ... ( some other lines )
}

2. List content of only some specific directory

Set autoindex option to on. It is off by default.

Your configuration file ( vi /etc/nginx/sites-available/default )
should be like this.
change path_of_your_directory to your directory path

location /path_of_your_directory{ 
   ... ( some other lines )
   autoindex on;
   ... ( some other lines )
}

Hope it helps..

How to filter object array based on attributes?

You could do this pretty easily - there are probably many implementations you can choose from, but this is my basic idea (and there is probably some format where you can iterate over an object with jQuery, I just cant think of it right now):

function filter(collection, predicate)
{
    var result = new Array();
    var length = collection.length;

    for(var j = 0; j < length; j++)
    {
        if(predicate(collection[j]) == true)
        {
             result.push(collection[j]);
        }
    }

    return result;
}

And then you could invoke this function like so:

filter(json, function(element)
{
    if(element.price <= 1000 && element.sqft >= 500 && element.num_of_beds > 2 && element.num_of_baths > 2.5)
        return true;

    return false;
});

This way, you can invoke the filter based on whatever predicate you define, or even filter multiple times using smaller filters.

C++ static virtual members?

No, its not possible, since static members are bound at compile time, while virtual members are bound at runtime.

angularjs: ng-src equivalent for background-image:url(...)

just a matter of taste but if you prefer accessing the variable or function directly like this:

<div id="playlist-icon" back-img="playlist.icon">

instead of interpolating like this:

<div id="playlist-icon" back-img="{{playlist.icon}}">

then you can define the directive a bit differently with scope.$watch which will do $parse on the attribute

angular.module('myApp', [])
.directive('bgImage', function(){

    return function(scope, element, attrs) {
        scope.$watch(attrs.bgImage, function(value) {
            element.css({
                'background-image': 'url(' + value +')',
                'background-size' : 'cover'
            });
        });
    };
})

there is more background on this here: AngularJS : Difference between the $observe and $watch methods

jQuery validation: change default error message

Another possible solution is to loop over the fields, adding the same error message to each field.

$('.required').each(function(index) {
  $(this).rules("add", {
    messages: {
      required: "Custom error message."
   }
  });
});

How to compile C program on command line using MinGW?

You can permanently include the directory of the MinGW file, by clicking on My Computer, Properties, Advanced system settings, Environment variables, then edit and paste your directory.

python variable NameError

Initialize tSize to

tSize = ""  

before your if block to be safe. Also in your else case, put tSize in quotes so it is a string not an int. Also also you are comparing strings to ints.

How to strip HTML tags with jQuery?

Use the .text() function:

var text = $("<p> example ive got a string</P>").text();

Update: As Brilliand points out below, if the input string does not contain any tags and you are unlucky enough, it might be treated as a CSS selector. So this version is more robust:

var text = $("<div/>").html("<p> example ive got a string</P>").text();

Get string after character

Use parameter expansion, if the value is already stored in a variable.

$ str="GenFiltEff=7.092200e-01"
$ value=${str#*=}

Or use read

$ IFS="=" read name value <<< "GenFiltEff=7.092200e-01"

Either way,

$ echo $value
7.092200e-01

install apt-get on linux Red Hat server

I think you're running into problems because RedHat uses RPM for managing packages. Debian based systems use DEBs, which are managed with tools like apt.

jQuery serialize does not register checkboxes

A technique I've used in my own systems, and which I believe is employed by Struts, is to include...

<input type="hidden" name="_fieldname" value="fieldvalue"/> 

...immediately next to the checkbox as part of my form creation logic.

This allows me to reconstruct which checkboxes were served in the form but not selected, with a tiny bit of extra logic to do the diff what was served and what was checked, you have the ones which were unchecked. The submission is also the same in content regardless whether you're using HTML or AJAX style submission.

Depending on the technology you're using server-side then you may wish to use this syntax...

<input type="hidden" name="_fieldname[]" value="fieldvalue"/>

...to make it easy to grab these values as a list.

How to find a value in an excel column by vba code Cells.Find

I'd prefer to use the .Find method directly on a range object containing the range of cells to be searched. For original poster's code it might look like:

Set cell = ActiveSheet.Columns("B:B").Find( _
    What:=celda, _
    After:=ActiveCell _
    LookIn:=xlFormulas, _
    LookAt:=xlWhole, _
    SearchOrder:=xlByRows, _
    SearchDirection:=xlNext, _
    MatchCase:=False, _
    SearchFormat:=False _
)

If cell Is Nothing Then
    'do something
Else
    'do something else
End If

I'd prefer to use more variables (and be sure to declare them) and let a lot of optional arguments use their default values:

Dim rng as Range
Dim cell as Range
Dim search as String

Set rng = ActiveSheet.Columns("B:B")
search = "String to Find"
Set cell = rng.Find(What:=search, LookIn:=xlFormulas, LookAt:=xlWhole, MatchCase:=False)

If cell Is Nothing Then
    'do something
Else
    'do something else
End If

I kept LookIn:=, LookAt::=, and MatchCase:= to be explicit about what is being matched. The other optional parameters control the order matches are returned in - I'd only specify those if the order is important to my application.

Python argparse command line flags without arguments

Adding a quick snippet to have it ready to execute:

Source: myparser.py

import argparse
parser = argparse.ArgumentParser(description="Flip a switch by setting a flag")
parser.add_argument('-w', action='store_true')

args = parser.parse_args()
print args.w

Usage:

python myparser.py -w
>> True

Numpy converting array from float to strings

You seem a bit confused as to how numpy arrays work behind the scenes. Each item in an array must be the same size.

The string representation of a float doesn't work this way. For example, repr(1.3) yields '1.3', but repr(1.33) yields '1.3300000000000001'.

A accurate string representation of a floating point number produces a variable length string.

Because numpy arrays consist of elements that are all the same size, numpy requires you to specify the length of the strings within the array when you're using string arrays.

If you use x.astype('str'), it will always convert things to an array of strings of length 1.

For example, using x = np.array(1.344566), x.astype('str') yields '1'!

You need to be more explict and use the '|Sx' dtype syntax, where x is the length of the string for each element of the array.

For example, use x.astype('|S10') to convert the array to strings of length 10.

Even better, just avoid using numpy arrays of strings altogether. It's usually a bad idea, and there's no reason I can see from your description of your problem to use them in the first place...

How do I delete an item or object from an array using ng-click?

Building on the accepted answer, this will work with ngRepeat, filterand handle expections better:

Controller:

vm.remove = function(item, array) {
  var index = array.indexOf(item);
  if(index>=0)
    array.splice(index, 1);
}

View:

ng-click="vm.remove(item,$scope.bdays)"

Generating PDF files with JavaScript

Another interesting project is texlive.js.

It allows you to compile (La)TeX to PDF in the browser.

List file names based on a filename pattern and file content?

Grep DOES NOT use "wildcards" for search – that's shell globbing, like *.jpg. Grep uses "regular expressions" for pattern matching. While in the shell '*' means "anything", in grep it means "match the previous item zero or more times".

More information and examples here: http://www.regular-expressions.info/reference.html

To answer of your question - you can find files matching some pattern with grep:

find /somedir -type f -print | grep 'LMN2011' # that will show files whose names contain LMN2011

Then you can search their content (case insensitive):

find /somedir -type f -print | grep -i 'LMN2011' | xargs grep -i 'LMN20113456'

If the paths can contain spaces, you should use the "zero end" feature:

find /somedir -type f -print0 | grep -iz 'LMN2011' | xargs -0 grep -i 'LMN20113456'

How to use querySelectorAll only for elements that have a specific attribute set?

You can use querySelectorAll() like this:

var test = document.querySelectorAll('input[value][type="checkbox"]:not([value=""])');

This translates to:

get all inputs with the attribute "value" and has the attribute "value" that is not blank.

In this demo, it disables the checkbox with a non-blank value.

Pass Parameter to Gulp Task

@Ethan's answer would completely work. From my experience, the more node way is to use environment variables. It's a standard way to configure programs deployed on hosting platforms (e.g. Heroku or Dokku).

To pass the parameter from the command line, do it like this:

Development: gulp dev

Production: NODE_ENV=production gulp dev

The syntax is different, but very Unix, and it's compatible with Heroku, Dokku, etc.

You can access the variable in your code at process.env.NODE_ENV

MYAPP=something_else gulp dev

would set

process.env.MYAPP === 'something_else'

This answer might give you some other ideas.

Correct way to select from two tables in SQL Server with no common field to join on

A suggestion - when using cross join please take care of the duplicate scenarios. For example in your case:

  • Table 1 may have >1 columns as part of primary keys(say table1_id, id2, id3, table2_id)
  • Table 2 may have >1 columns as part of primary keys(say table2_id, id3, id4)

since there are common keys between these two tables (i.e. foreign keys in one/other) - we will end up with duplicate results. hence using the following form is good:

WITH data_mined_table (col1, col2, col3, etc....) AS
SELECT DISTINCT col1, col2, col3, blabla
FROM table_1 (NOLOCK), table_2(NOLOCK))
SELECT * from data_mined WHERE data_mined_table.col1 = :my_param_value

How to inflate one view with a layout

Though late answer, but would like to add that one way to get this

LayoutInflater layoutInflater = (LayoutInflater)this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View view = layoutInflater.inflate(R.layout.mylayout, item );

where item is the parent layout where you want to add a child layout.

javascript: get a function's variable's value within another function

Your nameContent variable is inside the function scope and not visible outside that function so if you want to use the nameContent outside of the function then declare it global inside the <script> tag and use inside functions without the var keyword as follows

<script language="javascript" type="text/javascript">
    var nameContent; // In the global scope
    function first(){
        nameContent=document.getElementById('full_name').value;
    }

    function second() {
        first();
        y=nameContent; 
        alert(y);
    }
    second();
</script>

How to convert a byte to its binary string representation

Use Integer#toBinaryString():

byte b1 = (byte) 129;
String s1 = String.format("%8s", Integer.toBinaryString(b1 & 0xFF)).replace(' ', '0');
System.out.println(s1); // 10000001

byte b2 = (byte) 2;
String s2 = String.format("%8s", Integer.toBinaryString(b2 & 0xFF)).replace(' ', '0');
System.out.println(s2); // 00000010

DEMO.

start MySQL server from command line on Mac OS Lion

On mac Big Sur and MySQL 5.7, I needed to stop/start with:

sudo launchctl load -F /Library/LaunchDaemons/com.oracle.oss.mysql.mysqld.plist

and

sudo launchctl unload -F /Library/LaunchDaemons/com.oracle.oss.mysql.mysqld.plist

This answer came from https://coolestguidesontheplanet.com/start-stop-mysql-from-the-command-line-terminal-osx-linux/

Comparing two NumPy arrays for equality, element-wise

Usually two arrays will have some small numeric errors,

You can use numpy.allclose(A,B), instead of (A==B).all(). This returns a bool True/False

How to assign colors to categorical variables in ggplot2 that have stable mapping?

This is an old post, but I was looking for answer to this same question,

Why not try something like:

scale_color_manual(values = c("foo" = "#999999", "bar" = "#E69F00"))

If you have categorical values, I don't see a reason why this should not work.

Open File Dialog, One Filter for Multiple Excel Extensions?

Use a semicolon

OpenFileDialog of = new OpenFileDialog();
of.Filter = "Excel Files|*.xls;*.xlsx;*.xlsm";

String replacement in java, similar to a velocity template

I threw together a small test implementation of this. The basic idea is to call format and pass in the format string, and a map of objects, and the names that they have locally.

The output of the following is:

My dog is named fido, and Jane Doe owns him.

public class StringFormatter {

    private static final String fieldStart = "\\$\\{";
    private static final String fieldEnd = "\\}";

    private static final String regex = fieldStart + "([^}]+)" + fieldEnd;
    private static final Pattern pattern = Pattern.compile(regex);

    public static String format(String format, Map<String, Object> objects) {
        Matcher m = pattern.matcher(format);
        String result = format;
        while (m.find()) {
            String[] found = m.group(1).split("\\.");
            Object o = objects.get(found[0]);
            Field f = o.getClass().getField(found[1]);
            String newVal = f.get(o).toString();
            result = result.replaceFirst(regex, newVal);
        }
        return result;
    }

    static class Dog {
        public String name;
        public String owner;
        public String gender;
    }

    public static void main(String[] args) {
        Dog d = new Dog();
        d.name = "fido";
        d.owner = "Jane Doe";
        d.gender = "him";
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("d", d);
        System.out.println(
           StringFormatter.format(
                "My dog is named ${d.name}, and ${d.owner} owns ${d.gender}.", 
                map));
    }
}

Note: This doesn't compile due to unhandled exceptions. But it makes the code much easier to read.

Also, I don't like that you have to construct the map yourself in the code, but I don't know how to get the names of the local variables programatically. The best way to do it, is to remember to put the object in the map as soon as you create it.

The following example produces the results that you want from your example:

public static void main(String[] args) {
    Map<String, Object> map = new HashMap<String, Object>();
    Site site = new Site();
    map.put("site", site);
    site.name = "StackOverflow.com";
    User user = new User();
    map.put("user", user);
    user.name = "jjnguy";
    System.out.println(
         format("Hello ${user.name},\n\tWelcome to ${site.name}. ", map));
}

I should also mention that I have no idea what Velocity is, so I hope this answer is relevant.

Reading numbers from a text file into an array in C

There are two problems in your code:

  • the return value of scanf must be checked
  • the %d conversion does not take overflows into account (blindly applying *10 + newdigit for each consecutive numeric character)

The first value you got (-104204697) is equals to 5623125698541159 modulo 2^32; it is thus the result of an overflow (if int where 64 bits wide, no overflow would happen). The next values are uninitialized (garbage from the stack) and thus unpredictable.

The code you need could be (similar to the answer of BLUEPIXY above, with the illustration how to check the return value of scanf, the number of items successfully matched):

#include <stdio.h>

int main(int argc, char *argv[]) {
    int i, j;
    short unsigned digitArray[16];
    i = 0;
    while (
        i != sizeof(digitArray) / sizeof(digitArray[0])
     && 1 == scanf("%1hu", digitArray + i)
    ) {
        i++;
    }
    for (j = 0; j != i; j++) {
        printf("%hu\n", digitArray[j]);
    }
    return 0;
}

$.focus() not working

In my case, and in case someone else runs into this, I load a form for view, user clicks "Edit" and ajax gets & returns values and updates the form.

Just after this, I tried all of these and none worked except:

setTimeout(function() { $('input[name="q"]').focus() }, 3000);

which I had to change to (due to ajax):

setTimeout(function() { $('input[name="q"]').focus() }, **500**);

and I finally just used $("#q") even though it was an input:

setTimeout(function () { $("#q").focus() }, 500);

Search for a string in Enum and return the Enum

Given the latest and greatest changes to .NET (+ Core) and C# 7, here is the best solution:

var ignoreCase = true;
Enum.TryParse("red", ignoreCase , out MyColours colour);

colour variable can be used within the scope of Enum.TryParse

How to pass datetime from c# to sql correctly?

You've already done it correctly by using a DateTime parameter with the value from the DateTime, so it should already work. Forget about ToString() - since that isn't used here.

If there is a difference, it is most likely to do with different precision between the two environments; maybe choose a rounding (seconds, maybe?) and use that. Also keep in mind UTC/local/unknown (the DB has no concept of the "kind" of date; .NET does).

I have a table and the date-times in it are in the format: 2011-07-01 15:17:33.357

Note that datetimes in the database aren't in any such format; that is just your query-client showing you white lies. It is stored as a number (and even that is an implementation detail), because humans have this odd tendency not to realise that the date you've shown is the same as 40723.6371916281. Stupid humans. By treating it simply as a "datetime" throughout, you shouldn't get any problems.

React-router v4 this.props.history.push(...) not working

You need to export the Customers Component not the CustomerList.

    CustomersList = withRouter(Customers);
    export default CustomersList;

ImportError: No module named 'encodings'

In my case just changing the permissions of anaconda folder worked:

sudo chmod -R u=rwx,g=rx,o=rx /path/to/anaconda   

Uncaught TypeError: undefined is not a function while using jQuery UI

And if you have this problem in slider or slideshow you must use jquery.easing.1.3:

<script src="http://gsgd.co.uk/sandbox/jquery/easing/jquery.easing.1.3.js"></script>

Error Code: 1062. Duplicate entry '1' for key 'PRIMARY'

Also check your triggers.

Encountered this with a history table trigger which tried to insert the main table id into the history table id instead of the correct hist-table.source_id column.

The update statement did not touch the id column at all so took some time to find:

UPDATE source_table SET status = 0;

The trigger tried to do something similar to this:

FOR EACH ROW
BEGIN
    INSERT INTO `history_table` (`action`,`id`,`status`,`time_created`)
    VALUES('update', NEW.id, NEW.status, NEW.time_created);
END;

Was corrected to something like this:

FOR EACH ROW
BEGIN
    INSERT INTO `history_table` (`action`,`source_id`,`status`,`time_created`)
    VALUES('update', NEW.id, NEW.status, NEW.time_created);
END;

Min and max value of input in angular4 application

If you are looking to validate length use minLength and maxLength instead.

Develop Android app using C#

You could use Mono for Android:

http://xamarin.com/monoforandroid

An alternative is dot42:

http://www.dot42.com/

dot42 provides a free community licence as well as a professional licence for $399.

illegal character in path

Your path includes " at the beginning and at the end. Drop the quotes, and it'll be ok.

The \" at the beginning and end of what you see in VS Debugger is what tells us that the quotes are literally in the string.

Convert hexadecimal string (hex) to a binary string

public static byte[] hexToBin(String str)
    {
        int len = str.length();
        byte[] out = new byte[len / 2];
        int endIndx;

        for (int i = 0; i < len; i = i + 2)
        {
            endIndx = i + 2;
            if (endIndx > len)
                endIndx = len - 1;
            out[i / 2] = (byte) Integer.parseInt(str.substring(i, endIndx), 16);
        }
        return out;
    }

Storing an object in state of a React component?

Easier way to do it in one line of code

this.setState({ object: { ...this.state.object, objectVarToChange: newData } })

How to read file with async/await properly?

To use await/async you need methods that return promises. The core API functions don't do that without wrappers like promisify:

const fs = require('fs');
const util = require('util');

// Convert fs.readFile into Promise version of same    
const readFile = util.promisify(fs.readFile);

function getStuff() {
  return readFile('test');
}

// Can't use `await` outside of an async function so you need to chain
// with then()
getStuff().then(data => {
  console.log(data);
})

As a note, readFileSync does not take a callback, it returns the data or throws an exception. You're not getting the value you want because that function you supply is ignored and you're not capturing the actual return value.

Set cellpadding and cellspacing in CSS?

You can easily set padding inside the table cells using the CSS padding property. It is a valid way to produce the same effect as the table's cellpadding attribute.

_x000D_
_x000D_
table,_x000D_
th,_x000D_
td {_x000D_
  border: 1px solid #666;_x000D_
}_x000D_
_x000D_
table th,_x000D_
table td {_x000D_
  padding: 10px;_x000D_
  /* Apply cell padding */_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
<head>_x000D_
_x000D_
  <meta charset="utf-8">_x000D_
  <title>Set Cellpadding in CSS</title>_x000D_
_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
_x000D_
  <table>_x000D_
    <thead>_x000D_
      <tr>_x000D_
        <th>Row</th>_x000D_
        <th>First Name</th>_x000D_
        <th>Last Name</th>_x000D_
        <th>Email</th>_x000D_
      </tr>_x000D_
    </thead>_x000D_
    <tbody>_x000D_
      <tr>_x000D_
        <td>1</td>_x000D_
        <td>Clark</td>_x000D_
        <td>Kent</td>_x000D_
        <td>[email protected]</td>_x000D_
      </tr>_x000D_
      <tr>_x000D_
        <td>2</td>_x000D_
        <td>Peter</td>_x000D_
        <td>Parker</td>_x000D_
        <td>[email protected]</td>_x000D_
      </tr>_x000D_
      <tr>_x000D_
        <td>3</td>_x000D_
        <td>John</td>_x000D_
        <td>Rambo</td>_x000D_
        <td>[email protected]</td>_x000D_
      </tr>_x000D_
    </tbody>_x000D_
  </table>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Similarly, you can use the CSS border-spacing property to apply the spacing between adjacent table cell borders like the cellspacing attribute. However, in order to work border-spacing the value of border-collapse property muse be separate, which is default.

_x000D_
_x000D_
table {_x000D_
  border-collapse: separate;_x000D_
  border-spacing: 10px;_x000D_
  /* Apply cell spacing */_x000D_
}_x000D_
_x000D_
table,_x000D_
th,_x000D_
td {_x000D_
  border: 1px solid #666;_x000D_
}_x000D_
_x000D_
table th,_x000D_
table td {_x000D_
  padding: 5px;_x000D_
  /* Apply cell padding */_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
<head>_x000D_
_x000D_
  <meta charset="utf-8">_x000D_
  <title>Set Cellspacing in CSS</title>_x000D_
_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
_x000D_
  <table>_x000D_
    <thead>_x000D_
      <tr>_x000D_
        <th>Row</th>_x000D_
        <th>First Name</th>_x000D_
        <th>Last Name</th>_x000D_
        <th>Email</th>_x000D_
      </tr>_x000D_
    </thead>_x000D_
    <tbody>_x000D_
      <tr>_x000D_
        <td>1</td>_x000D_
        <td>Clark</td>_x000D_
        <td>Kent</td>_x000D_
        <td>[email protected]</td>_x000D_
      </tr>_x000D_
      <tr>_x000D_
        <td>2</td>_x000D_
        <td>Peter</td>_x000D_
        <td>Parker</td>_x000D_
        <td>[email protected]</td>_x000D_
      </tr>_x000D_
      <tr>_x000D_
        <td>3</td>_x000D_
        <td>John</td>_x000D_
        <td>Rambo</td>_x000D_
        <td>[email protected]</td>_x000D_
      </tr>_x000D_
    </tbody>_x000D_
  </table>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Shell script - remove first and last quote (") from a variable

I know this is a very old question, but here is another sed variation, which may be useful to someone. Unlike some of the others, it only replaces double quotes at the start or end...

echo "$opt" | sed -r 's/^"|"$//g'

What is the meaning of polyfills in HTML5?

First off let's clarify what a polyfil is not: A polyfill is not part of the HTML5 Standard. Nor is a polyfill limited to Javascript, even though you often see polyfills being referred to in those contexts.

The term polyfill itself refers to some code that "allows you to have some specific functionality that you expect in current or “modern” browsers to also work in other browsers that do not have the support for that functionality built in. "

Source and example of polyfill here:

http://www.programmerinterview.com/index.php/html5/html5-polyfill/

ApiNotActivatedMapError for simple html page using google-places-api

as of Jan 2017, unfortunately @Adi's answer, while it seems like it should work, does not. (Google's API key process is buggy)

you'll need to click "get a key" from this link: https://developers.google.com/maps/documentation/javascript/get-api-key

also I strongly recommend you don't ever choose "secure key" until you are ready to switch to production. I did http referrer restrictions on a key and afterwards was unable to get it working with localhost, even after disabling security for the key. I had to create a new key for it to work again.

How to download HTTP directory with all files and sub-directories as they appear on the online files/folders list?

you can use lftp, the swish army knife of downloading if you have bigger files you can add --use-pget-n=10 to command

lftp -c 'mirror --parallel=100 https://example.com/files/ ;exit'

Fit image into ImageView, keep aspect ratio and then resize ImageView to image dimensions?

I needed to have an ImageView and an Bitmap, so the Bitmap is scaled to ImageView size, and size of the ImageView is the same of the scaled Bitmap :).

I was looking through this post for how to do it, and finally did what I want, not the way described here though.

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/acpt_frag_root"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/imageBackground"
android:orientation="vertical">

<ImageView
    android:id="@+id/acpt_image"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:adjustViewBounds="true"
    android:layout_margin="@dimen/document_editor_image_margin"
    android:background="@color/imageBackground"
    android:elevation="@dimen/document_image_elevation" />

and then in onCreateView method

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

    View view = inflater.inflate(R.layout.fragment_scanner_acpt, null);

    progress = view.findViewById(R.id.progress);

    imageView = view.findViewById(R.id.acpt_image);
    imageView.setImageBitmap( bitmap );

    imageView.getViewTreeObserver().addOnGlobalLayoutListener(()->
        layoutImageView()
    );

    return view;
}

and then layoutImageView() code

private void layoutImageView(){

    float[] matrixv = new float[ 9 ];

    imageView.getImageMatrix().getValues(matrixv);

    int w = (int) ( matrixv[Matrix.MSCALE_X] * bitmap.getWidth() );
    int h = (int) ( matrixv[Matrix.MSCALE_Y] * bitmap.getHeight() );

    imageView.setMaxHeight(h);
    imageView.setMaxWidth(w);

}

And the result is that image fits inside perfectly, keeping aspect ratio, and doesn't have extra leftover pixels from ImageView when the Bitmap is inside.

Result

It's important ImageView to have wrap_content and adjustViewBounds to true, then setMaxWidth and setMaxHeight will work, this is written in the source code of ImageView,

/*An optional argument to supply a maximum height for this view. Only valid if
 * {@link #setAdjustViewBounds(boolean)} has been set to true. To set an image to be a
 * maximum of 100 x 100 while preserving the original aspect ratio, do the following: 1) set
 * adjustViewBounds to true 2) set maxWidth and maxHeight to 100 3) set the height and width
 * layout params to WRAP_CONTENT. */

How can I toggle word wrap in Visual Studio?

Use menu Edit ? Advanced ? Word Wrap in Visual Studio 2003.

Hash function that produces short hashes?

I needed something along the lines of a simple string reduction function recently. Basically, the code looked something like this (C/C++ code ahead):

size_t ReduceString(char *Dest, size_t DestSize, const char *Src, size_t SrcSize, bool Normalize)
{
    size_t x, x2 = 0, z = 0;

    memset(Dest, 0, DestSize);

    for (x = 0; x < SrcSize; x++)
    {
        Dest[x2] = (char)(((unsigned int)(unsigned char)Dest[x2]) * 37 + ((unsigned int)(unsigned char)Src[x]));
        x2++;

        if (x2 == DestSize - 1)
        {
            x2 = 0;
            z++;
        }
    }

    // Normalize the alphabet if it looped.
    if (z && Normalize)
    {
        unsigned char TempChr;
        y = (z > 1 ? DestSize - 1 : x2);
        for (x = 1; x < y; x++)
        {
            TempChr = ((unsigned char)Dest[x]) & 0x3F;

            if (TempChr < 10)  TempChr += '0';
            else if (TempChr < 36)  TempChr = TempChr - 10 + 'A';
            else if (TempChr < 62)  TempChr = TempChr - 36 + 'a';
            else if (TempChr == 62)  TempChr = '_';
            else  TempChr = '-';

            Dest[x] = (char)TempChr;
        }
    }

    return (SrcSize < DestSize ? SrcSize : DestSize);
}

It probably has more collisions than might be desired but it isn't intended for use as a cryptographic hash function. You might try various multipliers (i.e. change the 37 to another prime number) if you get too many collisions. One of the interesting features of this snippet is that when Src is shorter than Dest, Dest ends up with the input string as-is (0 * 37 + value = value). If you want something "readable" at the end of the process, Normalize will adjust the transformed bytes at the cost of increasing collisions.

Source:

https://github.com/cubiclesoft/cross-platform-cpp/blob/master/sync/sync_util.cpp

How to control the width of select tag?

You've simply got it backwards. Specifying a minimum width would make the select menu always be at least that width, so it will continue expanding to 90% no matter what the window size is, also being at least the size of its longest option.

You need to use max-width instead. This way, it will let the select menu expand to its longest option, but if that expands past your set maximum of 90% width, crunch it down to that width.

C# Clear all items in ListView

Just use the clear method is works like a charm. ListView1.Items.Clear() i think if its not working it may be the position whereby you place this code. Also can try nullifying the datasource.

How to convert int to string on Arduino?

This is speed-optimized solution for converting int (signed 16-bit integer) into string.

This implementation avoids using division since 8-bit AVR used for Arduino has no hardware DIV instruction, the compiler translate division into time-consuming repetitive subtractions. Thus the fastest solution is using conditional branches to build the string.

A fixed 7 bytes buffer prepared from beginning in RAM to avoid dynamic allocation. Since it's only 7 bytes, the cost of fixed RAM usage is considered minimum. To assist compiler, we add register modifier into variable declaration to speed-up execution.

char _int2str[7];
char* int2str( register int i ) {
  register unsigned char L = 1;
  register char c;
  register boolean m = false;
  register char b;  // lower-byte of i
  // negative
  if ( i < 0 ) {
    _int2str[ 0 ] = '-';
    i = -i;
  }
  else L = 0;
  // ten-thousands
  if( i > 9999 ) {
    c = i < 20000 ? 1
      : i < 30000 ? 2
      : 3;
    _int2str[ L++ ] = c + 48;
    i -= c * 10000;
    m = true;
  }
  // thousands
  if( i > 999 ) {
    c = i < 5000
      ? ( i < 3000
          ? ( i < 2000 ? 1 : 2 )
          :   i < 4000 ? 3 : 4
        )
      : i < 8000
        ? ( i < 6000
            ? 5
            : i < 7000 ? 6 : 7
          )
        : i < 9000 ? 8 : 9;
    _int2str[ L++ ] = c + 48;
    i -= c * 1000;
    m = true;
  }
  else if( m ) _int2str[ L++ ] = '0';
  // hundreds
  if( i > 99 ) {
    c = i < 500
      ? ( i < 300
          ? ( i < 200 ? 1 : 2 )
          :   i < 400 ? 3 : 4
        )
      : i < 800
        ? ( i < 600
            ? 5
            : i < 700 ? 6 : 7
          )
        : i < 900 ? 8 : 9;
    _int2str[ L++ ] = c + 48;
    i -= c * 100;
    m = true;
  }
  else if( m ) _int2str[ L++ ] = '0';
  // decades (check on lower byte to optimize code)
  b = char( i );
  if( b > 9 ) {
    c = b < 50
      ? ( b < 30
          ? ( b < 20 ? 1 : 2 )
          :   b < 40 ? 3 : 4
        )
      : b < 80
        ? ( i < 60
            ? 5
            : i < 70 ? 6 : 7
          )
        : i < 90 ? 8 : 9;
    _int2str[ L++ ] = c + 48;
    b -= c * 10;
    m = true;
  }
  else if( m ) _int2str[ L++ ] = '0';
  // last digit
  _int2str[ L++ ] = b + 48;
  // null terminator
  _int2str[ L ] = 0;  
  return _int2str;
}

// Usage example:
int i = -12345;
char* s;
void setup() {
  s = int2str( i );
}
void loop() {}

This sketch is compiled to 1,082 bytes of code using avr-gcc which bundled with Arduino v1.0.5 (size of int2str function itself is 594 bytes). Compared with solution using String object which compiled into 2,398 bytes, this implementation can reduce your code size by 1.2 Kb (assumed that you need no other String's object method, and your number is strict to signed int type).

This function can be optimized further by writing it in proper assembler code.

Google Maps API throws "Uncaught ReferenceError: google is not defined" only when using AJAX

Uncaught ReferenceError: google is not defined error will be gone when removed the async defer from the map API script tag.

How do I read the source code of shell commands?

Actually more sane sources are provided by http://suckless.org look at their sbase repository:

git clone git://git.suckless.org/sbase

They are clearer, smarter, simpler and suckless, eg ls.c has just 369 LOC

After that it will be easier to understand more complicated GNU code.

Enabling/Disabling Microsoft Virtual WiFi Miniport

In the device manager you can select View > Show hidden devices

How to configure port for a Spring Boot application

In the application.properties file, add this line:

server.port = 65535

where to place that fie:

24.3 Application Property Files

SpringApplication loads properties from application.properties files in the following locations and adds them to the Spring Environment:

A /config subdirectory of the current directory
The current directory
A classpath /config package
The classpath root

The list is ordered by precedence (properties defined in locations higher in the list override those defined in lower locations).

In my case I put it in the directory where the jar file stands.

From:

https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#boot-features-external-config-application-property-files

Check if value is zero or not null in python

You can check if it can be converted to decimal. If yes, then its a number

from decimal import Decimal

def is_number(value):
    try:
        value = Decimal(value)
        return True
    except:
        return False

print is_number(None)   // False
print is_number(0)      // True
print is_number(2.3)    // True
print is_number('2.3')  // True (caveat!)

Passing parameters on button action:@selector

You can sub-class a UIButton named MyButton, and pass the parameter by MyButton's properties.

Then, get the parameter back from (id)sender.

Spring MVC UTF-8 Encoding

Depending on how you render your view, you may also need:

@Bean
public StringHttpMessageConverter stringHttpMessageConverter() {
    return new StringHttpMessageConverter(Charset.forName("UTF-8"));
}

How to print star pattern in JavaScript in a very simple manner?

Here is the solution in javascript while loop:

> var i = 0, out = '';
>  while( i <= 4)
>     {
>       out = out + '* ';
>       document.write('<br> '+ out);
>       i++;
>     } 
>  
> document.write('<br>');

Strange "java.lang.NoClassDefFoundError" in Eclipse

I had a similar problem and it had to do with the libraries referenced by the java build path; I was referencing libraries that didn't exist anymore when I did an update. When I removed these references, by project started running again.

The libraries are listed under the Java Build Path in the project properties window.

Hope this helps.

How do I specify the JDK for a GlassFish domain?

Here you can find how to set path to JDK for Glassfish: http://www.devdaily.com/blog/post/java/fixing-glassfish-jdk-path-problem-solved

Check

glassfish\config\asenv.bat

where java path is configured

REM set AS_JAVA=C:\Program Files\Java\jdk1.6.0_04\jre/..
set AS_JAVA=C:\Program Files\Java\jdk1.5.0_16

Add timer to a Windows Forms application

Download http://download.cnet.com/Free-Desktop-Timer/3000-2350_4-75415517.html

Then add a button or something on the form and inside its event, just open this app ie:

{

Process.Start(@"C:\Program Files (x86)\Free Desktop Timer\DesktopTimer");

}

php, mysql - Too many connections to database error

This can happen due to too many connection same time or many chat at same time. Also it can happen due too many session.

The best way to sort out this issue is restart MySQL.

service mysqld restart

or

service mysql restart

or

 /etc/init.d/mysqld restart

Decreasing for loops in Python impossible?

For python3 where -1 indicate the value that to be decremented in each step for n in range(6,0,-1): print(n)

Combining paste() and expression() functions in plot labels

An alternative solution to that of @Aaron is the bquote() function. We need to supply a valid R expression, in this case LABEL ~ x^2 for example, where LABEL is the string you want to assign from the vector labNames. bquote evaluates R code within the expression wrapped in .( ) and subsitutes the result into the expression.

Here is an example:

labNames <- c('xLab','yLab')
xlab <- bquote(.(labNames[1]) ~ x^2)
ylab <- bquote(.(labNames[2]) ~ y^2)
plot(c(1:10), xlab = xlab, ylab = ylab)

(Note the ~ just adds a bit of spacing, if you don't want the space, replace it with * and the two parts of the expression will be juxtaposed.)

Spring MVC: difference between <context:component-scan> and <annotation-driven /> tags?

<mvc:annotation-driven /> means that you can define spring beans dependencies without actually having to specify a bunch of elements in XML or implement an interface or extend a base class. For example @Repository to tell spring that a class is a Dao without having to extend JpaDaoSupport or some other subclass of DaoSupport. Similarly @Controller tells spring that the class specified contains methods that will handle Http requests without you having to implement the Controller interface or extend a subclass that implements the controller.

When spring starts up it reads its XML configuration file and looks for <bean elements within it if it sees something like <bean class="com.example.Foo" /> and Foo was marked up with @Controller it knows that the class is a controller and treats it as such. By default, Spring assumes that all the classes it should manage are explicitly defined in the beans.XML file.

Component scanning with <context:component-scan base-package="com.mycompany.maventestwebapp" /> is telling spring that it should search the classpath for all the classes under com.mycompany.maventestweapp and look at each class to see if it has a @Controller, or @Repository, or @Service, or @Component and if it does then Spring will register the class with the bean factory as if you had typed <bean class="..." /> in the XML configuration files.

In a typical spring MVC app you will find that there are two spring configuration files, a file that configures the application context usually started with the Spring context listener.

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

And a Spring MVC configuration file usually started with the Spring dispatcher servlet. For example.

<servlet>
        <servlet-name>main</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>main</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

Spring has support for hierarchical bean factories, so in the case of the Spring MVC, the dispatcher servlet context is a child of the main application context. If the servlet context was asked for a bean called "abc" it will look in the servlet context first, if it does not find it there it will look in the parent context, which is the application context.

Common beans such as data sources, JPA configuration, business services are defined in the application context while MVC specific configuration goes not the configuration file associated with the servlet.

Hope this helps.

Where is the kibana error log? Is there a kibana error log?

In kibana 4.0.2 there is no --log-file option. If I start kibana as a service with systemctl start kibana I find log in /var/log/messages

jQuery UI autocomplete with item and id

I've tried above code displaying (value or ID) in text-box insted of Label text. After that I've tried event.preventDefault() it's working perfectly...

var e = [{"label":"PHP","value":"1"},{"label":"Java","value":"2"}]

$(".jquery-autocomplete").autocomplete({
    source: e,select: function( event, ui ) {
        event.preventDefault();
        $('.jquery-autocomplete').val(ui.item.label);
        console.log(ui.item.label);
        console.log(ui.item.value);
    }
});

Groovy Shell warning "Could not open/create prefs root node ..."

I was getting the following message:

Could not open/create prefs root node Software\JavaSoft\Prefs at root 0x80000002

and it was gone after creating one of these registry keys, mine is 64 bit so I tried only that.

32 bit Windows
HKEY_LOCAL_MACHINE\Software\JavaSoft\Prefs

64 bit Windows
HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\JavaSoft\Prefs

Jquery each - Stop loop and return object

"We can break the $.each() loop at a particular iteration by making the callback function return false. Returning non-false is the same as a continue statement in a for loop; it will skip immediately to the next iteration."

from http://api.jquery.com/jquery.each/

Yea, this is old BUT, JUST to answer the question, this can be a bit simpler:

_x000D_
_x000D_
function findXX(word) {_x000D_
  $.each(someArray, function(index, value) {_x000D_
    $('body').append('-> ' + index + ":" + value + '<br />');_x000D_
    return !(value == word);_x000D_
  });_x000D_
}_x000D_
$(function() {_x000D_
  someArray = new Array();_x000D_
  someArray[0] = 't5';_x000D_
  someArray[1] = 'z12';_x000D_
  someArray[2] = 'b88';_x000D_
  someArray[3] = 's55';_x000D_
  someArray[4] = 'e51';_x000D_
  someArray[5] = 'o322';_x000D_
  someArray[6] = 'i22';_x000D_
  someArray[7] = 'k954';_x000D_
  findXX('o322');_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

A bit more with comments:

_x000D_
_x000D_
function findXX(myA, word) {_x000D_
  let br = '<br />';//create once_x000D_
  let myHolder = $("<div />");//get a holder to not hit DOM a lot_x000D_
  let found = false;//default return_x000D_
  $.each(myA, function(index, value) {_x000D_
    found = (value == word);_x000D_
    myHolder.append('-> ' + index + ":" + value + br);_x000D_
    return !found;_x000D_
  });_x000D_
  $('body').append(myHolder.html());// hit DOM once_x000D_
  return found;_x000D_
}_x000D_
$(function() {_x000D_
  // no horrid global array, easier array setup;_x000D_
  let someArray = ['t5', 'z12', 'b88', 's55', 'e51', 'o322', 'i22', 'k954'];_x000D_
  // pass the array and the value we want to find, return back a value_x000D_
  let test = findXX(someArray, 'o322');_x000D_
  $('body').append("<div>Found:" + test + "</div>");_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

NOTE: array .includes() may better suit here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes

Or just .find() to get that https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find

Can we open pdf file using UIWebView on iOS?

WKWebView: I find this question to be the best place to let people know that they should start using WKWebview as UIWebView is now deprecated.

Objective C

WKWebView *webView = [[WKWebView alloc] initWithFrame:self.view.frame];
webView.navigationDelegate = self;
NSURL *nsurl=[NSURL URLWithString:@"https://www.example.com/document.pdf"];
NSURLRequest *nsrequest=[NSURLRequest requestWithURL:nsurl];
[webView loadRequest:nsrequest];
[self.view addSubview:webView];

Swift

let myURLString = "https://www.example.com/document.pdf"
let url = NSURL(string: myURLString)
let request = NSURLRequest(URL: url!)  
let webView = WKWebView(frame: self.view.frame)
webView.navigationDelegate = self
webView.loadRequest(request)
view.addSubview(webView)

I haven't copied this code directly from Xcode, so it might, it might contain some syntax error. Please check while using it.

React hooks useState Array

Try to keep your state minimal. There is no need to store

   const initialValue = [
    { id: 0,value: " --- Select a State ---" }];

as state. Separate the permanent from the changing

const ALL_STATE_VALS = [
    { id: 0,value: " --- Select a State ---" }
    { id: 1, value: "Alabama" },
    { id: 2, value: "Georgia" },
    { id: 3, value: "Tennessee" }
];

Then you can store just the id as your state:

const StateSelector = () =>{
  const [selectedStateOption, setselectedStateOption] = useState(0);

  return (
    <div>
      <label>Select a State:</label>
      <select>
        {ALL_STATE_VALS.map((option, index) => (
          <option key={option.id} selected={index===selectedStateOption}>{option.value}</option>
        ))}
      </select>
    </div>);
   )
}

Returning data from Axios API

I know this post is old. But i have seen several attempts of guys trying to answer using async and await but getting it wrong. This should clear it up for any new references

async function axiosTest() {
      try {
        const {data:response} = await axios.get(url) //use data destructuring to get data from the promise object
        return response
      }

      catch (error) {
        console.log(error);
      }
    }

SQL Server command line backup statement

I am using SQL Server 2005 Express, and I had to enable Named Pipes connection to be able to backup from the Windows Command. My final script is this:

@echo off
set DB_NAME=Your_DB_Name
set BK_FILE=D:\DB_Backups\%DB_NAME%.bak
set DB_HOSTNAME=Your_DB_Hostname
echo.
echo.
echo Backing up %DB_NAME% to %BK_FILE%...
echo.
echo.
sqlcmd -E -S np:\\%DB_HOSTNAME%\pipe\MSSQL$SQLEXPRESS\sql\query -d master -Q "BACKUP DATABASE [%DB_NAME%] TO DISK = N'%BK_FILE%' WITH INIT , NOUNLOAD , NAME = N'%DB_NAME% backup', NOSKIP , STATS = 10, NOFORMAT"
echo.
echo Done!
echo.

It's working just fine here!!

how to count the total number of lines in a text file using python

For the people saying to use with open ("filename.txt","r") as f you can do anyname = open("filename.txt","r")

def main():

    file = open("infile.txt",'r')
    count = 0
    for line in file:
            count+=1

    print (count)

main ()

How to access single elements in a table in R

That is so basic that I am wondering what book you are using to study? Try

data[1, "V1"]  # row first, quoted column name second, and case does matter

Further note: Terminology in discussing R can be crucial and sometimes tricky. Using the term "table" to refer to that structure leaves open the possibility that it was either a 'table'-classed, or a 'matrix'-classed, or a 'data.frame'-classed object. The answer above would succeed with any of them, while @BenBolker's suggestion below would only succeed with a 'data.frame'-classed object.

I am unrepentant in my phrasing despite the recent downvote. There is a ton of free introductory material for beginners in R: https://cran.r-project.org/other-docs.html

How to generate access token using refresh token through google drive API?

If you using Java then follow below code snippet :

GoogleCredential refreshTokenCredential = new GoogleCredential.Builder().setJsonFactory(JSON_FACTORY).setTransport(HTTP_TRANSPORT).setClientSecrets(CLIENT_ID, CLIENT_SECRET).build().setRefreshToken(yourOldToken);
refreshTokenCredential.refreshToken(); //do not forget to call this
String newAccessToken = refreshTokenCredential.getAccessToken();

Finding the second highest number in array

// Initialize these to the smallest value possible
int highest = Integer.MIN_VALUE;
int secondHighest = Integer.MIN_VALUE;

// Loop over the array
for (int i = 0; i < array.Length; i++) {

    // If we've found a new highest number...
    if (array[i] > highest) {

        // ...shift the current highest number to second highest
        secondHighest = highest;

        // ...and set the new highest.
        highest = array[i];
    } else if (array[i] > secondHighest)
        // Just replace the second highest
        secondHighest = array[i];
    }
}

// After exiting the loop, secondHighest now represents the second
// largest value in the array

Edit:

Whoops. Thanks for pointing out my mistake, guys. Fixed now.

Mocking static methods with Mockito

For those who use JUnit 5, Powermock is not an option. You'll require the following dependencies to successfully mock a static method with just Mockito.

testCompile    group: 'org.mockito', name: 'mockito-core',           version: '3.6.0'
testCompile    group: 'org.mockito', name: 'mockito-junit-jupiter',  version: '3.6.0'
testCompile    group: 'org.mockito', name: 'mockito-inline',         version: '3.6.0'

mockito-junit-jupiter add supports for JUnit 5.

And support for mocking static methods is provided by mockito-inline dependency.

Example:

@Test
void returnUtilTest() {
    assertEquals("foo", UtilClass.staticMethod("foo"));

    try (MockedStatic<UtilClass> classMock = mockStatic(UtilClass.class)) {

        classMock.when(() -> UtilClass.staticMethod("foo")).thenReturn("bar");

        assertEquals("bar", UtilClass.staticMethod("foo"));
     }

     assertEquals("foo", UtilClass.staticMethod("foo"));
}

The try-with-resource block is used to make the static mock remains temporary, so it's mocked only within that scope.

When not using a try block, make sure to close the scoped mock, once you are done with the assertions.

MockedStatic<UtilClass> classMock = mockStatic(UtilClass.class)
classMock.when(() -> UtilClass.staticMethod("foo")).thenReturn("bar");
assertEquals("bar", UtilClass.staticMethod("foo"));
classMock.close();

Mocking void methods:

When mockStatic is called on a class, all the static void methods in that class automatically get mocked to doNothing().

Getting the last n elements of a vector. Is there a better way than using the length() function?

see ?tail and ?head for some convenient functions:

> x <- 1:10
> tail(x,5)
[1]  6  7  8  9 10

For the argument's sake : everything but the last five elements would be :

> head(x,n=-5)
[1] 1 2 3 4 5

As @Martin Morgan says in the comments, there are two other possibilities which are faster than the tail solution, in case you have to carry this out a million times on a vector of 100 million values. For readibility, I'd go with tail.

test                                        elapsed    relative 
tail(x, 5)                                    38.70     5.724852     
x[length(x) - (4:0)]                           6.76     1.000000     
x[seq.int(to = length(x), length.out = 5)]     7.53     1.113905     

benchmarking code :

require(rbenchmark)
x <- 1:1e8
do.call(
  benchmark,
  c(list(
    expression(tail(x,5)),
    expression(x[seq.int(to=length(x), length.out=5)]),
    expression(x[length(x)-(4:0)])
  ),  replications=1e6)
)

Metadata file '.dll' could not be found

In my case, I had a bunch of other build errors as well (some simple type conversions) along with this one, I was scratching my head trying to solve this, and I wasn't focusing on the other errors.

What finally solved my problem was that I fixed all the other build error and then I build again and it build successfully.

So in case you have other build errors along with missing DLL file error, and nothing else is working for you then try to fix the other errors first and then build the solution again.

awk without printing newline

awk '{sum+=$3}; END {printf "%f",sum/NR}' ${file}_${f}_v1.xls >> to-plot-p.xls

print will insert a newline by default. You dont want that to happen, hence use printf instead.

input type=file show only button

I was having a heck of a time trying to accomplish this. I didn't want to use a Flash solution, and none of the jQuery libraries I looked at were reliable across all browsers.

I came up with my own solution, which is implemented completely in CSS (except for the onclick style change to make the button appear 'clicked').

You can try a working example here: http://jsfiddle.net/VQJ9V/307/ (Tested in FF 7, IE 9, Safari 5, Opera 11 and Chrome 14)

It works by creating a big file input (with font-size:50px), then wrapping it in a div that has a fixed size and overflow:hidden. The input is then only visible through this "window" div. The div can be given a background image or color, text can be added, and the input can be made transparent to reveal the div background:

HTML:

<div class="inputWrapper">
    <input class="fileInput" type="file" name="file1"/>
</div>

CSS:

.inputWrapper {
    height: 32px;
    width: 64px;
    overflow: hidden;
    position: relative;
    cursor: pointer;
    /*Using a background color, but you can use a background image to represent a button*/
    background-color: #DDF;
}
.fileInput {
    cursor: pointer;
    height: 100%;
    position:absolute;
    top: 0;
    right: 0;
    z-index: 99;
    /*This makes the button huge. If you want a bigger button, increase the font size*/
    font-size:50px;
    /*Opacity settings for all browsers*/
    opacity: 0;
    -moz-opacity: 0;
    filter:progid:DXImageTransform.Microsoft.Alpha(opacity=0)
}

Let me know if there are any problems with it and I'll try to fix them.

What is a semaphore?

Think of semaphores as bouncers at a nightclub. There are a dedicated number of people that are allowed in the club at once. If the club is full no one is allowed to enter, but as soon as one person leaves another person might enter.

It's simply a way to limit the number of consumers for a specific resource. For example, to limit the number of simultaneous calls to a database in an application.

Here is a very pedagogic example in C# :-)

using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;

namespace TheNightclub
{
    public class Program
    {
        public static Semaphore Bouncer { get; set; }

        public static void Main(string[] args)
        {
            // Create the semaphore with 3 slots, where 3 are available.
            Bouncer = new Semaphore(3, 3);

            // Open the nightclub.
            OpenNightclub();
        }

        public static void OpenNightclub()
        {
            for (int i = 1; i <= 50; i++)
            {
                // Let each guest enter on an own thread.
                Thread thread = new Thread(new ParameterizedThreadStart(Guest));
                thread.Start(i);
            }
        }

        public static void Guest(object args)
        {
            // Wait to enter the nightclub (a semaphore to be released).
            Console.WriteLine("Guest {0} is waiting to entering nightclub.", args);
            Bouncer.WaitOne();          

            // Do some dancing.
            Console.WriteLine("Guest {0} is doing some dancing.", args);
            Thread.Sleep(500);

            // Let one guest out (release one semaphore).
            Console.WriteLine("Guest {0} is leaving the nightclub.", args);
            Bouncer.Release(1);
        }
    }
}

Simple division in Java - is this a bug or a feature?

In my case I was doing this:

double a = (double) (MAX_BANDWIDTH_SHARED_MB/(qCount+1));

Instead of the "correct" :

double a = (double)MAX_BANDWIDTH_SHARED_MB/(qCount+1);

Take attention with the parentheses !

Getting the error "Missing $ inserted" in LaTeX

I had this symbol _ in the head of one table and the code didn't run, so I had to delete.

Send PHP variable to javascript function

You can do the following:

<script type='text/javascript'>
    document.body.onclick(function(){
        var myVariable = <?php echo(json_encode($myVariable)); ?>;
    };
</script>

Python def function: How do you specify the end of the function?

It uses indentation

 def func():
     funcbody
     if cond: 
         ifbody
     outofif

 outof_func 

Javascript to export html table to Excel

For UTF 8 Conversion and Currency Symbol Export Use this:

var tableToExcel = (function() {
  var uri = 'data:application/vnd.ms-excel;base64,'
    , template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><?xml version="1.0" encoding="UTF-8" standalone="yes"?><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table>{table}</table></body></html>'
    , base64 = function(s) { return window.btoa(unescape(encodeURIComponent(s))) }
    , format = function(s, c) { return s.replace(/{(\w+)}/g, function(m, p) { return c[p]; }) }
  return function(table, name) {
      if (!table.nodeType) table = document.getElementById(table)
      var ctx = { worksheet: name || 'Worksheet', table: table.innerHTML }
    window.location.href = uri + base64(format(template, ctx))
  }
})()

printf %f with only 2 numbers after the decimal point?

I suggest to learn it with printf because for many cases this will be sufficient for your needs and you won't need to create other objects.

double d = 3.14159;     
printf ("%.2f", d);

But if you need rounding please refer to this post

https://stackoverflow.com/a/153785/2815227

How to Ping External IP from Java Android

I implemented "ping" in pure Android Java and hosted it on gitlab. It does the same thing as the ping executable, but is much easier to configure. It's has a couple useful features like being able to bind to a given Network.

https://github.com/dburckh/AndroidPing

SQL server stored procedure return a table

A procedure can't return a table as such. However you can select from a table in a procedure and direct it into a table (or table variable) like this:

create procedure p_x
as
begin
declare @t table(col1 varchar(10), col2 float, col3 float, col4 float)
insert @t values('a', 1,1,1)
insert @t values('b', 2,2,2)

select * from @t
end
go

declare @t table(col1 varchar(10), col2 float, col3 float, col4 float)
insert @t
exec p_x

select * from @t

Bold black cursor in Eclipse deletes code, and I don't know how to get rid of it

The problem is also identified in your status bar at the bottom:

overwrite label in status bar

You are in overwrite mode instead of insert mode.

The “Insert” key toggles between insert and overwrite modes.

How to change the background-color of jumbrotron?

In the .css try

_x000D_
_x000D_
.jumbotron {_x000D_
    background-color:red !important; _x000D_
}
_x000D_
_x000D_
_x000D_

how to get the first and last days of a given month

Basically:

$lastDate = date("Y-m-t", strtotime($query_d));

Date t parameter return days number in current month.

How to update and order by using ms sql

You can do a subquery where you first get the IDs of the top 10 ordered by priority and then update the ones that are on that sub query:

UPDATE  messages 
SET status=10 
WHERE ID in (SELECT TOP (10) Id 
             FROM Table 
             WHERE status=0 
             ORDER BY priority DESC);

"SyntaxError: Unexpected token < in JSON at position 0"

If anyone else is using fetch from the "Using Fetch" documentation on Web API's in Mozilla: (This is really useful: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch)

  fetch(api_url + '/database', {
    method: 'POST', // or 'PUT'
    headers: {
     'Content-Type': 'application/json'
    },
    body: qrdata //notice that it is not qr but qrdata
  })
  .then((response) => response.json())
  .then((data) => {
    console.log('Success:', data);
  })  
  .catch((error) => {
  console.error('Error:', error);  });

This was inside the function:

async function postQRData(qr) {

  let qrdata = qr; //this was added to fix it!
  //then fetch was here
}

I was passing into my function qr what I believed to be an object because qr looked like this: {"name": "Jade", "lname": "Bet", "pet":"cat"} but I kept getting syntax errors. When I assigned it to something else: let qrdata = qr; it worked.

Waiting until two async blocks are executed before starting another block

Answers above are all cool, but they all missed one thing. group executes tasks(blocks) in the thread where it entered when you use dispatch_group_enter/dispatch_group_leave.

- (IBAction)buttonAction:(id)sender {
      dispatch_queue_t demoQueue = dispatch_queue_create("com.demo.group", DISPATCH_QUEUE_CONCURRENT);
      dispatch_async(demoQueue, ^{
        dispatch_group_t demoGroup = dispatch_group_create();
        for(int i = 0; i < 10; i++) {
          dispatch_group_enter(demoGroup);
          [self testMethod:i
                     block:^{
                       dispatch_group_leave(demoGroup);
                     }];
        }

        dispatch_group_notify(demoGroup, dispatch_get_main_queue(), ^{
          NSLog(@"All group tasks are done!");
        });
      });
    }

    - (void)testMethod:(NSInteger)index block:(void(^)(void))completeBlock {
      NSLog(@"Group task started...%ld", index);
      NSLog(@"Current thread is %@ thread", [NSThread isMainThread] ? @"main" : @"not main");
      [NSThread sleepForTimeInterval:1.f];

      if(completeBlock) {
        completeBlock();
      }
    }

this runs in the created concurrent queue demoQueue. If i dont create any queue, it runs in main thread.

- (IBAction)buttonAction:(id)sender {
    dispatch_group_t demoGroup = dispatch_group_create();
    for(int i = 0; i < 10; i++) {
      dispatch_group_enter(demoGroup);
      [self testMethod:i
                 block:^{
                   dispatch_group_leave(demoGroup);
                 }];
    }

    dispatch_group_notify(demoGroup, dispatch_get_main_queue(), ^{
      NSLog(@"All group tasks are done!");
    });
    }

    - (void)testMethod:(NSInteger)index block:(void(^)(void))completeBlock {
      NSLog(@"Group task started...%ld", index);
      NSLog(@"Current thread is %@ thread", [NSThread isMainThread] ? @"main" : @"not main");
      [NSThread sleepForTimeInterval:1.f];

      if(completeBlock) {
        completeBlock();
      }
    }

and there's a third way to make tasks executed in another thread:

- (IBAction)buttonAction:(id)sender {
      dispatch_queue_t demoQueue = dispatch_queue_create("com.demo.group", DISPATCH_QUEUE_CONCURRENT);
      //  dispatch_async(demoQueue, ^{
      __weak ViewController* weakSelf = self;
      dispatch_group_t demoGroup = dispatch_group_create();
      for(int i = 0; i < 10; i++) {
        dispatch_group_enter(demoGroup);
        dispatch_async(demoQueue, ^{
          [weakSelf testMethod:i
                         block:^{
                           dispatch_group_leave(demoGroup);
                         }];
        });
      }

      dispatch_group_notify(demoGroup, dispatch_get_main_queue(), ^{
        NSLog(@"All group tasks are done!");
      });
      //  });
    }

Of course, as mentioned you can use dispatch_group_async to get what you want.

PHP cURL vs file_get_contents

This is old topic but on my last test on one my API, cURL is faster and more stable. Sometimes file_get_contents on larger request need over 5 seconds when cURL need only from 1.4 to 1.9 seconds what is double faster.

I need to add one note on this that I just send GET and recive JSON content. If you setup cURL properly, you will have a great response. Just "tell" to cURL what you need to send and what you need to recive and that's it.

On your exampe I would like to do this setup:

$ch =  curl_init('http://api.bitly.com/v3/shorten?login=user&apiKey=key&longUrl=url');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
    curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
    curl_setopt($ch, CURLOPT_TIMEOUT, 3);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/json'));
$result = curl_exec($ch);

This request will return data in 0.10 second max

Using Laravel Homestead: 'no input file specified'

If you renamed the folder containing your Homestead project, you'll get this error. Visit your Homestead.yaml file and update any references to point to the renamed folder, then do vagrant up (etc.) again

How to set iframe size dynamically

Not quite sure what the 300 is supposed to mean? Miss typo? However for iframes it would be best to use CSS :) - Ive found befor when importing youtube videos that it ignores inline things.

<style>
    #myFrame { width:100%; height:100%; }
</style>

<iframe src="html_intro.asp" id="myFrame">
<p>Hi SOF</p>
</iframe>

Is there anything like .NET's NotImplementedException in Java?

As mentioned, the JDK does not have a close match. However, my team occasionally has a use for such an exception as well. We could have gone with UnsupportedOperationException as suggested by other answers, but we prefer a custom exception class in our base library that has deprecated constructors:

public class NotYetImplementedException extends RuntimeException
{
    /**
     * @deprecated Deprecated to remind you to implement the corresponding code
     *             before releasing the software.
     */
    @Deprecated
    public NotYetImplementedException()
    {
    }

    /**
     * @deprecated Deprecated to remind you to implement the corresponding code
     *             before releasing the software.
     */
    @Deprecated
    public NotYetImplementedException(String message)
    {
        super(message);
    }
}

This approach has the following benefits:

  1. When readers see NotYetImplementedException, they know that an implementation was planned and was either forgotten or is still in progress, whereas UnsupportedOperationException says (in line with collection contracts) that something will never be implemented. That's why we have the word "yet" in the class name. Also, an IDE can easily list the call sites.
  2. With the deprecation warning at each call site, your IDE and static code analysis tool can remind you where you still have to implement something. (This use of deprecation may feel wrong to some, but in fact deprecation is not limited to announcing removal.)
  3. The constructors are deprecated, not the class. This way, you only get a deprecation warning inside the method that needs implementing, not at the import line (JDK 9 fixed this, though).

How to open a Bootstrap modal window using jQuery?

Try this. It's works for me well.

_x000D_
_x000D_
function clicked(item) {
         alert($(item).attr("id"));
        }
_x000D_
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-rtl/3.4.0/css/bootstrap-rtl.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>

<button onclick="clicked(this);" id="modalME">Click me</button>

<!-- Modal -->
  <div class="modal" id="modalME" aria-hidden="true">
    <div class="modal-dialog">
      <div class="modal-header">
        <h2>Modal in CSS</h2>
        <a href="#close" class="btn-close" aria-hidden="true">×</a> <!--CHANGED TO "#close"-->
      </div>
      <div class="modal-body">
        <p>One modal example here.</p>
      </div>
      <div class="modal-footer">
        <a href="#close" class="btn">Nice!</a>  <!--CHANGED TO "#close"-->
      </div>
      </div>
    </div>
  </div>
  <!-- /Modal -->
_x000D_
_x000D_
_x000D_

How to connect to a remote Windows machine to execute commands using python?

I don't know WMI but if you want a simple Server/Client, You can use this simple code from tutorialspoint

Server:

import socket               # Import socket module

s = socket.socket()         # Create a socket object
host = socket.gethostname() # Get local machine name
port = 12345                # Reserve a port for your service.
s.bind((host, port))        # Bind to the port

s.listen(5)                 # Now wait for client connection.
while True:
   c, addr = s.accept()     # Establish connection with client.
   print 'Got connection from', addr
   c.send('Thank you for connecting')
   c.close()                # Close the connection 

Client

#!/usr/bin/python           # This is client.py file

import socket               # Import socket module

s = socket.socket()         # Create a socket object
host = socket.gethostname() # Get local machine name
port = 12345                # Reserve a port for your service.

s.connect((host, port))
print s.recv(1024)
s.close                     # Close the socket when done

it also have all the needed information for simple client/server applications.

Just convert the server and use some simple protocol to call a function from python.

P.S: i'm sure there are a lot of better options, it's just a simple one if you want...

Control cannot fall through from one case label

You need to break;, throw, goto, or return from each of your case labels. In a loop you may also continue.

        switch (searchType)
        {
            case "SearchBooks":
                Selenium.Type("//*[@id='SearchBooks_TextInput']", searchText);
                Selenium.Click("//*[@id='SearchBooks_SearchBtn']");
                break;

            case "SearchAuthors":
                Selenium.Type("//*[@id='SearchAuthors_TextInput']", searchText);
                Selenium.Click("//*[@id='SearchAuthors_SearchBtn']");
                break;
        }

The only time this isn't true is when the case labels are stacked like this:

 case "SearchBooks": // no code inbetween case labels.
 case "SearchAuthors":
    // handle both of these cases the same way.
    break;

Convert JS date time to MySQL datetime

The venerable DateJS library has a formatting routine (it overrides ".toString()"). You could also do one yourself pretty easily because the "Date" methods give you all the numbers you need.

When or Why to use a "SET DEFINE OFF" in Oracle Database

By default, SQL Plus treats '&' as a special character that begins a substitution string. This can cause problems when running scripts that happen to include '&' for other reasons:

SQL> insert into customers (customer_name) values ('Marks & Spencers Ltd');
Enter value for spencers: 
old   1: insert into customers (customer_name) values ('Marks & Spencers Ltd')
new   1: insert into customers (customer_name) values ('Marks  Ltd')

1 row created.

SQL> select customer_name from customers;

CUSTOMER_NAME
------------------------------
Marks  Ltd

If you know your script includes (or may include) data containing '&' characters, and you do not want the substitution behaviour as above, then use set define off to switch off the behaviour while running the script:

SQL> set define off
SQL> insert into customers (customer_name) values ('Marks & Spencers Ltd');

1 row created.

SQL> select customer_name from customers;

CUSTOMER_NAME
------------------------------
Marks & Spencers Ltd

You might want to add set define on at the end of the script to restore the default behaviour.

How to fix div on scroll

On jQuery for designers there's a well written post about this, this is the jQuery snippet that does the magic. just replace #comment with the selector of the div that you want to float.

Note: To see the whole article go here: http://jqueryfordesigners.com/fixed-floating-elements/

$(document).ready(function () {
  var $obj = $('#comment');
  var top = $obj.offset().top - parseFloat($obj.css('marginTop').replace(/auto/, 0));

  $(window).scroll(function (event) {
    // what the y position of the scroll is
    var y = $(this).scrollTop();

    // whether that's below the form
    if (y >= top) {
      // if so, ad the fixed class
      $obj.addClass('fixed');
    } else {
      // otherwise remove it
      $obj.removeClass('fixed');
    }
  });
});

Is there a Subversion command to reset the working copy?

To revert tracked files

svn revert . -R

To clean untracked files

svn status | rm -rf $(awk '/^?/{$1 = ""; print $0}')

The -rf may/should look scary at first, but once understood it will not be for these reasons:

  1. Only wholly-untracked directories will match the pattern passed to rm
  2. The -rf is required, else these directories will not be removed

To revert then clean (the OP question)

svn revert . -R && svn status | rm -rf $(awk '/^?/{$1 = ""; print $0}')

For consistent ease of use

Add permanent alias to your .bash_aliases

alias svn.HardReset='read -p "destroy all local changes?[y/N]" && [[ $REPLY =~ ^[yY] ]] && svn revert . -R && rm -rf $(awk -f <(echo "/^?/{print \$2}") <(svn status) ;)'

DNS caching in linux

On Linux (and probably most Unix), there is no OS-level DNS caching unless nscd is installed and running. Even then, the DNS caching feature of nscd is disabled by default at least in Debian because it's broken. The practical upshot is that your linux system very very probably does not do any OS-level DNS caching.

You could implement your own cache in your application (like they did for Squid, according to diegows's comment), but I would recommend against it. It's a lot of work, it's easy to get it wrong (nscd got it wrong!!!), it likely won't be as easily tunable as a dedicated DNS cache, and it duplicates functionality that already exists outside your application.

If an end user using your software needs to have DNS caching because the DNS query load is large enough to be a problem or the RTT to the external DNS server is long enough to be a problem, they can install a caching DNS server such as Unbound on the same machine as your application, configured to cache responses and forward misses to the regular DNS resolvers.

How to create empty data frame with column names specified in R?

Just create a data.frame with 0 length variables

eg

nodata <- data.frame(x= numeric(0), y= integer(0), z = character(0))
str(nodata)

## 'data.frame':    0 obs. of  3 variables:
##  $ x: num 
##  $ y: int 
##  $ z: Factor w/ 0 levels: 

or to create a data.frame with 5 columns named a,b,c,d,e

nodata <- as.data.frame(setNames(replicate(5,numeric(0), simplify = F), letters[1:5]))

Error parsing yaml file: mapping values are not allowed here

Change

application:climate-change

to

application: climate-change

The space after the colon is mandatory in yaml if you want a key-value pair. (See http://www.yaml.org/spec/1.2/spec.html#id2759963)

MySQL CREATE TABLE IF NOT EXISTS in PHPmyadmin import

it is because you already defined the 'abuse_id' as auto increment, then there is no need to insert its value. it will be inserted automatically. the error comes because you are inserting 1 many times that is duplication of data. the primary key should be unique. should not be repeated.

the thing you have to do is to change your insertion query as below

INSERT INTO  `abuses` (  `user_id` ,  `abuser_username` ,  `comment` ,  `reg_date` , `auction_id` ) 
VALUES ( 100020,  'artictundra', 'I placed a bid for it more than an hour ago. It is still active. I     thought I was supposed to get an email after 15 minutes.', 1338052850, 108625 ) ;

Android:java.lang.OutOfMemoryError: Failed to allocate a 23970828 byte allocation with 2097152 free bytes and 2MB until OOM

Resize your image before setup to ImageView like this:

Bitmap.createScaledBitmap(_yourImageBitmap, _size, _size, false);

where size is actual size of ImageView. You can reach size by measuring:

imageView.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED), MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));

and use next size imageView.getMeasuredWidth() and imageView.getMeasuredHeight() for scaling.

SSH SCP Local file to Remote in Terminal Mac Os X

Just to clarify the answer given by JScoobyCed, the scp command cannot copy files to directories that require administrative permission. However, you can use the scp command to copy to directories that belong to the remote user.

So, to copy to a directory that requires root privileges, you must first copy that file to a directory belonging to the remote user using the scp command. Next, you must login to the remote account using ssh. Once logged in, you can then move the file to the directory of your choosing by using the sudo mv command. In short, the commands to use are as follows:

Using scp, copy file to a directory in the remote user's account, for example the Documents directory:

scp /path/to/your/local/file remoteUser@some_address:/home/remoteUser/Documents

Next, login to the remote user's account using ssh and then move the file to a restricted directory using sudo:

ssh remoteUser@some_address
sudo mv /home/remoteUser/Documents/file /var/www

MySql: Tinyint (2) vs tinyint(1) - what is the difference?

About the INT, TINYINT... These are different data types, INT is 4-byte number, TINYINT is 1-byte number. More information here - INTEGER, INT, SMALLINT, TINYINT, MEDIUMINT, BIGINT.

The syntax of TINYINT data type is TINYINT(M), where M indicates the maximum display width (used only if your MySQL client supports it).

Numeric Type Attributes.

Get the current URL with JavaScript?

OK, getting the full URL of the current page is easy using pure JavaScript. For example, try this code on this page:

window.location.href;
// use it in the console of this page will return
// http://stackoverflow.com/questions/1034621/get-current-url-in-web-browser"

The window.location.href property returns the URL of the current page.

_x000D_
_x000D_
document.getElementById("root").innerHTML = "The full URL of this page is:<br>" + window.location.href;
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
_x000D_
<body>_x000D_
  <h2>JavaScript</h2>_x000D_
  <h3>The window.location.href</h3>_x000D_
  <p id="root"></p>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

Just not bad to mention these as well:

  • if you need a relative path, simply use window.location.pathname;

  • if you'd like to get the host name, you can use window.location.hostname;

  • and if you need to get the protocol separately, use window.location.protocol

    • also, if your page has hash tag, you can get it like: window.location.hash.

So window.location.href handles all in once... basically:

window.location.protocol + '//' + window.location.hostname + window.location.pathname + window.location.hash === window.location.href;
    //true

Also using window is not needed if already in window scope...

So, in that case, you can use:

location.protocol

location.hostname

location.pathname

location.hash

location.href

Get the current URL with JavaScript

How can I delete multiple lines in vi?

You can delete multiple(range) lines if you know the line numbers:

:[start_line_no],[end_line_no]d

Note: d stands for delete

where,
start_line_no is the beginning line no you want to delete and end_line_no is the ending line no you want to delete. The lines between the start and end, including start and end will be deleted.

Eg:

:45,101d

The lines between 45 and 101 including 45 and 101 will be deleted.

Add days Oracle SQL

You can use the plus operator to add days to a date.

order_date + 20

jQuery append() vs appendChild()

I know this is an old and answered question and I'm not looking for votes I just want to add an extra little thing that I think might help newcomers.

yes appendChild is a DOM method and append is JQuery method but practically the key difference is that appendChild takes a node as a parameter by that I mean if you want to add an empty paragraph to the DOM you need to create that p element first

var p = document.createElement('p')

then you can add it to the DOM whereas JQuery append creates that node for you and adds it to the DOM right away whether it's a text element or an html element or a combination!

$('p').append('<span> I have been appended </span>');

Count number of 1's in binary representation

I have actually done this using a bit of sleight of hand: a single lookup table with 16 entries will suffice and all you have to do is break the binary rep into nibbles (4-bit tuples). The complexity is in fact O(1) and I wrote a C++ template which was specialized on the size of the integer you wanted (in # bits)… makes it a constant expression instead of indetermined.

fwiw you can use the fact that (i & -i) will return you the LS one-bit and simply loop, stripping off the lsbit each time, until the integer is zero — but that’s an old parity trick.