Programs & Examples On #Cd drive

Skip over a value in the range function in python

It depends on what you want to do. For example you could stick in some conditionals like this in your comprehensions:

# get the squares of each number from 1 to 9, excluding 2
myList = [i**2 for i in range(10) if i != 2]
print(myList)

# --> [0, 1, 9, 16, 25, 36, 49, 64, 81]

How do you parse and process HTML/XML in PHP?

Why you shouldn't and when you should use regular expressions?

First off, a common misnomer: Regexps are not for "parsing" HTML. Regexes can however "extract" data. Extracting is what they're made for. The major drawback of regex HTML extraction over proper SGML toolkits or baseline XML parsers are their syntactic effort and varying reliability.

Consider that making a somewhat dependable HTML extraction regex:

<a\s+class="?playbutton\d?[^>]+id="(\d+)".+?    <a\s+class="[\w\s]*title
[\w\s]*"[^>]+href="(http://[^">]+)"[^>]*>([^<>]+)</a>.+?

is way less readable than a simple phpQuery or QueryPath equivalent:

$div->find(".stationcool a")->attr("title");

There are however specific use cases where they can help.

  • Many DOM traversal frontends don't reveal HTML comments <!--, which however are sometimes the more useful anchors for extraction. In particular pseudo-HTML variations <$var> or SGML residues are easy to tame with regexps.
  • Oftentimes regular expressions can save post-processing. However HTML entities often require manual caretaking.
  • And lastly, for extremely simple tasks like extracting <img src= urls, they are in fact a probable tool. The speed advantage over SGML/XML parsers mostly just comes to play for these very basic extraction procedures.

It's sometimes even advisable to pre-extract a snippet of HTML using regular expressions /<!--CONTENT-->(.+?)<!--END-->/ and process the remainder using the simpler HTML parser frontends.

Note: I actually have this app, where I employ XML parsing and regular expressions alternatively. Just last week the PyQuery parsing broke, and the regex still worked. Yes weird, and I can't explain it myself. But so it happened.
So please don't vote real-world considerations down, just because it doesn't match the regex=evil meme. But let's also not vote this up too much. It's just a sidenote for this topic.

Error - SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM

This error occurs if you are trying to set variable of type DateTime to null. Declare the variable as nullable, i.e. DateTime? . This will solve the problem.

How to remove unused imports in Intellij IDEA on commit?

You can check checkbox in the commit dialog.

enter image description here

You can use settings to automatically optimize imports since 11.1 and above.

enter image description here

What is the attribute property="og:title" inside meta tag?

og:title is one of the open graph meta tags. og:... properties define objects in a social graph. They are used for example by Facebook.

og:title stands for the title of your object as it should appear within the graph (see here for more http://ogp.me/ )

How to detect IE11?

Quite frankly I would say use a library that does what you need (like platform.js for example). At some point things will change and the library will be equipped for those changes and manual parsing using regular expressions will fail.

Thank god IE goes away...

Fork() function in C

I think every process you make start executing the line you create so something like this...

pid=fork() at line 6. fork function returns 2 values 
you have 2 pids, first pid=0 for child and pid>0 for parent 
so you can use if to separate

.

/*
    sleep(int time) to see clearly
    <0 fail 
    =0 child
    >0 parent
*/
int main(int argc, char** argv) {
    pid_t childpid1, childpid2;
    printf("pid = process identification\n");
    printf("ppid = parent process identification\n");
    childpid1 = fork();
    if (childpid1 == -1) {
        printf("Fork error !\n");
    }
    if (childpid1 == 0) {
        sleep(1);
        printf("child[1] --> pid = %d and  ppid = %d\n",
                getpid(), getppid());
    } else {
        childpid2 = fork();
        if (childpid2 == 0) {
            sleep(2);
            printf("child[2] --> pid = %d and ppid = %d\n",
                    getpid(), getppid());
        } else {
            sleep(3);
            printf("parent --> pid = %d\n", getpid());
        }
    }
    return 0;
}

//pid = process identification
//ppid = parent process identification
//child[1] --> pid = 2399 and  ppid = 2398
//child[2] --> pid = 2400 and ppid = 2398
//parent --> pid = 2398

linux.die.net

some uni stuff

Convert object of any type to JObject with Json.NET

If you have an object and wish to become JObject you can use:

JObject o = (JObject)JToken.FromObject(miObjetoEspecial);

like this :

Pocion pocionDeVida = new Pocion{
tipo = "vida",
duracion = 32,
};

JObject o = (JObject)JToken.FromObject(pocionDeVida);
Console.WriteLine(o.ToString());
// {"tipo": "vida", "duracion": 32,}

java.lang.IllegalStateException: Cannot (forward | sendRedirect | create session) after response has been committed

You should add return statement while you are forwarding or redirecting the flow.

Example:

if forwardind,

    request.getRequestDispatcher("/abs.jsp").forward(request, response);
    return;

if redirecting,

    response.sendRedirect(roundTripURI);
    return;

CSS scale height to match width - possibly with a formfactor

.video {
    width: 100%;
    position: relative;
    padding-bottom: 56.25%; /* ratio 16/9 */
}

.video iframe {
    border: none;
    position: absolute;
    width: 100%;
    height: 100%;
}

16:9

padding-bottom = 9/16 * 100 = 56.25

Check for a substring in a string in Oracle without LIKE

You can do it this way using INSTR:

SELECT * FROM users WHERE INSTR(LOWER(last_name), 'z') > 0;

INSTR returns zero if the substring is not in the string.

Out of interest, why don't you want to use like?

Edit: I took the liberty of making the search case insensitive so you don't miss Bob Zebidee. :-)

SoapFault exception: Could not connect to host

Version check helped me OpenSSL. OpenSSL_1_0_1f not supported TSLv.1_2 ! Check version and compatibility with TSLv.1_2 on github openssl/openssl . And regenerate your certificate with new openssl

openssl pkcs12 -in path.p12 -out newfile.pem

P.S I don’t know what they were minus, but this solution will really help.

The container 'Maven Dependencies' references non existing library - STS

Today I had this same problem with another jar. I tried multiple things people said on Stackoverflow, but nothing worked. Eventually I did this:

  1. Close eclipse and any project-app that is running.
  2. Delete the .m2 folder (Users --> [your_username] --> .m2). It's an invisible folder, make sure you are able to view invisible folders.
  3. Restarted Eclipse (I guess it works in other IDE too) and updated my project.

Now it works again for me. Perhaps this solves the problem for someone else too.

const to Non-const Conversion in C++

Changing a constant type will lead to an Undefined Behavior.

However, if you have an originally non-const object which is pointed to by a pointer-to-const or referenced by a reference-to-const then you can use const_cast to get rid of that const-ness.

Casting away constness is considered evil and should not be avoided. You should consider changing the type of the pointers you use in vector to non-const if you want to modify the data through it.

SessionNotCreatedException: Message: session not created: This version of ChromeDriver only supports Chrome version 81

Do below steps :

  1. Check the version of chrome browser.

  2. download chromedriver of same version from https://sites.google.com/a/chromium.org/chromedriver/

  3. Give correct path in the pycharm and run the code.

I want to convert std::string into a const wchar_t *

You can use the ATL text conversion macros to convert a narrow (char) string to a wide (wchar_t) one. For example, to convert a std::string:

#include <atlconv.h>
...
std::string str = "Hello, world!";
CA2W pszWide(str.c_str());
loadU(pszWide);

You can also specify a code page, so if your std::string contains UTF-8 chars you can use:

CA2W pszWide(str.c_str(), CP_UTF8);

Very useful but Windows only.

Fixing broken UTF-8 encoding

I found a solution after days of search. My comment is going to be buried but anyway...

  1. I get the corrupted data with php.

  2. I don't use set names UTF8

  3. I use utf8_decode() on my data

  4. I update my database with my new decoded data, still not using set names UTF8

and voilà :)

OpenCV - Apply mask to a color image

Here, you could use cv2.bitwise_and function if you already have the mask image.

For check the below code:

img = cv2.imread('lena.jpg')
mask = cv2.imread('mask.png',0)
res = cv2.bitwise_and(img,img,mask = mask)

The output will be as follows for a lena image, and for rectangular mask.

enter image description here

How to parse SOAP XML?

PHP version > 5.0 has a nice SoapClient integrated. Which doesn't require to parse response xml. Here's a quick example

$client = new SoapClient("http://path.to/wsdl?WSDL");
$res = $client->SoapFunction(array('param1'=>'value','param2'=>'value'));
echo $res->PaymentNotification->payment;

What exactly does Double mean in java?

Double is a wrapper class,

The Double class wraps a value of the primitive type double in an object. An object of type Double contains a single field whose type is double.

In addition, this class provides several methods for converting a double to a String and a String to a double, as well as other constants and methods useful when dealing with a double.

The double data type,

The double data type is a double-precision 64-bit IEEE 754 floating point. Its range of values is 4.94065645841246544e-324d to 1.79769313486231570e+308d (positive or negative). For decimal values, this data type is generally the default choice. As mentioned above, this data type should never be used for precise values, such as currency.

Check each datatype with their ranges : Java's Primitive Data Types.


Important Note : If you'r thinking to use double for precise values, you need to re-think before using it. Java Traps: double

How to allow users to check for the latest app version from inside the app?

I know the OP was very old, at that time in-app-update was not available. But from API 21, you can use in-app-update checking. You may need to keep your eyes on some points which are nicely written up here:

Top 5 time-consuming SQL queries in Oracle

the complete information one that I got from askTom-Oracle. I hope it helps you

select * 
from v$sql 
where buffer_gets > 1000000 
or disk_reads > 100000 
or executions > 50000 

How can I remove an SSH key?

I opened "Passwords and Keys" application in my Unity and removed unwanted keys from Secure Keys -> OpenSSH keys And they automatically had been removed from ssh-agent -l as well.

what does Error "Thread 1:EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)" mean?

I got this on WatchOS Sim. The issue persisted even after:

  • Deleting the app
  • Restarting Xcode
  • Deleting Derived Data

...and was finally fixed by "Erase all Content and Settings" in the simulator.

RegEx to extract all matches from string using RegExp.exec

Since ES9, there's now a simpler, better way of getting all the matches, together with information about the capture groups, and their index:

const string = 'Mice like to dice rice';
const regex = /.ice/gu;
for(const match of string.matchAll(regex)) {
    console.log(match);
}

// ["mice", index: 0, input: "mice like to dice rice", groups: undefined]

// ["dice", index: 13, input: "mice like to dice rice", groups: undefined]

// ["rice", index: 18, input: "mice like to dice rice", groups: undefined]

It is currently supported in Chrome, Firefox, Opera. Depending on when you read this, check this link to see its current support.

What does 'stale file handle' in Linux mean?

When the directory is deleted, the inode for that directory (and the inodes for its contents) are recycled. The pointer your shell has to that directory's inode (and its contents's inodes) are now no longer valid. When the directory is restored from backup, the old inodes are not (necessarily) reused; the directory and its contents are stored on random inodes. The only thing that stays the same is that the parent directory reuses the same name for the restored directory (because you told it to).

Now if you attempt to access the contents of the directory that your original shell is still pointing to, it communicates that request to the file system as a request for the original inode, which has since been recycled (and may even be in use for something entirely different now). So you get a stale file handle message because you asked for some nonexistent data.

When you perform a cd operation, the shell reevaluates the inode location of whatever destination you give it. Now that your shell knows the new inode for the directory (and the new inodes for its contents), future requests for its contents will be valid.

What's the fastest way to loop through an array in JavaScript?

While loop is a bit faster than for loop.

var len = arr.length;
while (len--) {
    // blah blah
}

Use while loop instead

PHP Pass variable to next page

There are three method to pass value in php.

  • By post
  • By get
  • By making session variable

These three method are used for different purpose.For example if we want to receive our value on next page then we can use 'post' ($_POST) method as:-

$a=$_POST['field-name'];

If we require the value of variable on more than one page than we can use session variable as:-

$a=$_SESSION['field-name];

Before using this Syntax for creating SESSION variable we first have to add this tag at the very beginning of our php page

session_start(); 

GET method are generally used to print data on same page which used to take input from user. Its syntax is as:

$a=$_GET['field-name'];

POST method are generally consume more secure than GET because when we use Get method than it can display the data in URL bar.If the data is more sensitive data like password then it can be inggeris.

How to add \newpage in Rmarkdown in a smart way?

You can make the pagebreak conditional on knitting to PDF. This worked for me.

```{r, results='asis', eval=(opts_knit$get('rmarkdown.pandoc.to') == 'latex')}
cat('\\pagebreak')
```

How do I install cURL on Windows?

I agree with Erroid, you must add PHP directory into PATH environment.

PATH=%PATH%;<Your_PHP_Path>

Example

PATH=%PATH%;C:\php

It worked for me. Thank you.

Batch File: ( was unexpected at this time

Oh, dear. A few little problems...

As pointed out by others, you need to quote to protect against empty/space-containing entries, and use the !delayed_expansion! facility.

Two other matters of which you should be aware:

First, set/p will assign a user-input value to a variable. That's not news - but the gotcha is that pressing enter in response will leave the variable UNCHANGED - it will not ASSIGN a zero-length string to the variable (hence deleting the variable from the environment.) The safe method is:

 set "var="
 set /p var=

That is, of course, if you don't WANT enter to repeat the existing value.
Another useful form is

 set "var=default"
 set /p var=

or

 set "var=default"
 set /p "var=[%var%]"

(which prompts with the default value; !var! if in a block statement with delayedexpansion)

Second issue is that on some Windows versions (although W7 appears to "fix" this issue) ANY label - including a :: comment (which is a broken-label) will terminate any 'block' - that is, parenthesised compound statement)

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')

How to check if an integer is within a range of numbers in PHP?

using a switch case

    switch ($num){

        case ($num>= $value1 && $num<= $value2): 
            echo "within range 1";
        break;
        case ($num>= $value3 && $num<= $value4): 
            echo "within range 2";
        break;
        .
        .
        .
        .
        .

        default: //default
            echo "within no range";
        break;
     }

Why is Event.target not Element in Typescript?

JLRishe's answer is correct, so I simply use this in my event handler:

if (event.target instanceof Element) { /*...*/ }

MySQL Removing Some Foreign keys

first need to get actual constrain name by this query

SHOW CREATE TABLE TABLE_NAME

This query will result constrain name of the foreign key, now below query will drop it.

ALTER TABLE TABLE_NAME DROP FOREIGN KEY COLUMN_NAME_ibfk_1

last number in above constrain name depends how many foreign keys you have in table

How to restart Postgresql

Try this as root (maybe you can use sudo or su):

/etc/init.d/postgresql restart

Without any argument the script also gives you a hint on how to restart a specific version

[Uqbar@Feynman ~] /etc/init.d/postgresql
Usage: /etc/init.d/postgresql {start|stop|restart|reload|force-reload|status} [version ...]

Similarly, in case you have it, you can also use the service tool:

[Uqbar@Feynman ~] service postgresql
Usage: /etc/init.d/postgresql {start|stop|restart|reload|force reload|status} [version ...]

Please, pay attention to the optional [version ...] trailing argument. That's meant to allow you, the user, to act on a specific version, in case you were running multiple ones. So you can restart version X while keeping version Y and Z untouched and running.

Finally, in case you are running systemd, then you can use systemctl like this:

[support@Feynman ~] systemctl status postgresql
? postgresql.service - PostgreSQL database server
   Loaded: loaded (/usr/lib/systemd/system/postgresql.service; enabled; vendor preset: disabled)
   Active: active (running) since Wed 2017-11-14 12:33:35 CET; 7min ago
...

You can replace status with stop, start or restart as well as other actions. Please refer to the documentation for full details. In order to operate on multiple concurrent versions, the syntax is slightly different. For example to stop v12 and reload v13 you can run:

systemctl stop postgresql-12.service
systemctl reload postgresql-13.service

Thanks to @Jojo for pointing me to this very one. Finally Keep in mind that root permissions may be needed for non-informative tasks as in the other cases seen earlier.

org.hibernate.HibernateException: Access to DialectResolutionInfo cannot be null when 'hibernate.dialect' not set

Same but in a JBoss WildFly AS.

Solved with properties in my META-INF/persistence.xml

<properties>
            <property name="hibernate.transaction.jta.platform"
                value="org.hibernate.service.jta.platform.internal.JBossAppServerJtaPlatform" />
            <property name="spring.jpa.database-platform" value="org.hibernate.dialect.PostgreSQLDialect" />
            <property name="spring.jpa.show-sql" value="false" />
</properties>

overlay two images in android to set an imageview

You can use the code below to solve the problem or download demo here

Create two functions to handle each.

First, the canvas is drawn and the images are drawn on top of each other from point (0,0)

On button click

public void buttonMerge(View view) {

        Bitmap bigImage = BitmapFactory.decodeResource(getResources(), R.drawable.img1);
        Bitmap smallImage = BitmapFactory.decodeResource(getResources(), R.drawable.img2);
        Bitmap mergedImages = createSingleImageFromMultipleImages(bigImage, smallImage);

        img.setImageBitmap(mergedImages);
    }

Function to create an overlay.

private Bitmap createSingleImageFromMultipleImages(Bitmap firstImage, Bitmap secondImage){

    Bitmap result = Bitmap.createBitmap(firstImage.getWidth(), firstImage.getHeight(), firstImage.getConfig());
    Canvas canvas = new Canvas(result);
    canvas.drawBitmap(firstImage, 0f, 0f, null);
    canvas.drawBitmap(secondImage, 10, 10, null);
    return result;
}

Read more

How to get Device Information in Android

You may want to take a look at those pages : http://developer.android.com/reference/android/os/Build.html and http://developer.android.com/reference/java/lang/System.html (the getProperty() method might do the job).

For instance :

System.getProperty("os.version"); // OS version
android.os.Build.VERSION.SDK      // API Level
android.os.Build.DEVICE           // Device
android.os.Build.MODEL            // Model 
android.os.Build.PRODUCT          // Product

Etc...

Convert a string to datetime in PowerShell

Hope below helps!

PS C:\Users\aameer>$invoice = $object.'Invoice Month'
$invoice = "01-" + $invoice
[datetime]$Format_date =$invoice

Now type is converted. You can use method or can access any property.

Example :$Format_date.AddDays(5)

How to use class from other files in C# with visual studio?

I was having the same problem here. Found out that the problem was with an Advanced Property of the file. There is there an option with the name 'Compilation Action' (may be not with the exact words, I am translating - my VS is in Portuguese).

My Class1.cs file was there as "Content" and I just had to change it to "Compile" to make it work, and have the classes recognized by the others files in the same project.

How to validate an email address in PHP

This will not only validate your email, but also sanitize it for unexpected characters:

$email  = $_POST['email'];
$emailB = filter_var($email, FILTER_SANITIZE_EMAIL);

if (filter_var($emailB, FILTER_VALIDATE_EMAIL) === false ||
    $emailB != $email
) {
    echo "This email adress isn't valid!";
    exit(0);
}

Bash foreach loop

xargs --arg-file inputfile cat

This will output the filename followed by the file's contents:

xargs --arg-file inputfile -I % sh -c "echo %; cat %"

Set Focus on EditText

My answer here

As I read on the official document, I think this is the best answer, just pass the View to parameter such as your EditText, but showSoftKeyboard seems like not working on landscape

private fun showSoftKeyboard(view: View) {
    if (view.requestFocus()) {
        val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        imm.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT)
    }
}

private fun closeSoftKeyboard(view: View) {
    if (view.requestFocus()) {
        val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        imm.hideSoftInputFromWindow(view.windowToken, InputMethodManager.HIDE_NOT_ALWAYS)
    }
}

Selenium -- How to wait until page is completely loaded

3 answers, which you can combine:

  1. Set implicit wait immediately after creating the web driver instance:

    _ = driver.Manage().Timeouts().ImplicitWait;

    This will try to wait until the page is fully loaded on every page navigation or page reload.

  2. After page navigation, call JavaScript return document.readyState until "complete" is returned. The web driver instance can serve as JavaScript executor. Sample code:

    C#

    new WebDriverWait(driver, MyDefaultTimeout).Until(
    d => ((IJavaScriptExecutor) d).ExecuteScript("return document.readyState").Equals("complete"));
    

    Java

    new WebDriverWait(firefoxDriver, pageLoadTimeout).until(
          webDriver -> ((JavascriptExecutor) webDriver).executeScript("return document.readyState").equals("complete"));
    
  3. Check if the URL matches the pattern you expect.

Reading and writing binary file

If you want to do this the C++ way, do it like this:

#include <fstream>
#include <iterator>
#include <algorithm>

int main()
{
    std::ifstream input( "C:\\Final.gif", std::ios::binary );
    std::ofstream output( "C:\\myfile.gif", std::ios::binary );

    std::copy( 
        std::istreambuf_iterator<char>(input), 
        std::istreambuf_iterator<char>( ),
        std::ostreambuf_iterator<char>(output));
}

If you need that data in a buffer to modify it or something, do this:

#include <fstream>
#include <iterator>
#include <vector>

int main()
{
    std::ifstream input( "C:\\Final.gif", std::ios::binary );

    // copies all data into buffer
    std::vector<unsigned char> buffer(std::istreambuf_iterator<char>(input), {});

}

Algorithm to randomly generate an aesthetically-pleasing color palette

JavaScript adaptation of David Crow's original answer, IE and Nodejs specific code included.

generateRandomComplementaryColor = function(r, g, b){
    //--- JavaScript code
    var red = Math.floor((Math.random() * 256));
    var green = Math.floor((Math.random() * 256));
    var blue = Math.floor((Math.random() * 256));
    //---

    //--- Extra check for Internet Explorers, its Math.random is not random enough.
    if(!/MSIE 9/i.test(navigator.userAgent) && !/MSIE 10/i.test(navigator.userAgent) && !/rv:11.0/i.test(navigator.userAgent)){
        red = Math.floor((('0.' + window.crypto.getRandomValues(new Uint32Array(1))[0]) * 256));
        green = Math.floor((('0.' + window.crypto.getRandomValues(new Uint32Array(1))[0]) * 256));
        blue = Math.floor((('0.' + window.crypto.getRandomValues(new Uint32Array(1))[0]) * 256));
    };
    //---

    //--- nodejs code
    /*
    crypto = Npm.require('crypto');
    red = Math.floor((parseInt(crypto.randomBytes(8).toString('hex'), 16)) * 1.0e-19 * 256);
    green = Math.floor((parseInt(crypto.randomBytes(8).toString('hex'), 16)) * 1.0e-19 * 256);
    blue = Math.floor((parseInt(crypto.randomBytes(8).toString('hex'), 16)) * 1.0e-19 * 256);
    */
    //---

    red = (red + r)/2;
    green = (green + g)/2;
    blue = (blue + b)/2;

    return 'rgb(' + Math.floor(red) + ', ' + Math.floor(green) + ', ' + Math.floor(blue) + ')';
}

Run the function using:

generateRandomComplementaryColor(240, 240, 240);

jQuery ajax success callback function definition

Try rewriting your success handler to:

success : handleData

The success property of the ajax method only requires a reference to a function.

In your handleData function you can take up to 3 parameters:

object data
string textStatus
jqXHR jqXHR

CS0234: Mvc does not exist in the System.Web namespace

I had the same problem and I had solved it with:

1.Right click to solution and click 'Clean Solution'

2.Click 'References' folder in solution explorer and select the problem reference (in your case it seems System.Web.Mvc) and then right click and click 'Properties'.

3.In the properties window, make sure that the 'Copy Local' property is set to 'True'

This worked for me. Hope it works for someone else

Helpful Note: As it has mentioned in comments by @Vlad:

If it is already set to True:

  1. Set it False
  2. Set it True again
  3. Rebuild

URL encoding the space character: + or %20?

I would recommend %20.

Are you hard-coding them?

This is not very consistent across languages, though. If I'm not mistaken, in PHP urlencode() treats spaces as + whereas Python's urlencode() treats them as %20.

EDIT:

It seems I'm mistaken. Python's urlencode() (at least in 2.7.2) uses quote_plus() instead of quote() and thus encodes spaces as "+". It seems also that the W3C recommendation is the "+" as per here: http://www.w3.org/TR/html4/interact/forms.html#h-17.13.4.1

And in fact, you can follow this interesting debate on Python's own issue tracker about what to use to encode spaces: http://bugs.python.org/issue13866.

EDIT #2:

I understand that the most common way of encoding " " is as "+", but just a note, it may be just me, but I find this a bit confusing:

import urllib
print(urllib.urlencode({' ' : '+ '})

>>> '+=%2B+'

How to set time to midnight for current day?

Using some of the above recommendations, the following function and code is working for search a date range:

Set date with the time component set to 00:00:00

public static DateTime GetDateZeroTime(DateTime date)
{
    return new DateTime(date.Year, date.Month, date.Day, 0, 0, 0);
}

Usage

var modifieddatebegin = Tools.Utilities.GetDateZeroTime(form.modifieddatebegin);

var modifieddateend = Tools.Utilities.GetDateZeroTime(form.modifieddateend.AddDays(1));

Display List in a View MVC

Your action method considers model type asList<string>. But, in your view you are waiting for IEnumerable<Standings.Models.Teams>. You can solve this problem with changing the model in your view to List<string>.

But, the best approach would be to return IEnumerable<Standings.Models.Teams> as a model from your action method. Then you haven't to change model type in your view.

But, in my opinion your models are not correctly implemented. I suggest you to change it as:

public class Team
{
    public int Position { get; set; }
    public string HomeGround {get; set;}
    public string NickName {get; set;}
    public int Founded { get; set; }
    public string Name { get; set; }
}

Then you must change your action method as:

public ActionResult Index()
{
    var model = new List<Team>();

    model.Add(new Team { Name = "MU"});
    model.Add(new Team { Name = "Chelsea"});
    ...

    return View(model);
}

And, your view:

@model IEnumerable<Standings.Models.Team>

@{
     ViewBag.Title = "Standings";
}

@foreach (var item in Model)
{
    <div>
        @item.Name
        <hr />
    </div>
}

How do I limit the number of returned items?

Find parameters

The parameters find function takes are as follows:

  1. conditions «Object».
  2. [projection] «Object|String» optional fields to return, see Query.prototype.select()
  3. [options] «Object» optional see Query.prototype.setOptions()
  4. [callback] «Function»

How to limit

const Post = require('./models/Post');

Post.find(
  { published: true }, 
  null, 
  { sort: { 'date': 'asc' }, limit: 20 },
  function(error, posts) {
   if (error) return `${error} while finding from post collection`;

   return posts; // posts with sorted length of 20
  }
);

Extra Info

Mongoose allows you to query your collections in different ways like: Official Documentation

// named john and at least 18
MyModel.find({ name: 'john', age: { $gte: 18 }});

// executes, passing results to callback
MyModel.find({ name: 'john', age: { $gte: 18 }}, function (err, docs) {});

// executes, name LIKE john and only selecting the "name" and "friends" fields
MyModel.find({ name: /john/i }, 'name friends', function (err, docs) { })

// passing options
MyModel.find({ name: /john/i }, null, { skip: 10 })

// passing options and executes
MyModel.find({ name: /john/i }, null, { skip: 10 }, function (err, docs) {});

// executing a query explicitly
var query = MyModel.find({ name: /john/i }, null, { skip: 10 })
query.exec(function (err, docs) {});

// using the promise returned from executing a query
var query = MyModel.find({ name: /john/i }, null, { skip: 10 });
var promise = query.exec();
promise.addBack(function (err, docs) {});

Maven2: Best practice for Enterprise Project (EAR file)

NetBeans IDE automatically defines the structure which is almost similar to one suggested by Patrick Garner. For NetBeans users

File->New Project ->In left side select Maven and In right side select Maven Enterprise Application and press Next -> Asks for project names for both war,ejb and settings.

The IDE will automatically create the structure for you.

Add php variable inside echo statement as href link address?

You can use one and more echo statement inside href

<a href="profile.php?usr=<?php echo $_SESSION['firstname']."&email=". $_SESSION['email']; ?> ">Link</a>

link : "/profile.php?usr=firstname&email=email"

Use 'class' or 'typename' for template parameters?

It doesn't matter at all, but class makes it look like T can only be a class, while it can of course be any type. So typename is more accurate. On the other hand, most people use class, so that is probably easier to read generally.

How to make Twitter Bootstrap tooltips have multiple lines?

The CSS solution for Angular Bootstrap is

::ng-deep .tooltip-inner {
  white-space: pre-wrap;
}

No need to use a parent element or class selector if you don't need to restrict it's use. Copy/Pasta, and this rule will apply to all sub-components

How to make PyCharm always show line numbers

v. community 5.0.4 (linux): File -> Settings -> Editor -> General -> Appearance -> now check 'Show line numbers', confirm w. OK an voila :)

How can I make a HTML a href hyperlink open a new window?

<a href="#" onClick="window.open('http://www.yahoo.com', '_blank')">test</a>

Easy as that.

Or without JS

<a href="http://yahoo.com" target="_blank">test</a>

Bootstrap Navbar toggle button not working

because u have to have jquery set-up to enable the toggling functionality of the toggler button. So, all u have to do is to add bootstrap.bundle.js before bootstrap.css:

<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>

<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-ho+j7jyWK8fNQe+A12Hb8AhRq26LrZ/JpcUGGOn+Y7RsweNrtN/tE3MoK7ZeZDyx" crossorigin="anonymous"></script>

How to check for a JSON response using RSpec?

For Your JSON response you should parse that response for expected results For Instance: parsed_response = JSON.parse(response.body)

You can check other variables which is included in response like

expect(parsed_response["success"]).to eq(true)
expect(parsed_response["flashcard"]).to eq("flashcard expected value")
expect(parsed_response["lesson"]).to eq("lesson expected value")
expect(subject["status_code"]).to eq(201)

I prefer also check keys of JSON response, For Example:

expect(body_as_json.keys).to match_array(["success", "lesson","status_code", "flashcard"])

Here, We can use should matchers For expected results in Rspec

What possibilities can cause "Service Unavailable 503" error?

If the server doesn't have enough memory also will cause this problem. This is my personal experience with Godaddy VPS.

Shell script "for" loop syntax

Well, as I didn't have the seq command installed on my system (Mac OS X v10.6.1 (Snow Leopard)), I ended up using a while loop instead:

max=5
i=1

while [ $max -gt $i ]
do
    (stuff)
done

*Shrugs* Whatever works.

Regular expression to match exact number of characters?

Your solution is correct, but there is some redundancy in your regex.
The similar result can also be obtained from the following regex:

^([A-Z]{3})$

The {3} indicates that the [A-Z] must appear exactly 3 times.

Python Accessing Nested JSON Data

I'm using this lib to access nested dict keys

https://github.com/mewwts/addict

 import requests
 from addict import Dict
 r = requests.get('http://api.zippopotam.us/us/ma/belmont')
 j = Dict(r.json())

 print j.state
 print j.places[1]['post code']  # only work with keys without '-', space, or starting with number 

MySQL join with where clause

Try this

  SELECT *
    FROM categories
    LEFT JOIN user_category_subscriptions 
         ON user_category_subscriptions.category_id = categories.category_id 
   WHERE user_category_subscriptions.user_id = 1 
          or user_category_subscriptions.user_id is null

VirtualBox and vmdk vmx files

Actually, for the configuration of the machine, just open the .vmx file with a text editor (e.g. notepad, gedit, etc.). You will be able to see the OS type, memsize, ethernet.connectionType, and other settings. Then when you make your machine, just look in the text editor for the corresponding settings. When it asks for the disk, select the .vmdk disk as mentioned above.

Change the default editor for files opened in the terminal? (e.g. set it to TextEdit/Coda/Textmate)

Set your editor to point to this program:

/Applications/TextEdit.app/Contents/MacOS/TextEdit

With SVN, you should set SVN_EDITOR environment variable to:

$ export SVN_EDITOR=/Applications/TextEdit.app/Contents/MacOS/TextEdit

And then, when you try committing something, TextEdit will launch.

batch/bat to copy folder and content at once

For Folder Copy You can Use

robocopy C:\Source D:\Destination /E

For File Copy

copy D:\Sourcefile.txt D:\backup\Destinationfile.txt /Y 

Delete file in some folder last modify date more than some day

forfiles -p "D:\FolderPath" -s -m *.[Filetype eg-->.txt] -d -[Numberof dates] -c "cmd /c del @PATH"

And you can Shedule task in windows perform this task automatically in specific time.

HTTP Status 405 - Request method 'POST' not supported (Spring MVC)

I found the problem that was causing the HTTP error.

In the setFalse() function that is triggered by the Save button my code was trying to submit the form that contained the button.

        function setFalse(){
            document.getElementById("hasId").value ="false";
            document.deliveryForm.submit();
            document.submitForm.submit();

when I remove the document.submitForm.submit(); it works:

        function setFalse(){
            document.getElementById("hasId").value ="false";
            document.deliveryForm.submit()

@Roger Lindsjö Thank you for spotting my error where I wasn't passing on the right parameter!

Excel 2013 horizontal secondary axis

You should follow the guidelines on Add a secondary horizontal axis:

Add a secondary horizontal axis

To complete this procedure, you must have a chart that displays a secondary vertical axis. To add a secondary vertical axis, see Add a secondary vertical axis.

  1. Click a chart that displays a secondary vertical axis. This displays the Chart Tools, adding the Design, Layout, and Format tabs.

  2. On the Layout tab, in the Axes group, click Axes.

    enter image description here

  3. Click Secondary Horizontal Axis, and then click the display option that you want.

enter image description here


Add a secondary vertical axis

You can plot data on a secondary vertical axis one data series at a time. To plot more than one data series on the secondary vertical axis, repeat this procedure for each data series that you want to display on the secondary vertical axis.

  1. In a chart, click the data series that you want to plot on a secondary vertical axis, or do the following to select the data series from a list of chart elements:

    • Click the chart.

      This displays the Chart Tools, adding the Design, Layout, and Format tabs.

    • On the Format tab, in the Current Selection group, click the arrow in the Chart Elements box, and then click the data series that you want to plot along a secondary vertical axis.

      enter image description here

  2. On the Format tab, in the Current Selection group, click Format Selection. The Format Data Series dialog box is displayed.

    Note: If a different dialog box is displayed, repeat step 1 and make sure that you select a data series in the chart.

  3. On the Series Options tab, under Plot Series On, click Secondary Axis and then click Close.

    A secondary vertical axis is displayed in the chart.

  4. To change the display of the secondary vertical axis, do the following:

    • On the Layout tab, in the Axes group, click Axes.

    • Click Secondary Vertical Axis, and then click the display option that you want.

  5. To change the axis options of the secondary vertical axis, do the following:

    • Right-click the secondary vertical axis, and then click Format Axis.

    • Under Axis Options, select the options that you want to use.

adding x and y axis labels in ggplot2

since the data ex1221new was not given, so I have created a dummy data and added it to a data frame. Also, the question which was asked has few changes in codes like then ggplot package has deprecated the use of

"scale_area()" and nows uses scale_size_area()
"opts()" has changed to theme()

In my answer,I have stored the plot in mygraph variable and then I have used

mygraph$labels$x="Discharge of materials" #changes x axis title
       mygraph$labels$y="Area Affected" # changes y axis title

And the work is done. Below is the complete answer.

install.packages("Sleuth2")
library(Sleuth2)
library(ggplot2)

ex1221new<-data.frame(Discharge<-c(100:109),Area<-c(120:129),NO3<-seq(2,5,length.out = 10))
discharge<-ex1221new$Discharge
area<-ex1221new$Area
nitrogen<-ex1221new$NO3
p <- ggplot(ex1221new, aes(discharge, area), main="Point")
mygraph<-p + geom_point(aes(size= nitrogen)) + 
  scale_size_area() + ggtitle("Weighted Scatterplot of Watershed Area vs. Discharge and Nitrogen Levels (PPM)")+
theme(
 plot.title =  element_text(color="Blue", size=30, hjust = 0.5), 

 # change the styling of both the axis simultaneously from this-
 axis.title = element_text(color = "Green", size = 20, family="Courier",)
 

   # you can change the  axis title from the code below
   mygraph$labels$x="Discharge of materials" #changes x axis title
   mygraph$labels$y="Area Affected" # changes y axis title
   mygraph



   

Also, you can change the labels title from the same formula used above -

mygraph$labels$size= "N2" #size contains the nitrogen level 

How to put a Scanner input into an array... for example a couple of numbers

You could try something like this:

public static void main (String[] args)
{
    Scanner input = new Scanner(System.in);
    double[] numbers = new double[5];

    for (int i = 0; i < numbers.length; i++)
    {
        System.out.println("Please enter number");
        numbers[i] = input.nextDouble();
    }
}

It seems pretty basic stuff unless I am misunderstanding you

Getting or changing CSS class property with Javascript using DOM style

If you are looking for sending color data from backend

def color():
    color = "#{:06x}".format(random.randint(0, 0xFFFFFF))
    return color

scp with port number specified

To backup all files in all directories to a remote Synology NAS using a different remote port:

scp -P 10022 -r /media/data/somedata/* [email protected]:/var/services/homes/user/directory/

Types in Objective-C on iOS

Note that you can also use the C99 fixed-width types perfectly well in Objective-C:

#import <stdint.h>
...
int32_t x; // guaranteed to be 32 bits on any platform

The wikipedia page has a decent description of what's available in this header if you don't have a copy of the C standard (you should, though, since Objective-C is just a tiny extension of C). You may also find the headers limits.h and inttypes.h to be useful.

submit a form in a new tab

Try using jQuery

<script type="text/javascript">
$("form").submit(function() {
$("form").attr('target', '_blank');
return true;
});
</script>

Here is a full answer - http://ftutorials.com/open-html-form-in-new-tab/

How to use HTML Agility pack

First, install the HTMLAgilityPack nuget package into your project.

Then, as an example:

HtmlAgilityPack.HtmlDocument htmlDoc = new HtmlAgilityPack.HtmlDocument();

// There are various options, set as needed
htmlDoc.OptionFixNestedTags=true;

// filePath is a path to a file containing the html
htmlDoc.Load(filePath);

// Use:  htmlDoc.LoadHtml(xmlString);  to load from a string (was htmlDoc.LoadXML(xmlString)

// ParseErrors is an ArrayList containing any errors from the Load statement
if (htmlDoc.ParseErrors != null && htmlDoc.ParseErrors.Count() > 0)
{
    // Handle any parse errors as required

}
else
{

    if (htmlDoc.DocumentNode != null)
    {
        HtmlAgilityPack.HtmlNode bodyNode = htmlDoc.DocumentNode.SelectSingleNode("//body");

        if (bodyNode != null)
        {
            // Do something with bodyNode
        }
    }
}

(NB: This code is an example only and not necessarily the best/only approach. Do not use it blindly in your own application.)

The HtmlDocument.Load() method also accepts a stream which is very useful in integrating with other stream oriented classes in the .NET framework. While HtmlEntity.DeEntitize() is another useful method for processing html entities correctly. (thanks Matthew)

HtmlDocument and HtmlNode are the classes you'll use most. Similar to an XML parser, it provides the selectSingleNode and selectNodes methods that accept XPath expressions.

Pay attention to the HtmlDocument.Option?????? boolean properties. These control how the Load and LoadXML methods will process your HTML/XHTML.

There is also a compiled help file called HtmlAgilityPack.chm that has a complete reference for each of the objects. This is normally in the base folder of the solution.

How to get multiple selected values of select box in php?

If you want PHP to treat $_GET['select2'] as an array of options just add square brackets to the name of the select element like this: <select name="select2[]" multiple …

Then you can acces the array in your PHP script

<?php
header("Content-Type: text/plain");

foreach ($_GET['select2'] as $selectedOption)
    echo $selectedOption."\n";

$_GET may be substituted by $_POST depending on the <form method="…" value.

Getting the name of the currently executing method

MethodHandles.lookup().lookupClass().getEnclosingMethod().getName();

Forbidden: You don't have permission to access / on this server, WAMP Error

This could be one solution.

public class RegisterActivity extends AppCompatActivity {

    private static final String TAG = "RegisterActivity";
    private static final String URL_FOR_REGISTRATION = "http://192.168.10.4/android_login_example/register.php";
    ProgressDialog progressDialog;

    private EditText signupInputName, signupInputEmail, signupInputPassword, signupInputAge;
    private Button btnSignUp;
    private Button btnLinkLogin;
    private RadioGroup genderRadioGroup;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        // Progress dialog
        progressDialog = new ProgressDialog(this);
        progressDialog.setCancelable(false);

        signupInputName = (EditText) findViewById(R.id.signup_input_name);
        signupInputEmail = (EditText) findViewById(R.id.signup_input_email);
        signupInputPassword = (EditText) findViewById(R.id.signup_input_password);
        signupInputAge = (EditText) findViewById(R.id.signup_input_age);

        btnSignUp = (Button) findViewById(R.id.btn_signup);
        btnLinkLogin = (Button) findViewById(R.id.btn_link_login);

        genderRadioGroup = (RadioGroup) findViewById(R.id.gender_radio_group);
        btnSignUp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                submitForm();
            }
        });
        btnLinkLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                Intent i = new Intent(getApplicationContext(),MainActivity.class);
                startActivity(i);
            }
        });
    }

    private void submitForm() {

        int selectedId = genderRadioGroup.getCheckedRadioButtonId();
        String gender;
        if(selectedId == R.id.female_radio_btn)
            gender = "Female";
        else
            gender = "Male";

        registerUser(signupInputName.getText().toString(),
                signupInputEmail.getText().toString(),
                signupInputPassword.getText().toString(),
                gender,
                signupInputAge.getText().toString());
    }

    private void registerUser(final String name,  final String email, final String password,
                              final String gender, final String dob) {
        // Tag used to cancel the request
        String cancel_req_tag = "register";

        progressDialog.setMessage("Adding you ...");
        showDialog();

        StringRequest strReq = new StringRequest(Request.Method.POST,
                URL_FOR_REGISTRATION, new Response.Listener<String>() {

            @Override
            public void onResponse(String response) {
                Log.d(TAG, "Register Response: " + response.toString());
                hideDialog();

                try {
                    JSONObject jObj = new JSONObject(response);
                    boolean error = jObj.getBoolean("error");

                    if (!error) {
                        String user = jObj.getJSONObject("user").getString("name");
                        Toast.makeText(getApplicationContext(), "Hi " + user +", You are successfully Added!", Toast.LENGTH_SHORT).show();

                        // Launch login activity
                        Intent intent = new Intent(
                                RegisterActivity.this,
                                MainActivity.class);
                        startActivity(intent);
                        finish();
                    } else {



                        String errorMsg = jObj.getString("error_msg");
                        Toast.makeText(getApplicationContext(),
                                errorMsg, Toast.LENGTH_LONG).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e(TAG, "Registration Error: " + error.getMessage());
                Toast.makeText(getApplicationContext(),
                        error.getMessage(), Toast.LENGTH_LONG).show();
                hideDialog();
            }
        }) {
            @Override
            protected Map<String, String> getParams() {
                // Posting params to register url
                Map<String, String> params = new HashMap<String, String>();
                params.put("name", name);
                params.put("email", email);
                params.put("password", password);
                params.put("gender", gender);
                params.put("age", dob);
                return params;
            }
        };
        // Adding request to request queue
        AppSingleton.getInstance(getApplicationContext()).addToRequestQueue(strReq, cancel_req_tag);
    }

    private void showDialog() {
        if (!progressDialog.isShowing())
            progressDialog.show();
    }

    private void hideDialog() {
        if (progressDialog.isShowing())
            progressDialog.dismiss();
    }
    }

iOS 8 removed "minimal-ui" viewport property, are there other "soft fullscreen" solutions?

It is possible to get a web application running in full screen in both iOS and Android, it is called a PWA and after mucha hard work, it was the only way around this issue.

PWAs open a number of interesting options for development that should not be missed. I've made a couple already, check out this Public and Private Tender Manual For Designers (Spanish). And here is an English explanation from the CosmicJS site

Sum values in a column based on date

Use a column to let each date be shown as month number; another column for day number:

      A      B       C         D
   -----  ----- ----------- --------
1     8      6    8/6/2010   12.70
2     8      7    8/7/2010   10.50
3     8      7    8/7/2010    7.10
4     8      9    8/9/2010   10.50
5     8     10   8/10/2010   15.00

The formula for A1 is =Month(C1)

The formula for B1 is =Day(C1)

For Month sums, put the month number next to each month:

      E      F         G     
   -----  ----- -------------  
1     7    July   $1,000,010 
2     8     Aug   $1,200,300 

The formula for G1 is =SumIf($A$1:$A$100, E1, $D$1:$D$100). This is a portable formula; just copy it down.

Total for the day will be be a bit more complicated, but you can probably see how to do it.

How can I get a Bootstrap column to span multiple rows?

I believe the part regarding how to span rows has been answered thoroughly (i.e. by nesting rows), but I also ran into the issue of my nested rows not filling their container. While flexbox and negative margins are an option, a much easier solution is to use the predefined h-50 class on the row containing boxes 2, 3, 4, and 5.

Note: I am using Bootstrap-4, I just wanted to share because I ran into the same problem and found this to be a more elegant solution :)

Explode string by one or more spaces or tabs

@OP it doesn't matter, you can just split on a space with explode. Until you want to use those values, iterate over the exploded values and discard blanks.

$str = "A      B      C      D";
$s = explode(" ",$str);
foreach ($s as $a=>$b){    
    if ( trim($b) ) {
     print "using $b\n";
    }
}

How can I get the iOS 7 default blue color programmatically?

From iOS 7 there is an API and you can get (and set) the tint color with:

self.view.tintColor

Or if you need the CGColor:

self.view.tintColor.CGColor

Regular expression \p{L} and \p{N}

These are Unicode property shortcuts (\p{L} for Unicode letters, \p{N} for Unicode digits). They are supported by .NET, Perl, Java, PCRE, XML, XPath, JGSoft, Ruby (1.9 and higher) and PHP (since 5.1.0)

At any rate, that's a very strange regex. You should not be using alternation when a character class would suffice:

[\p{L}\p{N}_.-]*

You cannot call a method on a null-valued expression

The simple answer for this one is that you have an undeclared (null) variable. In this case it is $md5. From the comment you put this needed to be declared elsewhere in your code

$md5 = new-object -TypeName System.Security.Cryptography.MD5CryptoServiceProvider

The error was because you are trying to execute a method that does not exist.

PS C:\Users\Matt> $md5 | gm


   TypeName: System.Security.Cryptography.MD5CryptoServiceProvider

Name                       MemberType Definition                                                                                                                            
----                       ---------- ----------                                                                                                                            
Clear                      Method     void Clear()                                                                                                                          
ComputeHash                Method     byte[] ComputeHash(System.IO.Stream inputStream), byte[] ComputeHash(byte[] buffer), byte[] ComputeHash(byte[] buffer, int offset, ...

The .ComputeHash() of $md5.ComputeHash() was the null valued expression. Typing in gibberish would create the same effect.

PS C:\Users\Matt> $bagel.MakeMeABagel()
You cannot call a method on a null-valued expression.
At line:1 char:1
+ $bagel.MakeMeABagel()
+ ~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

PowerShell by default allows this to happen as defined its StrictMode

When Set-StrictMode is off, uninitialized variables (Version 1) are assumed to have a value of 0 (zero) or $Null, depending on type. References to non-existent properties return $Null, and the results of function syntax that is not valid vary with the error. Unnamed variables are not permitted.

How to grep a string in a directory and all its subdirectories?

grep -r -e string directory

-r is for recursive; -e is optional but its argument specifies the regex to search for. Interestingly, POSIX grep is not required to support -r (or -R), but I'm practically certain that System V grep did, so in practice they (almost) all do. Some versions of grep support -R as well as (or conceivably instead of) -r; AFAICT, it means the same thing.

How do I check to see if my array includes an object?

#include? should work, it works for general objects, not only strings. Your problem in example code is this test:

unless @suggested_horses.exists?(horse.id)
  @suggested_horses<< horse
end

(even assuming using #include?). You try to search for specific object, not for id. So it should be like this:

unless @suggested_horses.include?(horse)
  @suggested_horses << horse
end

ActiveRecord has redefined comparision operator for objects to take a look only for its state (new/created) and id

Cleanest Way to Invoke Cross-Thread Events

Use the synchronisation context if you want to send a result to the UI thread. I needed to change the thread priority so I changed from using thread pool threads (commented out code) and created a new thread of my own. I was still able to use the synchronisation context to return whether the database cancel succeeded or not.

    #region SyncContextCancel

    private SynchronizationContext _syncContextCancel;

    /// <summary>
    /// Gets the synchronization context used for UI-related operations.
    /// </summary>
    /// <value>The synchronization context.</value>
    protected SynchronizationContext SyncContextCancel
    {
        get { return _syncContextCancel; }
    }

    #endregion //SyncContextCancel

    public void CancelCurrentDbCommand()
    {
        _syncContextCancel = SynchronizationContext.Current;

        //ThreadPool.QueueUserWorkItem(CancelWork, null);

        Thread worker = new Thread(new ThreadStart(CancelWork));
        worker.Priority = ThreadPriority.Highest;
        worker.Start();
    }

    SQLiteConnection _connection;
    private void CancelWork()//object state
    {
        bool success = false;

        try
        {
            if (_connection != null)
            {
                log.Debug("call cancel");
                _connection.Cancel();
                log.Debug("cancel complete");
                _connection.Close();
                log.Debug("close complete");
                success = true;
                log.Debug("long running query cancelled" + DateTime.Now.ToLongTimeString());
            }
        }
        catch (Exception ex)
        {
            log.Error(ex.Message, ex);
        }

        SyncContextCancel.Send(CancelCompleted, new object[] { success });
    }

    public void CancelCompleted(object state)
    {
        object[] args = (object[])state;
        bool success = (bool)args[0];

        if (success)
        {
            log.Debug("long running query cancelled" + DateTime.Now.ToLongTimeString());

        }
    }

Initializing an Array of Structs in C#

Are you using C# 3.0? You can use object initializers like so:

static MyStruct[] myArray = 
            new MyStruct[]{
                new MyStruct() { id = 1, label = "1" },
                new MyStruct() { id = 2, label = "2" },
                new MyStruct() { id = 3, label = "3" }
            };

How can I see the raw SQL queries Django is running?

I put this function in a util file in one of the apps in my project:

import logging
import re

from django.db import connection

logger = logging.getLogger(__name__)

def sql_logger():
    logger.debug('TOTAL QUERIES: ' + str(len(connection.queries)))
    logger.debug('TOTAL TIME: ' + str(sum([float(q['time']) for q in connection.queries])))

    logger.debug('INDIVIDUAL QUERIES:')
    for i, query in enumerate(connection.queries):
        sql = re.split(r'(SELECT|FROM|WHERE|GROUP BY|ORDER BY|INNER JOIN|LIMIT)', query['sql'])
        if not sql[0]: sql = sql[1:]
        sql = [(' ' if i % 2 else '') + x for i, x in enumerate(sql)]
        logger.debug('\n### {} ({} seconds)\n\n{};\n'.format(i, query['time'], '\n'.join(sql)))

Then, when needed, I just import it and call it from whatever context (usually a view) is necessary, e.g.:

# ... other imports
from .utils import sql_logger

class IngredientListApiView(generics.ListAPIView):
    # ... class variables and such

    # Main function that gets called when view is accessed
    def list(self, request, *args, **kwargs):
        response = super(IngredientListApiView, self).list(request, *args, **kwargs)

        # Call our function
        sql_logger()

        return response

It's nice to do this outside the template because then if you have API views (usually Django Rest Framework), it's applicable there too.

What function is to replace a substring from a string in C?

You can use this function (the comments explain how it works):

void strreplace(char *string, const char *find, const char *replaceWith){
    if(strstr(string, replaceWith) != NULL){
        char *temporaryString = malloc(strlen(strstr(string, find) + strlen(find)) + 1);
        strcpy(temporaryString, strstr(string, find) + strlen(find));    //Create a string with what's after the replaced part
        *strstr(string, find) = '\0';    //Take away the part to replace and the part after it in the initial string
        strcat(string, replaceWith);    //Concat the first part of the string with the part to replace with
        strcat(string, temporaryString);    //Concat the first part of the string with the part after the replaced part
        free(temporaryString);    //Free the memory to avoid memory leaks
    }
}

Visual Studio 2012 Web Publish doesn't copy files

In Visual Studio 2012, switching between releases still causes problems.

We added a pre-build event to delete the obj folder: del /s /f /q $(ProjectDir)\obj and it fixed the issue of publishing. Cleaning works sometimes, but not always.

Performing SQL queries on an Excel Table within a Workbook with VBA Macro

Public Function GetRange(ByVal sListName As String) As String

Dim oListObject As ListObject
Dim wb As Workbook
Dim ws As Worksheet

Set wb = ThisWorkbook

For Each ws In wb.Sheets
    For Each oListObject In ws.ListObjects
        If oListObject.Name = sListName Then
            GetRange = "[" & ws.Name & "$" & Replace(oListObject.Range.Address, "$", "") & "]"
        Exit Function
        End If
    Next oListObject
Next ws


End Function

In your SQL use it like this

sSQL = "Select * from " & GetRange("NameOfTable") & ""

Verify object attribute value with mockito

Another easy way to do so:

import org.mockito.BDDMockito;    
import static org.mockito.Matchers.argThat;
import org.mockito.ArgumentMatcher;

BDDMockito.verify(mockedObject)
        .someMethodOnMockedObject(argThat(new ArgumentMatcher<TypeOfMethodArg>() {

            @Override
            public boolean matches(Object argument) {
                final TypeOfMethodArg castedArg = (TypeOfMethodArg) argument;

                // Make your verifications and return a boolean to say if it matches or not
                boolean isArgMarching = true;

                return isArgMarching;
            }
        }));

Why does Node.js' fs.readFile() return a buffer instead of string?

The data variable contains a Buffer object. Convert it into ASCII encoding using the following syntax:

data.toString('ascii', 0, data.length)

Asynchronously:

fs.readFile('test.txt', 'utf8', function (error, data) {
    if (error) throw error;
    console.log(data.toString());
});

Letter Count on a string

def count_letter(word, char):
    count = 0
    for char in word:
        if char == word:
            count += 1
    return count        #Your return is inside your for loop
r = count_word("banana", "a")
print r

3

String replacement in Objective-C

It also posible string replacement with stringByReplacingCharactersInRange:withString:

for (int i = 0; i < card.length - 4; i++) {

    if (![[card substringWithRange:NSMakeRange(i, 1)] isEqual:@" "]) {

        NSRange range = NSMakeRange(i, 1);
        card = [card stringByReplacingCharactersInRange:range withString:@"*"];

    }

} //out: **** **** **** 1234

Write single CSV file using spark-csv

by using Listbuffer we can save data into single file:

import java.io.FileWriter
import org.apache.spark.sql.SparkSession
import scala.collection.mutable.ListBuffer
    val text = spark.read.textFile("filepath")
    var data = ListBuffer[String]()
    for(line:String <- text.collect()){
      data += line
    }
    val writer = new FileWriter("filepath")
    data.foreach(line => writer.write(line.toString+"\n"))
    writer.close()

How to make php display \t \n as tab and new line instead of characters

You can use HTML,

foreach(...)
echo $data1 . '&nbsp' . $data2 . '&nbsp' . $data3 . '<br/>';

Why isn't my Pandas 'apply' function referencing multiple columns working?

If you just want to compute (column a) % (column b), you don't need apply, just do it directly:

In [7]: df['a'] % df['c']                                                                                                                                                        
Out[7]: 
0   -1.132022                                                                                                                                                                    
1   -0.939493                                                                                                                                                                    
2    0.201931                                                                                                                                                                    
3    0.511374                                                                                                                                                                    
4   -0.694647                                                                                                                                                                    
5   -0.023486                                                                                                                                                                    
Name: a

AWS S3 - How to fix 'The request signature we calculated does not match the signature' error?

I had the same problem when tried to copy an object with some UTF8 characters. Below is a JS example:

var s3 = new AWS.S3();

s3.copyObject({
    Bucket: 'somebucket',
    CopySource: 'path/to/Weird_file_name_ðO´pi´u.jpg',
    Key: 'destination/key.jpg',
    ACL: 'authenticated-read'
}, cb);

Solved by encoding the CopySource with encodeURIComponent()

Node.js request CERT_HAS_EXPIRED

I think the strictSSL: false should (should have worked, even in 2013) work. So in short are three possible ways:

  1. (obvious) Get your CA to renew the certificate, and put it on your server!
  2. Change the default settings of your request object:

    const myRequest = require('request').defaults({strictSSL: false})

    Many modules that use node-request internally also allow a request-object to be injected, so you can make them use your modified instance.
  3. (not recommended) Override all certificate checks for all HTTP(S) agent connections by setting the environment variable NODE_TLS_REJECT_UNAUTHORIZED=0 for the Node.js process.

Using Ajax.BeginForm with ASP.NET MVC 3 Razor

I think that all the answers missed a crucial point:

If you use the Ajax form so that it needs to update itself (and NOT another div outside of the form) then you need to put the containing div OUTSIDE of the form. For example:

 <div id="target">
 @using (Ajax.BeginForm("MyAction", "MyController",
            new AjaxOptions
            {
                HttpMethod = "POST",
                InsertionMode = InsertionMode.Replace,
                UpdateTargetId = "target"
            }))
 {
      <!-- whatever -->
 }
 </div>

Otherwise you will end like @David where the result is displayed in a new page.

How to update primary key

You could use this recursive function for generate necessary T-SQL script.

CREATE FUNCTION dbo.Update_Delete_PrimaryKey
(
    @TableName      NVARCHAR(255),
    @ColumnName     NVARCHAR(255),
    @OldValue       NVARCHAR(MAX),
    @NewValue       NVARCHAR(MAX),
    @Del            BIT
)
RETURNS NVARCHAR 
(
    MAX
)
AS
BEGIN
    DECLARE @fks TABLE 
            (
                constraint_name NVARCHAR(255),
                table_name NVARCHAR(255),
                col NVARCHAR(255)
            );
    DECLARE @Sql                  NVARCHAR(MAX),
            @EnableConstraints     NVARCHAR(MAX);

    SET @Sql = '';
    SET @EnableConstraints = '';

    INSERT INTO @fks
      (
        constraint_name,
        table_name,
        col
      )
    SELECT oConstraint.name     constraint_name,
           oParent.name         table_name,
           oParentCol.name      col
    FROM   sys.foreign_key_columns sfkc
           --INNER JOIN sys.foreign_keys sfk
           --     ON  sfk.[object_id] = sfkc.constraint_object_id

           INNER JOIN sys.sysobjects oConstraint
                ON  sfkc.constraint_object_id = oConstraint.id
           INNER JOIN sys.sysobjects oParent
                ON  sfkc.parent_object_id = oParent.id
           INNER JOIN sys.all_columns oParentCol
                ON  sfkc.parent_object_id = oParentCol.object_id
                AND sfkc.parent_column_id = oParentCol.column_id
           INNER JOIN sys.sysobjects oReference
                ON  sfkc.referenced_object_id = oReference.id
           INNER JOIN sys.all_columns oReferenceCol
                ON  sfkc.referenced_object_id = oReferenceCol.object_id
                AND sfkc.referenced_column_id = oReferenceCol.column_id
    WHERE  oReference.name = @TableName
           AND oReferenceCol.name = @ColumnName
    --AND (@Del <> 1 OR sfk.delete_referential_action = 0)
    --AND (@Del = 1 OR sfk.update_referential_action = 0)

    IF EXISTS(
           SELECT 1
           FROM   @fks
       )
    BEGIN
        DECLARE @Constraint     NVARCHAR(255),
                @Table          NVARCHAR(255),
                @Col            NVARCHAR(255)  

        DECLARE Table_Cursor CURSOR LOCAL 
        FOR
            SELECT f.constraint_name,
                   f.table_name,
                   f.col
            FROM   @fks AS f

        OPEN Table_Cursor FETCH NEXT FROM Table_Cursor INTO @Constraint, @Table,@Col  
        WHILE (@@FETCH_STATUS = 0)
        BEGIN
            IF @Del <> 1
            BEGIN
                SET @Sql = @Sql + 'ALTER TABLE ' + @Table + ' NOCHECK CONSTRAINT ' + @Constraint + CHAR(13) + CHAR(10);
                SET @EnableConstraints = @EnableConstraints + 'ALTER TABLE ' + @Table + ' CHECK CONSTRAINT ' + @Constraint 
                    + CHAR(13) + CHAR(10);
            END

            SET @Sql = @Sql + dbo.Update_Delete_PrimaryKey(@Table, @Col, @OldValue, @NewValue, @Del);
            FETCH NEXT FROM Table_Cursor INTO @Constraint, @Table,@Col
        END

        CLOSE Table_Cursor DEALLOCATE Table_Cursor
    END

    DECLARE @DataType NVARCHAR(30);
    SELECT @DataType = t.name +
           CASE 
                WHEN t.name IN ('char', 'varchar', 'nchar', 'nvarchar') THEN '(' +
                     CASE 
                          WHEN c.max_length = -1 THEN 'MAX'
                          ELSE CONVERT(
                                   VARCHAR(4),
                                   CASE 
                                        WHEN t.name IN ('nchar', 'nvarchar') THEN c.max_length / 2
                                        ELSE c.max_length
                                   END
                               )
                     END + ')'
                WHEN t.name IN ('decimal', 'numeric') THEN '(' + CONVERT(VARCHAR(4), c.precision) + ',' 
                     + CONVERT(VARCHAR(4), c.Scale) + ')'
                ELSE ''
           END
    FROM   sys.columns c
           INNER JOIN sys.types t
                ON  c.user_type_id = t.user_type_id
    WHERE  c.object_id = OBJECT_ID(@TableName)
           AND c.name = @ColumnName

    IF @Del <> 1
    BEGIN
        SET @Sql = @Sql + 'UPDATE [' + @TableName + '] SET [' + @ColumnName + '] = CONVERT(' + @DataType + ', ' + ISNULL('N''' + @NewValue + '''', 'NULL') 
            + ') WHERE [' + @ColumnName + '] = CONVERT(' + @DataType + ', ' + ISNULL('N''' + @OldValue + '''', 'NULL') +
            ');' + CHAR(13) + CHAR(10);
        SET @Sql = @Sql + @EnableConstraints;
    END
    ELSE
        SET @Sql = @Sql + 'DELETE [' + @TableName + '] WHERE [' + @ColumnName + '] = CONVERT(' + @DataType + ', N''' + @OldValue 
            + ''');' + CHAR(13) + CHAR(10);
    RETURN @Sql;
END
GO

DECLARE @Result NVARCHAR(MAX);
SET @Result = dbo.Update_Delete_PrimaryKey('@TableName', '@ColumnName', '@OldValue', '@NewValue', 0);/*Update*/
EXEC (@Result)
SET @Result = dbo.Update_Delete_PrimaryKey('@TableName', '@ColumnName', '@OldValue', NULL, 1);/*Delete*/
EXEC (@Result)
GO

DROP FUNCTION Update_Delete_PrimaryKey;

Regular expression for first and last name

I'm working on the app that validates International Passports (ICAO). We support only english characters. While most foreign national characters can be represented by a character in the Latin alphabet e.g. è by e, there are several national characters that require an extra letter to represent them such as the German umlaut which requires an ‘e’ to be added to the letter e.g. ä by ae.

This is the JavaScript Regex for the first and last names we use:

/^[a-zA-Z '.-]*$/

The max number of characters on the international passport is up to 31. We use maxlength="31" to better word error messages instead of including it in the regex.

Here is a snippet from our code in AngularJS 1.6 with form and error handling:

_x000D_
_x000D_
class PassportController {_x000D_
  constructor() {_x000D_
    this.details = {};_x000D_
    // English letters, spaces and the following symbols ' - . are allowed_x000D_
    // Max length determined by ng-maxlength for better error messaging_x000D_
    this.nameRegex = /^[a-zA-Z '.-]*$/;_x000D_
  }_x000D_
}_x000D_
_x000D_
angular.module('akyc', ['ngMessages'])_x000D_
  .controller('PassportController', PassportController);
_x000D_
 _x000D_
.has-error p[ng-message] {_x000D_
  color: #bc111e;_x000D_
}_x000D_
_x000D_
.tip {_x000D_
  color: #535f67;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.6/angular.min.js"></script>_x000D_
<script src="https://code.angularjs.org/1.6.6/angular-messages.min.js"></script>_x000D_
_x000D_
<main ng-app="akyc" ng-controller="PassportController as $ctrl">_x000D_
  <form name="$ctrl.form">_x000D_
_x000D_
    <div name="lastName" ng-class="{ 'has-error': $ctrl.form.lastName.$invalid} ">_x000D_
        <label for="pp-last-name">Surname</label>_x000D_
        <div class="tip">Exactly as it appears on your passport</div>_x000D_
        <div ng-messages="$ctrl.form.lastName.$error" ng-if="$ctrl.form.$submitted" id="last-name-error">_x000D_
          <p ng-message="required">Please enter your last name</p>_x000D_
          <p ng-message="maxlength">This field can be at most 31 characters long</p>_x000D_
          <p ng-message="pattern">Only English letters, spaces and the following symbols ' - . are allowed</p>_x000D_
        </div>_x000D_
        _x000D_
        <input type="text" id="pp-last-name" ng-model="$ctrl.details.lastName" name="lastName"_x000D_
               class="form-control" required ng-pattern="$ctrl.nameRegex" ng-maxlength="31" aria-describedby="last-name-error" />_x000D_
      </div>_x000D_
_x000D_
      <button type="submit" class="btn btn-primary">Test</button>_x000D_
_x000D_
  </form>_x000D_
</main>
_x000D_
_x000D_
_x000D_

Export DataTable to Excel File

I use This in page.`

 public void DTToExcel(DataTable dt)
{
    // dosya isimleri ileride ayni anda birden fazla kullanici ayni dosya üzerinde islem yapmak ister düsüncesiyle guid yapildi. 
    string FileName = Guid.NewGuid().ToString();

    FileInfo f = new FileInfo(Server.MapPath("Downloads") + string.Format("\\{0}.xlsx", FileName));
    if (f.Exists)
        f.Delete(); // delete the file if it already exist.

    HttpResponse response = HttpContext.Current.Response;
    response.Clear();
    response.ClearHeaders();
    response.ClearContent();
    response.Charset = Encoding.UTF8.WebName;
    response.AddHeader("content-disposition", "attachment; filename=" + FileName + ".xls");
    response.AddHeader("Content-Type", "application/Excel");
    response.ContentType = "application/vnd.xlsx";
    //response.AddHeader("Content-Length", file.Length.ToString());


    // create a string writer
    using (StringWriter sw = new StringWriter())
    {
        using (HtmlTextWriter htw = new HtmlTextWriter(sw)) //datatable'a aldigimiz sorguyu bir datagrid'e atayip html'e çevir.
        {
            // instantiate a datagrid
            DataGrid dg = new DataGrid();
            dg.DataSource = dt;
            dg.DataBind();
            dg.RenderControl(htw);
            response.Write(sw.ToString());
            dg.Dispose();
            dt.Dispose();
            response.End();
        }
    }
}

How to access /storage/emulated/0/

Also you can use Android Debug Bridge (adb) to copy your file from Android device to folder on your PC:

adb pull /storage/emulated/0/AudioRecorder/1436854479696.mp4 <folder_on_your_PC_e.g. c:/temp>

And you can copy from device whole AudioRecorder folder:

adb pull /storage/emulated/0/AudioRecorder <folder_on_your_PC_e.g. c:/temp>

How do I get the value of text input field using JavaScript?

I would create a variable to store the input like this:

var input = document.getElementById("input_id").value;

And then I would just use the variable to add the input value to the string.

= "Your string" + input;

How to clear or stop timeInterval in angularjs?

    $scope.toggleRightDelayed = function(){
        var myInterval = $interval(function(){
            $scope.toggleRight();
        },1000,1)
        .then(function(){
            $interval.cancel(myInterval);
        });
    };

How can I run multiple npm scripts in parallel?

How about forking

Another option to run multiple Node scripts is with a single Node script, which can fork many others. Forking is supported natively in Node, so it adds no dependencies and is cross-platform.


Minimal example

This would just run the scripts as-is and assume they're located in the parent script's directory.

// fork-minimal.js - run with: node fork-minimal.js

const childProcess = require('child_process');

let scripts = ['some-script.js', 'some-other-script.js'];
scripts.forEach(script => childProcess.fork(script));

Verbose example

This would run the scripts with arguments and configured by the many available options.

// fork-verbose.js - run with: node fork-verbose.js

const childProcess = require('child_process');

let scripts = [
    {
        path: 'some-script.js',
        args: ['-some_arg', '/some_other_arg'],
        options: {cwd: './', env: {NODE_ENV: 'development'}}
    },    
    {
        path: 'some-other-script.js',
        args: ['-another_arg', '/yet_other_arg'],
        options: {cwd: '/some/where/else', env: {NODE_ENV: 'development'}}
    }
];

let runningScripts= [];

scripts.forEach(script => {
    let runningScript = childProcess.fork(script.path, script.args, script.options);

   // Optionally attach event listeners to the script
   runningScript.on('close', () => console.log('Time to die...'))

    runningScripts.push(runningScript); // Keep a reference to the script for later use
});

Communicating with forked scripts

Forking also has the added benefit that the parent script can receive events from the forked child processes as well as send back. A common example is for the parent script to kill its forked children.

 runningScripts.forEach(runningScript => runningScript.kill());

For more available events and methods see the ChildProcess documentation

In HTML5, can the <header> and <footer> tags appear outside of the <body> tag?

I agree with some of the others' answers. The <head> and <header> tags have two unique and very unrelated functions. The <header> tag, if I'm not mistaken, was introduced in HTML5 and was created for increased accessibility, namely for screen readers. It's generally used to indicate the heading of your document and, in order to work appropriately and effectively, should be placed inside the <body> tag. The <head> tag, since it's origin, is used for SEO in that it constructs all of the necessary meta data and such. A valid HTML structure for your page with both tags included would be like something like this:

<!DOCTYPE html/>
<html lang="es">
    <head>
        <!--crazy meta stuff here-->
    </head>
    <body>
        <header>
            <!--Optional nav tag-->
            <nav>
            </nav>
        </header>
        <!--Body content-->
    </body>
</html>

How to get all elements inside "div" that starts with a known text

var $list = $('#divname input[id^="q17_"]');   // get all input controls with id q17_

// once you have $list you can do whatever you want

var ControlCnt = $list.length;
// Now loop through list of controls
$list.each( function() {

    var id = $(this).prop("id");      // get id
    var cbx = '';
    if ($(this).is(':checkbox') || $(this).is(':radio')) {
        // Need to see if this control is checked
    }
    else { 
        // Nope, not a checked control - so do something else
    }

});

What is a good game engine that uses Lua?

Game engines that use Lua

Free unless noted

  • Agen (2D Lua; Windows)
  • Amulet (2D Lua; Window, Linux, Mac, HTML5, iOS)
  • Cafu 3D (3D C++/Lua)
  • Cocos2d-x (2D C++/Lua/JS; Windows, Linux, Mac, iOS, Android, BlackBerry)
  • Codea (2D&3D Lua; iOS (Editor is iOs app); $14.99 USD)
  • Cryengine by Crytek (3D C++/Lua; Windows, Mac)
  • Defold (2D Lua; Windows, Linux, Mac, iOS, Android, Web, Switch)
  • gengine (2D Lua; Windows, Linux, HTML5)
  • Irrlicht (3D C++/.NET/Lua; Windows, Linux, Mac)
  • Leadwerks (3D C++/C#/Delphi/BlitzMax/Lua; Windows; $199.95 USD)
  • LÖVE (2D Lua; Windows, Linux, Mac)
  • MOAI (2D C++/Lua; Windows, Linux, Mac, iOS, Android, Google Chrome (Native Client))
  • Solar2D (was Corona) (2D Lua; Windows, Mac, iOS, Android)
  • Spring RTS Engine (3D C++/Lua; Linux, Windows, Mac)
  • Wicked Engine (3D C++/Lua; Linux, Windows 10, Windows Phone, XBox One)

Bindings:

  • Raylib via raylib-lua-sol (2D&3D C++/Lua/Others; Windows, Linux, Mac, Android, Web, Other Ports)
  • SDL2 via luasdl2 (2D&3D C++/Lua/Others; Windows, Linux, Mac, Android, Console Ports)

Fantasy Consoles:

Editor and games run in an emulated computer system

  • PICO-8 (2D Lua; Windows, Linux, Mac, Raspberry Pi, Web Player $14.99 USD)
  • TIC-80 (2D Lua; Windows, Linux, Mac, Web)

Inactive/Discontinued:

  • Baja Engine (3D C++/Lua; Windows, Mac, No Release since Dec 2008)
  • Blitwizard (2D Lua; Windows, Linux, Mac, Development stopped in May 2014)
  • Drystal (2D Lua; Linux, HTML5)
  • EGSL (2D Pascal/Lua; Windows, Linux, Mac, Haiku)
  • Glint 3d Engine (3D Lua, Development stopped in Nov 2011)
  • Grail Adventure Game Engine (2D C++/Lua; Windows, Linux, Mac (SDL))
  • Juno (2D Lua; Windows, Linux, Mac, last commit on Friday the 13th, May 2016)
  • Lavgine (2.5D C++/Lua, Windows)
  • Luxinia (3D C/Lua; Windows, Development stopped in Dec 2018)
  • Polycode (2D&3D C++/Lua; Windows, Linux, Mac)

How does the ARM architecture differ from x86?

The ARM is like an Italian sports car:

  • Well balanced, well tuned, engine. Gives good acceleration, and top speed.
  • Excellent chases, brakes and suspension. Can stop quickly, can corner without slowing down.

The x86 is like an American muscle car:

  • Big engine, big fuel pump. Gives excellent top speed, and acceleration, but uses a lot of fuel.
  • Dreadful brakes, you need to put an appointment in your diary, if you want to slowdown.
  • Terrible steering, you have to slow down to corner.

In summary: the x86 is based on a design from 1974 and is good in a straight line (but uses a lot of fuel). The arm uses little fuel, does not slowdown for corners (branches).


Metaphor over, here are some real differences.

  • Arm has more registers.
  • Arm has few special purpose registers, x86 is all special purpose registers (so less moving stuff around).
  • Arm has few memory access commands, only load/store register.
  • Arm is internally Harvard architecture my design.
  • Arm is simple and fast.
  • Arm instructions are architecturally single cycle (except load/store multiple).
  • Arm instructions often do more than one thing (in a single cycle).
  • Where more that one Arm instruction is needed, such as the x86's looping store & auto-increment, the Arm still does it in less clock cycles.
  • Arm has more conditional instructions.
  • Arm's branch predictor is trivially simple (if unconditional or backwards then assume branch, else assume not-branch), and performs better that the very very very complex one in the x86 (there is not enough space here to explain it, not that I could).
  • Arm has a simple consistent instruction set (you could compile by hand, and learn the instruction set quickly).

Changing the current working directory in Java?

There is no reliable way to do this in pure Java. Setting the user.dir property via System.setProperty() or java -Duser.dir=... does seem to affect subsequent creations of Files, but not e.g. FileOutputStreams.

The File(String parent, String child) constructor can help if you build up your directory path separately from your file path, allowing easier swapping.

An alternative is to set up a script to run Java from a different directory, or use JNI native code as suggested below.

The relevant Sun bug was closed in 2008 as "will not fix".

Python NoneType object is not callable (beginner)

I faced the error "TypeError: 'NoneType' object is not callable " but for a different issue. With the above clues, i was able to debug and got it right! The issue that i faced was : I had the custome Library written and my file wasnt recognizing it although i had mentioned it

example: 
Library           ../../../libraries/customlibraries/ExtendedWaitKeywords.py
the keywords from my custom library were recognized and that error  was resolved only after specifying the complete path, as it was not getting the callable function.

How to add a button programmatically in VBA next to some sheet cell data?

I think this is enough to get you on a nice path:

Sub a()
  Dim btn As Button
  Application.ScreenUpdating = False
  ActiveSheet.Buttons.Delete
  Dim t As Range
  For i = 2 To 6 Step 2
    Set t = ActiveSheet.Range(Cells(i, 3), Cells(i, 3))
    Set btn = ActiveSheet.Buttons.Add(t.Left, t.Top, t.Width, t.Height)
    With btn
      .OnAction = "btnS"
      .Caption = "Btn " & i
      .Name = "Btn" & i
    End With
  Next i
  Application.ScreenUpdating = True
End Sub

Sub btnS()
 MsgBox Application.Caller
End Sub

It creates the buttons and binds them to butnS(). In the btnS() sub, you should show your dialog, etc.

Mathematica graphics

Create a txt file using batch file in a specific folder

You can also use

cd %localhost%

to set the directory to the folder the batch file was opened from. Your script would look like this:

@echo off
cd %localhost%
echo .> dblank.txt

Make sure you set the directory before you use the command to create the text file.

CSS: How to have position:absolute div inside a position:relative div not be cropped by an overflow:hidden on a container

If there is other content not being shown inside the outer-div (the green box), why not have that content wrapped inside another div, let's call it "content". Have overflow hidden on this new inner-div, but keep overflow visible on the green box.

The only catch is that you will then have to mess around to make sure that the content div doesn't interfere with the positioning of the red box, but it sounds like you should be able to fix that with little headache.

<div id="1" background: #efe; padding: 5px; width: 125px">
    <div id="content" style="overflow: hidden;">
    </div>
    <div id="2" style="position: relative; background: #fee; padding: 2px; width: 100px; height: 100px">
        <div id="3" style="position: absolute; top: 10px; background: #eef; padding: 2px; width: 75px; height: 150px"/>
    </div>
</div>

Bootstrap - Uncaught TypeError: Cannot read property 'fn' of undefined

Import jquery first before bootstrap:

<script src="js/jquery.min.js"></script>
<script src="js/bootstrap.js"></script>
<script src="js/bootstrap.bundle.js"></script>

How to read file with space separated values in pandas

If you can't get text parsing to work using the accepted answer (e.g if your text file contains non uniform rows) then it's worth trying with Python's csv library - here's an example using a user defined Dialect:

 import csv

 csv.register_dialect('skip_space', skipinitialspace=True)
 with open(my_file, 'r') as f:
      reader=csv.reader(f , delimiter=' ', dialect='skip_space')
      for item in reader:
          print(item)

Quotation marks inside a string

String name = "\"john\"";

You have to escape the second pair of quotation marks using the \ character in front. It might be worth looking at this link, which explains in some detail.

Other scenario where you set variable:

String name2 = "\""+name+"\"";

Sequence in console:

> String name = "\"john\"";
> name
""john""
> String name2 = "\""+name+"\"";
> name2
"""john"""

How to simulate target="_blank" in JavaScript

You can extract the href from the a tag:

window.open(document.getElementById('redirect').href);

A JOIN With Additional Conditions Using Query Builder or Eloquent

$results = DB::table('rooms')
                     ->distinct()
                     ->leftJoin('bookings', function($join)
                         {
                             $join->on('rooms.id', '=', 'bookings.room_type_id');
                             $join->on('arrival','>=',DB::raw("'2012-05-01'"));
                             $join->on('arrival','<=',DB::raw("'2012-05-10'"));
                             $join->on('departure','>=',DB::raw("'2012-05-01'"));
                             $join->on('departure','<=',DB::raw("'2012-05-10'"));
                         })
                     ->where('bookings.room_type_id', '=', NULL)
                     ->get();

Not quite sure if the between clause can be added to the join in laravel.

Notes:

  • DB::raw() instructs Laravel not to put back quotes.
  • By passing a closure to join methods you can add more join conditions to it, on() will add AND condition and orOn() will add OR condition.

How to type in textbox using Selenium WebDriver (Selenium 2) with Java?

This is simple if you only use Selenium WebDriver, and forget the usage of Selenium-RC. I'd go like this.

WebDriver driver = new FirefoxDriver();
WebElement email = driver.findElement(By.id("email"));
email.sendKeys("[email protected]");

The reason for NullPointerException however is that your variable driver has never been started, you start FirefoxDriver in a variable wb thas is never being used.

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

You can query the data dictionary/catalog views to find out when an object was created as well as the time of last DDL involving the object (example: alter table)

select * 
  from all_objects 
 where owner = '<name of schema owner>'
   and object_name = '<name of table>'

The column "CREATED" tells you when the object was created. The column "LAST_DDL_TIME" tells you when the last DDL was performed against the object.

As for when a particular row was inserted/updated, you can use audit columns like an "insert_timestamp" column or use a trigger and populate an audit table

Cannot set some HTTP headers when using System.Net.WebRequest

WebRequest being abstract (and since any inheriting class must override the Headers property).. which concrete WebRequest are you using ? In other words, how do you get that WebRequest object to beign with ?

ehr.. mnour answer made me realize that the error message you were getting is actually spot on: it's telling you that the header you are trying to add already exist and you should then modify its value using the appropriate property (the indexer, for instance), instead of trying to add it again. That's probably all you were looking for.

Other classes inheriting from WebRequest might have even better properties wrapping certain headers; See this post for instance.

Excel data validation with suggestions/autocomplete

If you don't want to go down the VBA path, there is this trick from a previous question.

Excel 2010: how to use autocomplete in validation list

It does add some annoying bulk to the top of your sheets, and potential maintenance (should you need more options, adding names of people from a staff list, new projects etc.) but works all the same.

How to insert logo with the title of a HTML page?

Yes you right and I just want to make it understandable for complete beginners.

  1. Create favicon.ico file you want to be shown next to your url in browsers tab. You can do that online. I used http://www.prodraw.net/favicon/generator.php it worked juts fine.
  2. Save generated ico file in your web site root directory /images (yourwebsite/images) under the name favicon.ico.
  3. Copy this tag <link rel="shortcut icon" href="images/favicon.ico" /> and past it without any changes in between <head> opening and </head> closing tag.
  4. Save changes in your html file and reload your browser.

Filter array to have unique values

Filtering an array to contain unique values can be achieved using the JavaScript Set and Array.from method, as shown below:

Array.from(new Set(arrayOfNonUniqueValues));

Set

The Set object lets you store unique values of any type, whether primitive values or object references.

Return value A new Set object.

Array.from()

The Array.from() method creates a new Array instance from an array-like or iterable object.

Return value A new Array instance.

Example Code:

_x000D_
_x000D_
const array = ["X_row7", "X_row4", "X_row6", "X_row10", "X_row8", "X_row9", "X_row11", "X_row7", "X_row4", "X_row6", "X_row10", "X_row8", "X_row9", "X_row11", "X_row7", "X_row4", "X_row6", "X_row10", "X_row8", "X_row9", "X_row11", "X_row7", "X_row4", "X_row6", "X_row10", "X_row8", "X_row9", "X_row11", "X_row7", "X_row4", "X_row6", "X_row10", "X_row8", "X_row9", "X_row11", "X_row7", "X_row4", "X_row6", "X_row10", "X_row8", "X_row9", "X_row11"]_x000D_
_x000D_
const uniqueArray = Array.from(new Set(array));_x000D_
_x000D_
console.log("uniqueArray: ", uniqueArray);
_x000D_
_x000D_
_x000D_

What is the difference between Linear search and Binary search?

A linear search starts at the beginning of a list of values, and checks 1 by 1 in order for the result you are looking for.

A binary search starts in the middle of a sorted array, and determines which side (if any) the value you are looking for is on. That "half" of the array is then searched again in the same fashion, dividing the results in half by two each time.

how to increase the limit for max.print in R

See ?options:

options(max.print=999999)

Parallel foreach with asynchronous lambda

My lightweight implementation of ParallelForEach async.

Features:

  1. Throttling (max degree of parallelism).
  2. Exception handling (aggregation exception will be thrown at completion).
  3. Memory efficient (no need to store the list of tasks).

public static class AsyncEx
{
    public static async Task ParallelForEachAsync<T>(this IEnumerable<T> source, Func<T, Task> asyncAction, int maxDegreeOfParallelism = 10)
    {
        var semaphoreSlim = new SemaphoreSlim(maxDegreeOfParallelism);
        var tcs = new TaskCompletionSource<object>();
        var exceptions = new ConcurrentBag<Exception>();
        bool addingCompleted = false;

        foreach (T item in source)
        {
            await semaphoreSlim.WaitAsync();
            asyncAction(item).ContinueWith(t =>
            {
                semaphoreSlim.Release();

                if (t.Exception != null)
                {
                    exceptions.Add(t.Exception);
                }

                if (Volatile.Read(ref addingCompleted) && semaphoreSlim.CurrentCount == maxDegreeOfParallelism)
                {
                    tcs.TrySetResult(null);
                }
            });
        }

        Volatile.Write(ref addingCompleted, true);
        await tcs.Task;
        if (exceptions.Count > 0)
        {
            throw new AggregateException(exceptions);
        }
    }
}

Usage example:

await Enumerable.Range(1, 10000).ParallelForEachAsync(async (i) =>
{
    var data = await GetData(i);
}, maxDegreeOfParallelism: 100);

How to make a dropdown readonly using jquery?

You could also disable it and at the moment that you make the submit call enable it. I think is the easiest way :)

How do you create a read-only user in PostgreSQL?

Do note that PostgreSQL 9.0 (today in beta testing) will have a simple way to do that:

test=> GRANT SELECT ON ALL TABLES IN SCHEMA public TO joeuser;

Installing J2EE into existing eclipse IDE

For Eclipse Mars the following worked

  1. In Eclipse select Help - Install New Software.
  2. Search for "EE". Got two hits and it what obvious which to use.
  3. Let IDE restart.

Ruby send JSON request

real life example, notify Airbrake API about new deployment via NetHttps

require 'uri'
require 'net/https'
require 'json'

class MakeHttpsRequest
  def call(url, hash_json)
    uri = URI.parse(url)
    req = Net::HTTP::Post.new(uri.to_s)
    req.body = hash_json.to_json
    req['Content-Type'] = 'application/json'
    # ... set more request headers 

    response = https(uri).request(req)

    response.body
  end

  private

  def https(uri)
    Net::HTTP.new(uri.host, uri.port).tap do |http|
      http.use_ssl = true
      http.verify_mode = OpenSSL::SSL::VERIFY_NONE
    end
  end
end

project_id = 'yyyyyy'
project_key = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
url = "https://airbrake.io/api/v4/projects/#{project_id}/deploys?key=#{project_key}"
body_hash = {
  "environment":"production",
  "username":"tomas",
  "repository":"https://github.com/equivalent/scrapbook2",
  "revision":"live-20160905_0001",
  "version":"v2.0"
}

puts MakeHttpsRequest.new.call(url, body_hash)

Notes:

in case you doing authentication via Authorisation header set header req['Authorization'] = "Token xxxxxxxxxxxx" or http://api.rubyonrails.org/classes/ActionController/HttpAuthentication/Token.html

Joining pairs of elements of a list

You can use slice notation with steps:

>>> x = "abcdefghijklm"
>>> x[0::2] #0. 2. 4...
'acegikm'
>>> x[1::2] #1. 3. 5 ..
'bdfhjl'
>>> [i+j for i,j in zip(x[::2], x[1::2])] # zip makes (0,1),(2,3) ...
['ab', 'cd', 'ef', 'gh', 'ij', 'kl']

Same logic applies for lists too. String lenght doesn't matter, because you're simply adding two strings together.

Rolling back bad changes with svn in Eclipse

In Eclipse using Subversive:

Right click your project > Team > Merge

In the merge window, select the revisions you want to revert as normally but also enable checkbox "Reversed merge".

Merge as normally.

Click a button programmatically

The best practice for this sort of situation is to create a method that hold all the logics, and call the method in both events, rather than calling an event from another event;

Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click

        LogicMethod()

End Sub

Protected Sub Button2_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click

        LogicMethod()

End Sub

Private Sub LogicMethod()

     // All your logic goes here

End Sub

In case you need the properties of the EventArgs (e), you can easily pass it through parameters in your method, that will avoid errors if ever the sender is of different types. But that won't be a problem in your case, as both senders are of type Button.

How to Completely Uninstall Xcode and Clear All Settings

This answer should be more of a comment against Dawn Song's comment earlier, but since I don't have enough reputation, I'm going to write it as an answer.

According to the forum page

https://forums.developer.apple.com/thread/11313

"In general, you should never just delete the CoreSimulator/Devices directory yourself. If you really absolutely must, you need to make sure that the service is not runnign while you do that. eg:"

# Quit Xcode.app, Simulator.app, etc
sudo killall -9 com.apple.CoreSimulator.CoreSimulatorService
rm -rf ~/Library/*/CoreSimulator

I definitely ran into this issue after deleting and reinstalling Xcode.

You might encounter a problem trying to connect the build to a simulator device. The thread also answers what to do in that case,

gem install snapshot
fastlane snapshot reset_simulators

How to deal with the URISyntaxException

Replace spaces in URL with + like If url contains dimension1=Incontinence Liners then replace it with dimension1=Incontinence+Liners.

Stop setInterval call in JavaScript

The clearInterval() method can be used to clear a timer set with the setInterval() method.

setInterval always returns a ID value. This value can be passed in clearInterval() to stop the timer. Here is an example of timer starting from 30 and stops when it becomes 0.

  let time = 30;
  const timeValue = setInterval((interval) => {
  time = this.time - 1;
  if (time <= 0) {
    clearInterval(timeValue);
  }
}, 1000);

How to write data to a text file without overwriting the current data

Here's a chunk of code that will write values to a log file. If the file doesn't exist, it creates it, otherwise it just appends to the existing file. You need to add "using System.IO;" at the top of your code, if it's not already there.

string strLogText = "Some details you want to log.";

// Create a writer and open the file:
StreamWriter log;

if (!File.Exists("logfile.txt"))
{
  log = new StreamWriter("logfile.txt");
}
else
{
  log = File.AppendText("logfile.txt");
}

// Write to the file:
log.WriteLine(DateTime.Now);
log.WriteLine(strLogText);
log.WriteLine();

// Close the stream:
log.Close();

How can I list ALL grants a user received?

If you want more than just direct table grants (e.g., grants via roles, system privileges such as select any table, etc.), here are some additional queries:

System privileges for a user:

SELECT PRIVILEGE
  FROM sys.dba_sys_privs
 WHERE grantee = <theUser>
UNION
SELECT PRIVILEGE 
  FROM dba_role_privs rp JOIN role_sys_privs rsp ON (rp.granted_role = rsp.role)
 WHERE rp.grantee = <theUser>
 ORDER BY 1;

Direct grants to tables/views:

SELECT owner, table_name, select_priv, insert_priv, delete_priv, update_priv, references_priv, alter_priv, index_priv 
  FROM table_privileges
 WHERE grantee = <theUser>
 ORDER BY owner, table_name;

Indirect grants to tables/views:

SELECT DISTINCT owner, table_name, PRIVILEGE 
  FROM dba_role_privs rp JOIN role_tab_privs rtp ON (rp.granted_role = rtp.role)
 WHERE rp.grantee = <theUser>
 ORDER BY owner, table_name;

How to update Git clone

git pull origin master

this will sync your master to the central repo and if new branches are pushed to the central repo it will also update your clone copy.

Writing an Excel file in EPPlus

It's best if you worked with DataSets and/or DataTables. Once you have that, ideally straight from your stored procedure with proper column names for headers, you can use the following method:

ws.Cells.LoadFromDataTable(<DATATABLE HERE>, true, OfficeOpenXml.Table.TableStyles.Light8);

.. which will produce a beautiful excelsheet with a nice table!

Now to serve your file, assuming you have an ExcelPackage object as in your code above called pck..

Response.Clear();

Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("Content-Disposition", "attachment;filename=" + sFilename);

Response.BinaryWrite(pck.GetAsByteArray());
Response.End();

How do I get git to default to ssh and not https for new repositories

The response provided by Trevor is correct.

But here is what you can directly add in your .gitconfig:

# Enforce SSH
[url "ssh://[email protected]/"]
  insteadOf = https://github.com/
[url "ssh://[email protected]/"]
  insteadOf = https://gitlab.com/
[url "ssh://[email protected]/"]
  insteadOf = https://bitbucket.org/

Javascript geocoding from address to latitude and longitude numbers not working

You're accessing the latitude and longitude incorrectly.

Try

<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">

var geocoder = new google.maps.Geocoder();
var address = "new york";

geocoder.geocode( { 'address': address}, function(results, status) {

  if (status == google.maps.GeocoderStatus.OK) {
    var latitude = results[0].geometry.location.lat();
    var longitude = results[0].geometry.location.lng();
    alert(latitude);
  } 
}); 
</script>

Should I use typescript? or I can just use ES6?

I've been using Typescript in my current angular project for about a year and a half and while there are a few issues with definitions every now and then the DefinitelyTyped project does an amazing job at keeping up with the latest versions of most popular libraries.

Having said that there is a definite learning curve when transitioning from vanilla JavaScript to TS and you should take into account the ability of you and your team to make that transition. Also if you are going to be using angular 1.x most of the examples you will find online will require you to translate them from JS to TS and overall there are not a lot of resources on using TS and angular 1.x together right now.

If you plan on using angular 2 there are a lot of examples using TS and I think the team will continue to provide most of the documentation in TS, but you certainly don't have to use TS to use angular 2.

ES6 does have some nice features and I personally plan on getting more familiar with it but I would not consider it a production-ready language at this point. Mainly due to a lack of support by current browsers. Of course, you can write your code in ES6 and use a transpiler to get it to ES5, which seems to be the popular thing to do right now.

Overall I think the answer would come down to what you and your team are comfortable learning. I personally think both TS and ES6 will have good support and long futures, I prefer TS though because you tend to get language features quicker and right now the tooling support (in my opinion) is a little better.

How to set 777 permission on a particular folder?

go to FileZilla and select which folder you will be give 777 permission, then right click set permission 777 and select check box, then ok.

How many socket connections possible?

On Linux you should be looking at using epoll for async I/O. It might also be worth fine-tuning socket-buffers to not waste too much kernel space per connection.

I would guess that you should be able to reach 100k connections on a reasonable machine.

Gradle does not find tools.jar

With Centos 7, I have found that only JDK has tools.jar, while JRE has not. I have installed the Java 8 JRE(yum install java-1.8.0-openjdk), but not the JDK(yum install java-1.8.0-openjdk-devel).

Installing the latter solves the problem. Also, remember to set JAVA_HOME.

How do I add 1 day to an NSDate?

In swift 4 or swift 5, you can use like bellow:

    let date = Date()
    let yesterday = Calendar.current.date(byAdding: .day, value: -1, to: date)
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd"
    let yesterday_date = dateFormatter.string(from: yesterday!)
    print("yesterday->",yesterday_date)

output:

Current date: 2020-03-02
yesterday date: 2020-03-01

javax.naming.NoInitialContextException - Java

If working on EJB client library:

You need to mention the argument for getting the initial context.

InitialContext ctx = new InitialContext();

If you do not, it will look in the project folder for properties file. Also you can include the properties credentials or values in your class file itself as follows:

Properties props = new Properties();
props.put(Context.INITIAL_CONTEXT_FACTORY, "org.jnp.interfaces.NamingContextFactory");
props.put(Context.URL_PKG_PREFIXES, "org.jboss.ejb.client.naming");
props.put(Context.PROVIDER_URL, "jnp://localhost:1099");

InitialContext ctx = new InitialContext(props);

URL_PKG_PREFIXES: Constant that holds the name of the environment property for specifying the list of package prefixes to use when loading in URL context factories.

The EJB client library is the primary library to invoke remote EJB components.
This library can be used through the InitialContext. To invoke EJB components the library creates an EJB client context via a URL context factory. The only necessary configuration is to parse the value org.jboss.ejb.client.naming for the java.naming.factory.url.pkgs property to instantiate an InitialContext.

Identify if a string is a number

If you want to know if a string is a number, you could always try parsing it:

var numberString = "123";
int number;

int.TryParse(numberString , out number);

Note that TryParse returns a bool, which you can use to check if your parsing succeeded.

How to let PHP to create subdomain automatically for each user?

You could [potentially] do a rewrite of the URL, but yes: you have to have control of your DNS settings so that when a user is added it gets its own subdomain.

How do I detect unsigned integer multiply overflow?

I see that a lot of people answered the question about overflow, but I wanted to address his original problem. He said the problem was to find ab=c such that all digits are used without repeating. Ok, that's not what he asked in this post, but I'm still think that it was necessary to study the upper bound of the problem and conclude that he would never need to calculate or detect an overflow (note: I'm not proficient in math so I did this step by step, but the end result was so simple that this might have a simple formula).

The main point is that the upper bound that the problem requires for either a, b or c is 98.765.432. Anyway, starting by splitting the problem in the trivial and non trivial parts:

  • x0 == 1 (all permutations of 9, 8, 7, 6, 5, 4, 3, 2 are solutions)
  • x1 == x (no solution possible)
  • 0b == 0 (no solution possible)
  • 1b == 1 (no solution possible)
  • ab, a > 1, b > 1 (non trivial)

Now we just need to show that no other solution is possible and only the permutations are valid (and then the code to print them is trivial). We go back to the upper bound. Actually the upper bound is c = 98.765.432. It's the upper bound because it's the largest number with 8 digits (10 digits total minus 1 for each a and b). This upper bound is only for c because the bounds for a and b must be much lower because of the exponential growth, as we can calculate, varying b from 2 to the upper bound:

    9938.08^2 == 98765432
    462.241^3 == 98765432
    99.6899^4 == 98765432
    39.7119^5 == 98765432
    21.4998^6 == 98765432
    13.8703^7 == 98765432
    9.98448^8 == 98765432
    7.73196^9 == 98765432
    6.30174^10 == 98765432
    5.33068^11 == 98765432
    4.63679^12 == 98765432
    4.12069^13 == 98765432
    3.72429^14 == 98765432
    3.41172^15 == 98765432
    3.15982^16 == 98765432
    2.95305^17 == 98765432
    2.78064^18 == 98765432
    2.63493^19 == 98765432
    2.51033^20 == 98765432
    2.40268^21 == 98765432
    2.30883^22 == 98765432
    2.22634^23 == 98765432
    2.15332^24 == 98765432
    2.08826^25 == 98765432
    2.02995^26 == 98765432
    1.97741^27 == 98765432

Notice, for example the last line: it says that 1.97^27 ~98M. So, for example, 1^27 == 1 and 2^27 == 134.217.728 and that's not a solution because it has 9 digits (2 > 1.97 so it's actually bigger than what should be tested). As it can be seen, the combinations available for testing a and b are really small. For b == 14, we need to try 2 and 3. For b == 3, we start at 2 and stop at 462. All the results are granted to be less than ~98M.

Now just test all the combinations above and look for the ones that do not repeat any digits:

    ['0', '2', '4', '5', '6', '7', '8'] 84^2 = 7056
    ['1', '2', '3', '4', '5', '8', '9'] 59^2 = 3481
    ['0', '1', '2', '3', '4', '5', '8', '9'] 59^2 = 3481 (+leading zero)
    ['1', '2', '3', '5', '8'] 8^3 = 512
    ['0', '1', '2', '3', '5', '8'] 8^3 = 512 (+leading zero)
    ['1', '2', '4', '6'] 4^2 = 16
    ['0', '1', '2', '4', '6'] 4^2 = 16 (+leading zero)
    ['1', '2', '4', '6'] 2^4 = 16
    ['0', '1', '2', '4', '6'] 2^4 = 16 (+leading zero)
    ['1', '2', '8', '9'] 9^2 = 81
    ['0', '1', '2', '8', '9'] 9^2 = 81 (+leading zero)
    ['1', '3', '4', '8'] 3^4 = 81
    ['0', '1', '3', '4', '8'] 3^4 = 81 (+leading zero)
    ['2', '3', '6', '7', '9'] 3^6 = 729
    ['0', '2', '3', '6', '7', '9'] 3^6 = 729 (+leading zero)
    ['2', '3', '8'] 2^3 = 8
    ['0', '2', '3', '8'] 2^3 = 8 (+leading zero)
    ['2', '3', '9'] 3^2 = 9
    ['0', '2', '3', '9'] 3^2 = 9 (+leading zero)
    ['2', '4', '6', '8'] 8^2 = 64
    ['0', '2', '4', '6', '8'] 8^2 = 64 (+leading zero)
    ['2', '4', '7', '9'] 7^2 = 49
    ['0', '2', '4', '7', '9'] 7^2 = 49 (+leading zero)

None of them matches the problem (which can also be seen by the absence of '0', '1', ..., '9').

The example code that solves it follows. Also note that's written in Python, not because it needs arbitrary precision integers (the code doesn't calculate anything bigger than 98 million), but because we found out that the amount of tests is so small that we should use a high level language to make use of its built-in containers and libraries (also note: the code has 28 lines).

    import math

    m = 98765432
    l = []
    for i in xrange(2, 98765432):
        inv = 1.0/i
        r = m**inv
        if (r < 2.0): break
        top = int(math.floor(r))
        assert(top <= m)

        for j in xrange(2, top+1):
            s = str(i) + str(j) + str(j**i)
            l.append((sorted(s), i, j, j**i))
            assert(j**i <= m)

    l.sort()
    for s, i, j, ji in l:
        assert(ji <= m)
        ss = sorted(set(s))
        if s == ss:
            print '%s %d^%d = %d' % (s, i, j, ji)

        # Try with non significant zero somewhere
        s = ['0'] + s
        ss = sorted(set(s))
        if s == ss:
            print '%s %d^%d = %d (+leading zero)' % (s, i, j, ji)

I get "Http failure response for (unknown url): 0 Unknown Error" instead of actual error message in Angular

If you are using Laravel as your Backend, then edit your .htaccess file by just pasting this code, to solve problem CROS in your Angular or IONIC project

Header add Access-Control-Allow-Origin "*"
Header add Access-Control-Allow-Methods: "GET,POST,OPTIONS,DELETE,PUT"

Include PHP inside JavaScript (.js) files

This is somewhat tricky since PHP gets evaluated server-side and javascript gets evaluated client side.

I would call your PHP file using an AJAX call from inside javascript and then use JS to insert the returned HTML somewhere on your page.

How do I make a matrix from a list of vectors in R?

simplify2array is a base function that is fairly intuitive. However, since R's default is to fill in data by columns first, you will need to transpose the output. (sapply uses simplify2array, as documented in help(sapply).)

> t(simplify2array(a))
      [,1] [,2] [,3] [,4] [,5] [,6]
 [1,]    1    1    2    3    4    5
 [2,]    2    1    2    3    4    5
 [3,]    3    1    2    3    4    5
 [4,]    4    1    2    3    4    5
 [5,]    5    1    2    3    4    5
 [6,]    6    1    2    3    4    5
 [7,]    7    1    2    3    4    5
 [8,]    8    1    2    3    4    5
 [9,]    9    1    2    3    4    5
[10,]   10    1    2    3    4    5

jQuery Array of all selected checkboxes (by class)

You can also add underscore.js to your project and will be able to do it in one line:

_.map($("input[name='category_ids[]']:checked"), function(el){return $(el).val()})

Checking whether a String contains a number value in Java

Shef's answer doesn't compile for me. It looks like he's using RegEx in String.contains(). If you want to use RegEx use this:

String strWithNumber = "This string has a 1 number";
String strWithoutNumber = "This string has a number";

System.out.println(strWithNumber.matches(".*\\d.*"));
System.out.println(strWithoutNumber.matches(".*\\d.*"));

Sort tuples based on second parameter

And if you are using python 3.X, you may apply the sorted function on the mylist. This is just an addition to the answer that @Sven Marnach has given above.

# using *sort method*
mylist.sort(lambda x: x[1]) 

# using *sorted function*
sorted(mylist, key = lambda x: x[1]) 

SQL Server: Invalid Column Name

I had a similar problem.

Issue was there was a trigger on the table that would write changes to an audit log table. Columns were missing in audit log table.

Reload activity in Android

Android includes a process management system which handles the creation and destruction of activities which largely negates any benefit you'd see from manually restarting an activity. You can see more information about it at Application Fundamentals

What is good practice though is to ensure that your onPause and onStop methods release any resources which you don't need to hold on to and use onLowMemory to reduce your activities needs to the absolute minimum.

python: how to check if a line is an empty line

If you want to ignore lines with only whitespace:

if not line.strip():
    ... do something

The empty string is a False value.

Or if you really want only empty lines:

if line in ['\n', '\r\n']:
    ... do  something

Simulate delayed and dropped packets on Linux

You can try http://snad.ncsl.nist.gov/nistnet/ https://www-x.antd.nist.gov/nistnet/ It's quite old NIST project (last release 2005), but it works for me.

Is there a short cut for going back to the beginning of a file by vi editor?

using :<line number> you can navigate to any line, thus :1 takes you to the first line.

Unix command to find lines common in two files

On limited version of Linux (like a QNAP (nas) I was working on):

  • comm did not exist
  • grep -f file1 file2 can cause some problems as said by @ChristopherSchultz and using grep -F -f file1 file2 was really slow (more than 5 minutes - not finished it - over 2-3 seconds with the method below on files over 20MB)

So here is what I did :

sort file1 > file1.sorted
sort file2 > file2.sorted

diff file1.sorted file2.sorted | grep "<" | sed 's/^< *//' > files.diff
diff file1.sorted files.diff | grep "<" | sed 's/^< *//' > files.same.sorted

If files.same.sorted shall have been in same order than the original ones, than add this line for same order than file1 :

awk 'FNR==NR {a[$0]=$0; next}; $0 in a {print a[$0]}' files.same.sorted file1 > files.same

or, for same order than file2 :

awk 'FNR==NR {a[$0]=$0; next}; $0 in a {print a[$0]}' files.same.sorted file2 > files.same

What is an IIS application pool?

I second the top voted answer, but feel like adding little more details here if anyone finds it useful.

short version:

IIS runs any website you configure in a process named w3wp.exe. IIS Application pool is feature in IIS which allows each website or a part of it to run under a corresponding w3wp.exe process. So you can run 100 websites all in a single w3wp.exe or 100 different w3wp.exe. E.g. run 3 websites in same application pool(same w3wp.exe) to save memory usage. ,run 2 different websites in two different application pools so that each can run under separate user account(called application pool identity). run a website in one application pool and a subsite 'website/app' under a different application pool.

Longer version:

Every website or a part of the website,you can run under an application pool.You can control some basic settings of the website using an application pool.

  1. You would like the website to run under a different w3wp.exe process.Then create a new application pool and assign that to the website.
  2. You would like to run the website and all it's code under a different user account(e.g under Admin privileges),you can run do that by changing Application Pool Identity.
  3. You would like to run a particular application under .net framework 4.0 or 2.0.
  4. You would like to make sure the website in 32 bit mode or have a scheduled recycle of the w3wp.exe process etc.All such things are controlled from iis application pool.

How to search JSON tree with jQuery

var json = {
    "people": {
        "person": [{
            "name": "Peter",
            "age": 43,
            "sex": "male"},
        {
            "name": "Zara",
            "age": 65,
            "sex": "female"}]
    }
};
$.each(json.people.person, function(i, v) {
    if (v.name == "Peter") {
        alert(v.age);
        return;
    }
});

Example.

Based on this answer, you could use something like:

$(function() {
    var json = {
        "people": {
            "person": [{
                "name": "Peter",
                "age": 43,
                "sex": "male"},
            {
                "name": "Zara",
                "age": 65,
                "sex": "female"}]
        }
    };
    $.each(json.people.person, function(i, v) {
        if (v.name.search(new RegExp(/peter/i)) != -1) {
            alert(v.age);
            return;
        }
    });
});

Example 2

How to loop in excel without VBA or macros?

Add more columns when you have variable loops that repeat at different rates. I'm not sure explicitly what you're trying to do, but I think I've done something that could apply.

Creating a single loop in Excel is prettty simple. It actually does the work for you. Try this on a new workbook

  1. Enter "1" in A1
  2. Enter "=A1+1" in A2

A3 will automatically be "=A2+1" as you drag down. The first steps don't have to be that explicit. Excel will automatically recognize the pattern and count if you just put "2" in A2, but if we want B1-B5 to be "100" and B5-B10 to be "200" (counting up the same way) you can see why knowing how to do it explicitly matters. In this scenario, You just enter:

  1. "100" in B1, drag through to B5 and
  2. "=B1+100" in B6

B7 will automatically be "=B2+100" etc. as you drag down, so basically it increases every 5 rows infinitely. To make a loop of numbers 1-5 in column A:

  1. Enter "=A1" in cell A6. As you drag down, it will automatically be "=A2" in cell A7, etc. because of the way that Excel does things.

So, now we have column A repeating numbers 1-5 while column B is increasing by 100 every 5 cells.You could make column B repeat, for instance, the numbers 100-900 in using the same method as you did with column A as a way to produce, for instance, each possible combination with multiple variables. Drag down the columns and they'll do it infinitely. I'm not explicitly addressing the scenario given, but if you follow the steps and understand them, the concept should give you an answer to the problem that involves adding more columns and concactinating or using them as your variables.

How do I create a table based on another table

There is no such syntax in SQL Server, though CREATE TABLE AS ... SELECT does exist in PDW. In SQL Server you can use this query to create an empty table:

SELECT * INTO schema.newtable FROM schema.oldtable WHERE 1 = 0;

(If you want to make a copy of the table including all of the data, then leave out the WHERE clause.)

Note that this creates the same column structure (including an IDENTITY column if one exists) but it does not copy any indexes, constraints, triggers, etc.

Mongoose (mongodb) batch insert?

It seems that using mongoose there is a limit of more than 1000 documents, when using

Potato.collection.insert(potatoBag, onInsert);

You can use:

var bulk = Model.collection.initializeOrderedBulkOp();

async.each(users, function (user, callback) {
    bulk.insert(hash);
}, function (err) {
    var bulkStart = Date.now();
    bulk.execute(function(err, res){
        if (err) console.log (" gameResult.js > err " , err);
        console.log (" gameResult.js > BULK TIME  " , Date.now() - bulkStart );
        console.log (" gameResult.js > BULK INSERT " , res.nInserted)
      });
});

But this is almost twice as fast when testing with 10000 documents:

function fastInsert(arrOfResults) {
var startTime = Date.now();
    var count = 0;
    var c = Math.round( arrOfResults.length / 990);

    var fakeArr = [];
    fakeArr.length = c;
    var docsSaved = 0

    async.each(fakeArr, function (item, callback) {

            var sliced = arrOfResults.slice(count, count+999);
            sliced.length)
            count = count +999;
            if(sliced.length != 0 ){
                    GameResultModel.collection.insert(sliced, function (err, docs) {
                            docsSaved += docs.ops.length
                            callback();
                    });
            }else {
                    callback()
            }
    }, function (err) {
            console.log (" gameResult.js > BULK INSERT AMOUNT: ", arrOfResults.length, "docsSaved  " , docsSaved, " DIFF TIME:",Date.now() - startTime);
    });
}

Warning: #1265 Data truncated for column 'pdd' at row 1

As the message error says, you need to Increase the length of your column to fit the length of the data you are trying to insert (0000-00-00)

EDIT 1:

Following your comment, I run a test table:

mysql> create table testDate(id int(2) not null auto_increment, pdd date default null, primary key(id));
Query OK, 0 rows affected (0.20 sec)

Insertion:

mysql> insert into testDate values(1,'0000-00-00');
Query OK, 1 row affected (0.06 sec)

EDIT 2:

So, aparently you want to insert a NULL value to pdd field as your comment states ? You can do that in 2 ways like this:

Method 1:

mysql> insert into testDate values(2,'');
Query OK, 1 row affected, 1 warning (0.06 sec)

Method 2:

mysql> insert into testDate values(3,NULL);
Query OK, 1 row affected (0.07 sec)

EDIT 3:

You failed to change the default value of pdd field. Here is the syntax how to do it (in my case, I set it to NULL in the start, now I will change it to NOT NULL)

mysql> alter table testDate modify pdd date not null;
Query OK, 3 rows affected, 1 warning (0.60 sec)
Records: 3  Duplicates: 0  Warnings: 1

HTML5 event handling(onfocus and onfocusout) using angular 2

If you want to catch the focus event dynamiclly on every input on your component :

import { AfterViewInit, Component, ElementRef } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent implements AfterViewInit {

  constructor(private el: ElementRef) {
  }

  ngAfterViewInit() {
       // document.getElementsByTagName('input') : to gell all Docuement imputs
       const inputList = [].slice.call((<HTMLElement>this.el.nativeElement).getElementsByTagName('input'));
        inputList.forEach((input: HTMLElement) => {
            input.addEventListener('focus', () => {
                input.setAttribute('placeholder', 'focused');
            });
            input.addEventListener('blur', () => {
                input.removeAttribute('placeholder');
            });
        });
    }
}

Checkout the full code here : https://stackblitz.com/edit/angular-93jdir

Fixing a systemd service 203/EXEC failure (no such file or directory)

I ran across a Main process exited, code=exited, status=203/EXEC today as well and my bug was that I forgot to add the executable bit to the file.

Login failed for user 'NT AUTHORITY\NETWORK SERVICE'

The error message you are receiving is telling you that the application failed to connect to the sqlexpress db, and not sql server. I will just change the name of the db in sql server and then update the connectionstring accordingly and try it again.

Your error message states the following:

Cannot open database "Phaeton.mdf" requested by the login. The login failed.

It looks to me you are still trying to connect to the file based database, the name "Phaeton.mdf" does not match with your new sql database name "Phaeton".

Hope this helps.

How do I check whether a checkbox is checked in jQuery?

I need to check the checked property of a checkbox and perform an action based on the checked property using jQuery.

E.X -

1) Run On load to get checkbox value if the age checkbox is checked, then I need to show a text box to enter age, else hide the text box.

2) if the age checkbox is checked, then I need to show a text box to enter age, else hide the text box using click event of checkbox.

so code not returns false by default:

Try the following:

<html>
        <head>
            <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
        </head>
        <body>
            <h1>Jquery Demo</h1>
            <input type="checkbox" name="isAge" checked id="isAge"> isAge <br/>
            <div id="Age" style="display:none">
              <label>Enter your age</label>
              <input type="number" name="age">
            </div>
            <script type="text/javascript">
            if(document.getElementById('isAge').checked) {
                $('#Age').show();
            } else {
                $('#Age').hide();
            }   
            $('#isAge').click(function() {
                if(document.getElementById('isAge').checked) {
                    $('#Age').show();
                } else {
                    $('#Age').hide();
                }
            }); 
            </script>
        </body>
    </html>

Here is a modified version : https://jsfiddle.net/sedhal/0hygLtrz/7/

Use Invoke-WebRequest with a username and password for basic authentication on the GitHub API

I am assuming Basic authentication here.

$cred = Get-Credential
Invoke-WebRequest -Uri 'https://whatever' -Credential $cred

You can get your credential through other means (Import-Clixml, etc.), but it does have to be a [PSCredential] object.

Edit based on comments:

GitHub is breaking RFC as they explain in the link you provided:

The API supports Basic Authentication as defined in RFC2617 with a few slight differences. The main difference is that the RFC requires unauthenticated requests to be answered with 401 Unauthorized responses. In many places, this would disclose the existence of user data. Instead, the GitHub API responds with 404 Not Found. This may cause problems for HTTP libraries that assume a 401 Unauthorized response. The solution is to manually craft the Authorization header.

Powershell's Invoke-WebRequest does to my knowledge wait for a 401 response before sending the credentials, and since GitHub never provides one, your credentials will never be sent.

Manually build the headers

Instead you'll have to create the basic auth headers yourself.

Basic authentication takes a string that consists of the username and password separated by a colon user:pass and then sends the Base64 encoded result of that.

Code like this should work:

$user = 'user'
$pass = 'pass'

$pair = "$($user):$($pass)"

$encodedCreds = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes($pair))

$basicAuthValue = "Basic $encodedCreds"

$Headers = @{
    Authorization = $basicAuthValue
}

Invoke-WebRequest -Uri 'https://whatever' -Headers $Headers

You could combine some of the string concatenation but I wanted to break it out to make it clearer.

Average of multiple columns

You could simply do:

Select Req_ID, (avg(R1)+avg(R2)+avg(R3)+avg(R4)+avg(R5))/5 as Average
from Request
Group by Req_ID

Right?

I'm assuming that you may have multiple rows with the same Req_ID and in these cases you want to calculate the average across all columns and rows for those rows with the same Req_ID

Opening A Specific File With A Batch File?

you are in a situation where you cannot set a certain program as the default program to use when opening a certain type of file, I've found using a .bat file handy. In my case, Textpad runs on my machine via Microsoft Application Virtualization ("AppV"). The path to Textpad is in an "AppV directory" so to speak. My Textpad AppV shortcut has this as a target...

%ALLUSERSPROFILE%\Microsoft\AppV\Client\Integration\
 12345ABC-A1BC-1A23-1A23-1234567E1234\Root\TextPad.exe

To associate the textpad.exe with 'txt' files via a 'bat' file:

1) In Explorer, create a new ('txt') file and save as opentextpad.bat in an "appropriate" location

2) In the opentextpad.bat file, type this line:

textpad.exe %1  

3) Save and Close

4) In explorer, perform windows file association by right-clicking on a 'txt' file (e.g. 'dummy.txt') and choose 'Open with > Choose default program...' from the menu. In the 'Open with' window, click 'Browse...', then navigate to and select your textpad.bat file. Click 'Open'. You'll return to the 'Open with' window. Make sure to check the 'Always use the selected program to open this type of file' checkbox. Click 'OK' and the window will close.

When you open a 'txt' file now, it will open the file with 'textpad.exe'.

Hope this is useful.

Font awesome is not showing icon

my issue was the one having most of the votes

*{
font-family: xxxxx
}

changing it to this solved the problem

body{
font-family: xxxx
}

How to change value for innodb_buffer_pool_size in MySQL on Mac OS?

In the earlier versions of MySQL ( < 5.7.5 ) the only way to set

'innodb_buffer_pool_size'

variable was by writing it to my.cnf (for linux) and my.ini (for windows) under [mysqld] section :

[mysqld]

innodb_buffer_pool_size = 2147483648

You need to restart your mysql server to have it's effect in action.

UPDATE :

As of MySQL 5.7.5, the innodb_buffer_pool_size configuration option can be set dynamically using a SET statement, allowing you to resize the buffer pool without restarting the server. For example:

mysql> SET GLOBAL innodb_buffer_pool_size=402653184;

Reference : https://dev.mysql.com/doc/refman/5.7/en/innodb-buffer-pool-resize.html

Extract every nth element of a vector

Another trick for getting sequential pieces (beyond the seq solution already mentioned) is to use a short logical vector and use vector recycling:

foo[ c( rep(FALSE, 5), TRUE ) ]

Change CSS properties on click

In your code you aren't using jquery, so, if you want to use it, yo need something like...

$('#foo').css({'background-color' : 'red', 'color' : 'white', 'font-size' : '44px'});

http://api.jquery.com/css/

Other way, if you are not using jquery, you need to do ...

document.getElementById('foo').style = 'background-color: red; color: white; font-size: 44px';

How to stop flask application without using ctrl-c

Google Cloud VM instance + Flask App

I hosted my Flask Application on Google Cloud Platform Virtual Machine. I started the app using python main.py But the problem was ctrl+c did not work to stop the server.

This command $ sudo netstat -tulnp | grep :5000 terminates the server.

My Flask app runs on port 5000 by default.

Note: My VM instance is running on Linux 9.

It works for this. Haven't tested for other platforms. Feel free to update or comment if it works for other versions too.

SQL Server 2012 can't start because of a login failure

While ("run as SYSTEM") works, people should be advised this means going from a minimum-permissions type account to an account which has all permissions in the world. Which is very much not a recommended setup best practices or security-wise.

If you know what you are doing and know your SQL Server will always be run in an isolated environment (i.e. not on hotel or airport wifi) it's probably fine, but this creates a very real attack vector which can completely compromise a machine if on open internets.

This seems to be an error on Microsoft's part and people should be aware of the implications of the workaround posted.

How do you set a JavaScript onclick event to a class with css

You could do it with jQuery.

$('.myClass').click(function() {
  alert('hohoho');
});

Round number to nearest integer

You can also use numpy assuming if you are using python3.x here is an example

import numpy as np
x = 2.3
print(np.rint(x))
>>> 2.0