Programs & Examples On #H.264

H.264/MPEG-4 Part 10 or AVC (Advanced Video Coding) is a standard for video compression

How to concatenate two MP4 files using FFmpeg?

Here's a fast (takes less than 1 minute) and lossless way to do this without needing intermediate files:

ls Movie_Part_1.mp4 Movie_Part_2.mp4 | \
perl -ne 'print "file $_"' | \
ffmpeg -f concat -i - -c copy Movie_Joined.mp4

The "ls" contains the files to join The "perl" creates the concatenation file on-the-fly into a pipe The "-i -" part tells ffmpeg to read from the pipe

(note - my files had no spaces or weird stuff in them - you'll need appropriate shell-escaping if you want to do this idea with "hard" files).

What is the difference between H.264 video and MPEG-4 video?

They are names for the same standard from two different industries with different naming methods, the guys who make & sell movies and the guys who transfer the movies over the internet. Since 2003: "MPEG 4 Part 10" = "H.264" = "AVC". Before that the relationship was a little looser in that they are not equal but an "MPEG 4 Part 2" decoder can render a stream that's "H.263". The Next standard is "MPEG H Part 2" = "H.265" = "HEVC"

H.264 file size for 1 hr of HD video

For a good quality x264 encoding of 1060i, done by a computer, not a mobile device, not in real time, you could use a bitrate at about 5 MBps. That means 2250 MB/hour of encoded material. Recommend you deinterlace the footage and compress as progressive.

ffmpeg usage to encode a video to H264 codec format

I believe that by now the above answers are outdated (or at least unclear) so here's my little go at it. I tried compiling ffmpeg with the option --enable-encoders=libx264 and it will give no error but it won't enable anything (I can't seem to find where I found that suggestion).

Anyways step-by-step, first you must compile libx264 yourself because repository version is outdated:

  wget ftp://ftp.videolan.org/pub/x264/snapshots/last_x264.tar.bz2
  tar --bzip2 -xvf last_x264.tar.bz2
  cd x264-snapshot-XXXXXXXX-XXXX/
  ./configure
  make
  sudo make install

And then get and compile ffmpeg with libx264 enabled. I'm using the latest release which is "Happiness":

wget http://ffmpeg.org/releases/ffmpeg-0.11.2.tar.bz2
tar --bzip2 -xvf ffmpeg-0.11.2.tar.bz2
cd ffmpeg-0.11.2/
./configure --enable-libx264 --enable-gpl
make
sudo install

Now finally you have the libx264 codec to encode, to check it you may run

ffmpeg -codecs | grep h264

and you'll see the options you have were the first D means decoding and the first E means encoding

CSS3 Continuous Rotate Animation (Just like a loading sundial)

Your code seems correct. I would presume it is something to do with the fact you are using a .png and the way the browser redraws the object upon rotation is inefficient, causing the hang (what browser are you testing under?)

If possible replace the .png with something native.

see; http://kilianvalkhof.com/2010/css-xhtml/css3-loading-spinners-without-images/

Chrome gives me no pauses using this method.

How to run test cases in a specified file?

There are two ways. The easy one is to use the -run flag and provide a pattern matching names of the tests you want to run.

Example:

$ go test -run NameOfTest

See the docs for more info.

The other way is to name the specific file, containing the tests you want to run:

$ go test foo_test.go

But there's a catch. This works well if:

  • foo.go is in package foo.
  • foo_test.go is in package foo_test and imports 'foo'.

If foo_test.go and foo.go are the same package (a common case) then you must name all other files required to build foo_test. In this example it would be:

$ go test foo_test.go foo.go

I'd recommend to use the -run pattern. Or, where/when possible, always run all package tests.

Android Min SDK Version vs. Target SDK Version

android:minSdkVersion

An integer designating the minimum API Level required for the application to run. The Android system will prevent the user from installing the application if the system's API Level is lower than the value specified in this attribute. You should always declare this attribute.

android:targetSdkVersion

An integer designating the API Level that the application is targetting.

With this attribute set, the application says that it is able to run on older versions (down to minSdkVersion), but was explicitly tested to work with the version specified here. Specifying this target version allows the platform to disable compatibility settings that are not required for the target version (which may otherwise be turned on in order to maintain forward-compatibility) or enable newer features that are not available to older applications. This does not mean that you can program different features for different versions of the platform—it simply informs the platform that you have tested against the target version and the platform should not perform any extra work to maintain forward-compatibility with the target version.

For more information refer this URL:

http://developer.android.com/guide/topics/manifest/uses-sdk-element.html

Python: 'ModuleNotFoundError' when trying to import module from imported package

For me when I created a file and saved it as python file, I was getting this error during importing. I had to create a filename with the type ".py" , like filename.py and then save it as a python file. post trying to import the file worked for me.

Why did a network-related or instance-specific error occur while establishing a connection to SQL Server?

I had the same problem with SQL Server 2008 R2 and when I checked "SQL Server Configuration Manager" My SQL Server instance had Stopped. Right Clicking and Starting the Instance solved the issue.

Having issues with a MySQL Join that needs to meet multiple conditions

SELECT 
    u . *
FROM
    room u
        JOIN
    facilities_r fu ON fu.id_uc = u.id_uc
        AND (fu.id_fu = '4' OR fu.id_fu = '3')
WHERE
    1 and vizibility = '1'
GROUP BY id_uc
ORDER BY u_premium desc , id_uc desc

You must use OR here, not AND.

Since id_fu cannot be equal to 4 and 3, both at once.

How to restart a node.js server

At first open terminal/command line then go to your project directory, now install nodemon by using command npm install nodemon --save-dev this command will make sure it saved as developer dependency. If you are working with expressjs then in your package file it will look like

{
  "name": "expressjs-app",
  "version": "0.0.0",
  "private": true,
  "scripts": {
    "start": "node ./bin/www"
  },
  "dependencies": {
    "cookie-parser": "~1.4.4",
    "debug": "~2.6.9",
    "express": "~4.16.1",
    "http-errors": "~1.6.3",
    "morgan": "~1.9.1",
    "pug": "^2.0.4"
  },
  "devDependencies": {
    "nodemon": "^2.0.3"
  }
}

now modify the "start" value in your package.json file, for production we will use the exsiting value but for development will use nodemon to track the changes in source file without restarting server. There for new value for start is "start": "if [[$NODE_ENV=='production']]; then node ./bin/www; else nodemon ./bin/www; fi"

final package.json file will look like

{
  "name": "expressjs-app",
  "version": "0.0.0",
  "private": true,
  "scripts": {
    "start": "if [[$NODE_ENV=='production']]; then node ./bin/www; else nodemon ./bin/www; fi"
  },
  "dependencies": {
    "cookie-parser": "~1.4.4",
    "debug": "~2.6.9",
    "express": "~4.16.1",
    "http-errors": "~1.6.3",
    "morgan": "~1.9.1",
    "pug": "^2.0.4"
  },
  "devDependencies": {
    "nodemon": "^2.0.3"
  }
}

to uninstall nodemon jusy simply run the command npm uninstall nodemon

Postgres password authentication fails

As shown in the latest edit, the password is valid until 1970, which means it's currently invalid. This explains the error message which is the same as if the password was incorrect.

Reset the validity with:

ALTER USER postgres VALID UNTIL 'infinity';

In a recent question, another user had the same problem with user accounts and PG-9.2:

PostgreSQL - Password authentication fail after adding group roles

So apparently there is a way to unintentionally set a bogus password validity to the Unix epoch (1st Jan, 1970, the minimum possible value for the abstime type). Possibly, there's a bug in PG itself or in some client tool that would create this situation.

EDIT: it turns out to be a pgadmin bug. See https://dba.stackexchange.com/questions/36137/

Easy way to get a test file into JUnit

I know you said you didn't want to read the file in by hand, but this is pretty easy

public class FooTest
{
    private BufferedReader in = null;

    @Before
    public void setup()
        throws IOException
    {
        in = new BufferedReader(
            new InputStreamReader(getClass().getResourceAsStream("/data.txt")));
    }

    @After
    public void teardown()
        throws IOException
    {
        if (in != null)
        {
            in.close();
        }

        in = null;
    }

    @Test
    public void testFoo()
        throws IOException
    {
        String line = in.readLine();

        assertThat(line, notNullValue());
    }
}

All you have to do is ensure the file in question is in the classpath. If you're using Maven, just put the file in src/test/resources and Maven will include it in the classpath when running your tests. If you need to do this sort of thing a lot, you could put the code that opens the file in a superclass and have your tests inherit from that.

NavigationBar bar, tint, and title text color in iOS 8

Setting text color of navigation bar title to white in Swift version 4.2:

navigationController?.navigationBar.titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.white]

Convert Numeric value to Varchar

i think it should be

select convert(varchar(10),StandardCost) +'S' from DimProduct where ProductKey = 212

or

select cast(StandardCost as varchar(10)) + 'S' from DimProduct where ProductKey = 212

How to write UPDATE SQL with Table alias in SQL Server 2008?

You can always take the CTE, (Common Tabular Expression), approach.

;WITH updateCTE AS
(
    SELECT ID, TITLE 
    FROM HOLD_TABLE
    WHERE ID = 101
)

UPDATE updateCTE
SET TITLE = 'TEST';

Creating a new DOM element from an HTML string using built-in DOM methods or Prototype

Here is working code for me

I wanted to convert 'Text' string to HTML element

var diva = UWA.createElement('div');
diva.innerHTML = '<a href="http://wwww.example.com">Text</a>';
var aelement = diva.firstChild;

Calling variable defined inside one function from another function

def anotherFunction(word):
    for letter in word:              
        print("_", end=" ")

def oneFunction(lists):
    category = random.choice(list(lists.keys()))
    word = random.choice(lists[category])
    return anotherFunction(word)

Change package name for Android in React Native

Use npx react-native-rename <newName>

With custom Bundle Identifier (Android only. For iOS, please use Xcode)

$ npx react-native-rename <newName> -b <bundleIdentifier>

First, Switch to new branch (optional but recommended)

$ git checkout -b rename-app

Then, Rename your app $ npx react-native-rename "Travel App"

With custom Bundle Identifier

$ npx react-native-rename "Travel App" -b com.junedomingo.travelapp 

After you change the name, please make sure you go to the android folder and run gradlew clean. then go back to the main project and run npx react-native run-android.

Also If you have google-services.json file in your previous project, change accordingly with the new one ... then you are good to go :)

See More here https://github.com/junedomingo/react-native-rename#readme

Where to get "UTF-8" string literal in Java?

In Java 1.7+

Do not use "UTF-8" string, instead use Charset type parameter:

import java.nio.charset.StandardCharsets

...

new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8);

git ignore all files of a certain type, except those in a specific subfolder

An optional prefix ! which negates the pattern; any matching file excluded by a previous pattern will become included again. If a negated pattern matches, this will override lower precedence patterns sources.

http://schacon.github.com/git/gitignore.html

*.json
!spec/*.json

Compare two different files line by line in python

Once the file object is iterated, it is exausted.

>>> f = open('1.txt', 'w')
>>> f.write('1\n2\n3\n')
>>> f.close()
>>> f = open('1.txt', 'r')
>>> for line in f: print line
...
1

2

3

# exausted, another iteration does not produce anything.
>>> for line in f: print line
...
>>>

Use file.seek (or close/open the file) to rewind the file:

>>> f.seek(0)
>>> for line in f: print line
...
1

2

3

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

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

Basic squid conf

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

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

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

Please note the basic_ncsa_auth program instead of the old ncsa_auth

squid 2.x

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

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

Setting up a user

sudo htpasswd -c /etc/squid3/passwords username_you_like

and enter a password twice for the chosen username then

sudo service squid3 restart

squid 2.x

sudo htpasswd -c /etc/squid/passwords username_you_like

and enter a password twice for the chosen username then

sudo service squid restart

htdigest vs htpasswd

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

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

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

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

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

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

MacOS

Similar as above applies, but file paths are different.

Install squid

brew install squid

Start squid service

brew services start squid

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

Comment or remove following line:

http_access allow localnet

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

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

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

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

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

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

Restart the squid service

brew services restart squid

jQuery multiselect drop down menu

You could hack your own, not relying on jQuery plugins... though you'd need to keep track externally (in JS) of selected items since the transition would remove the selected state info:

<head>
  <script type='text/javascript' src='http://code.jquery.com/jquery-1.4.4.min.js'></script>
  <script type='text/javascript'>
    $(window).load(function(){
      $('#transactionType').focusin(function(){
        $('#transactionType').attr('multiple', true);
      });
      $('#transactionType').focusout(function(){
        $('#transactionType').attr('multiple', false);
      });
    });>  
  </script>
</head>
<body>
  <select id="transactionType">
    <option value="ALLOC">ALLOC</option>
    <option value="LOAD1">LOAD1</option>
    <option value="LOAD2">LOAD2</option>
  </select>  
</body>

Add a property to a JavaScript object using a variable as the name?

ajavascript have two type of annotation for fetching javascript Object properties:

Obj = {};

1) (.) annotation eg. Obj.id this will only work if the object already have a property with name 'id'

2) ([]) annotation eg . Obj[id] here if the object does not have any property with name 'id',it will create a new property with name 'id'.

so for below example:

A new property will be created always when you write Obj[name]. And if the property already exist with the same name it will override it.

const obj = {}
    jQuery(itemsFromDom).each(function() {
      const element = jQuery(this)
      const name = element.attr('id')
      const value = element.attr('value')
      // This will work
      obj[name]= value;
    })

Using column alias in WHERE clause of MySQL query produces an error

Standard SQL disallows references to column aliases in a WHERE clause. This restriction is imposed because when the WHERE clause is evaluated, the column value may not yet have been determined. For example, the following query is illegal:

SELECT id, COUNT(*) AS cnt FROM tbl_name WHERE cnt > 0 GROUP BY id;

Disabling the long-running-script message in Internet Explorer

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

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

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

Breaking up a loop with timers is relatively straightforward:

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

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

Bootstrap Carousel image doesn't align properly

Try this

    .item img{
      max-height: 300px;
      margin: auto;
    }

What is for Python what 'explode' is for PHP?

Choose one you need:

>>> s = "Rajasekar SP  def"
>>> s.split(' ')
['Rajasekar', 'SP', '', 'def']
>>> s.split()
['Rajasekar', 'SP', 'def']
>>> s.partition(' ')
('Rajasekar', ' ', 'SP  def')

str.split and str.partition

How to free memory from char array in C

Local variables are automatically freed when the function ends, you don't need to free them by yourself. You only free dynamically allocated memory (e.g using malloc) as it's allocated on the heap:

char *arr = malloc(3 * sizeof(char));
strcpy(arr, "bo");
// ...
free(arr);

More about dynamic memory allocation: http://en.wikipedia.org/wiki/C_dynamic_memory_allocation

How to draw a path on a map using kml file?

Mathias Lin code working beautifully. However, you might want to consider changing this part inside drawPath method:

 if (lngLat.length >= 2 && gp1.getLatitudeE6() > 0 && gp1.getLongitudeE6() > 0
                    && gp2.getLatitudeE6() > 0 && gp2.getLongitudeE6() > 0) {

GeoPoint can be less than zero as well, I switch mine to:

     if (lngLat.length >= 2 && gp1.getLatitudeE6() != 0 && gp1.getLongitudeE6() != 0
                    && gp2.getLatitudeE6() != 0 && gp2.getLongitudeE6() != 0) {

Thank you :D

Powershell 2 copy-item which creates a folder if doesn't exist

In PowerShell 2.0, it is still not possible to get the Copy-Item cmdlet to create the destination folder, you'll need code like this:

$destinationFolder = "C:\My Stuff\Subdir"

if (!(Test-Path -path $destinationFolder)) {New-Item $destinationFolder -Type Directory}
Copy-Item "\\server1\Upgrade.exe" -Destination $destinationFolder

If you use -Recurse in the Copy-Item it will create all the subfolders of the source structure in the destination but it won't create the actual destination folder, even with -Force.

Laravel 5.5 ajax call 419 (unknown status)

If you already done the above suggestions and still having the issue.

Make sure that the env variable:

SESSION_SECURE_COOKIE

Is set to false if you don't have a SSL certificate, like on local.

How to do a Jquery Callback after form submit?

I just did this -

 $("#myform").bind('ajax:complete', function() {

         // tasks to do 


   });

And things worked perfectly .

See this api documentation for more specific details.

How to check if a string contains only digits in Java

Try this part of code:

void containsOnlyNumbers(String str)
{
    try {
        Integer num = Integer.valueOf(str);
        System.out.println("is a number");
    } catch (NumberFormatException e) {
        // TODO: handle exception
        System.out.println("is not a number");
    }

}

Append text with .bat

You need to use ECHO. Also, put the quotes around the entire file path if it contains spaces.

One other note, use > to overwrite a file if it exists or create if it does not exist. Use >> to append to an existing file or create if it does not exist.

Overwrite the file with a blank line:

ECHO.>"C:\My folder\Myfile.log"

Append a blank line to a file:

ECHO.>>"C:\My folder\Myfile.log"

Append text to a file:

ECHO Some text>>"C:\My folder\Myfile.log"

Append a variable to a file:

ECHO %MY_VARIABLE%>>"C:\My folder\Myfile.log"

How to Display blob (.pdf) in an AngularJS app

Most recent answer (for Angular 8+):

this.http.post("your-url",params,{responseType:'arraybuffer' as 'json'}).subscribe(
  (res) => {
    this.showpdf(res);
  }
)};

public Content:SafeResourceUrl;
showpdf(response:ArrayBuffer) {
  var file = new Blob([response], {type: 'application/pdf'});
  var fileURL = URL.createObjectURL(file);
  this.Content = this.sanitizer.bypassSecurityTrustResourceUrl(fileURL);
}

  HTML :

  <embed [src]="Content" style="width:200px;height:200px;" type="application/pdf" />

OSX - How to auto Close Terminal window after the "exit" command executed.

Create a script:

cat ~/exit.scpt

like this:

  • Note: If there is only one window, just quit the application, else simulate command + w to close the tab)

tell application "Terminal" set WindowNum to get window count if WindowNum = 1 then quit else tell application "System Events" to keystroke "w" using command down end if end tell

Then add a alias in your *shrc

just like vi ~/.bashrc or zshrc (anything else?)

add it: alias exit="osascript ~/exit.scpt"

And source the ~/.bashrc or reopen your terminal.app

How to deal with SettingWithCopyWarning in Pandas

I had been getting this issue with .apply() when assigning a new dataframe from a pre-existing dataframe on which i've used the .query() method. For instance:

prop_df = df.query('column == "value"')
prop_df['new_column'] = prop_df.apply(function, axis=1)

Would return this error. The fix that seems to resolve the error in this case is by changing this to:

prop_df = df.copy(deep=True)
prop_df = prop_df.query('column == "value"')
prop_df['new_column'] = prop_df.apply(function, axis=1)

However, this is NOT efficient especially when using large dataframes, due to having to make a new copy.

If you're using the .apply() method in generating a new column and its values, a fix that resolves the error and is more efficient is by adding .reset_index(drop=True):

prop_df = df.query('column == "value"').reset_index(drop=True)
prop_df['new_column'] = prop_df.apply(function, axis=1)

How to process a file in PowerShell line-by-line as a stream

If you want to use straight PowerShell check out the below code.

$content = Get-Content C:\Users\You\Documents\test.txt
foreach ($line in $content)
{
    Write-Host $line
}

Is there a macro to conditionally copy rows to another worksheet?

If this is just a one-off exercise, as an easier alternative, you could apply filters to your source data, and then copy and paste the filtered rows into your new worksheet?

SQL Server : How to test if a string has only digit characters

Method that will work. The way it is used above will not work.

declare @str varchar(50)='79136'

select 
  case 
    when  @str LIKE replicate('[0-9]',LEN(@str)) then 1 
    else 0 
  end

declare @str2 varchar(50)='79D136'

select 
  case 
    when  @str2 LIKE replicate('[0-9]',LEN(@str)) then 1 
    else 0 
  end

Split string into array of character strings

"cat".toCharArray()

But if you need strings

"cat".split("")

Edit: which will return an empty first value.

Installing mcrypt extension for PHP on OSX Mountain Lion

Another possibility for those who want to keep OS X as clean as possible, is to use vagrant [1] to define a php development environment. Vagrant can use VirtualBox [2] in headless mode (~3% of CPU on my 13-inch, Mid 2009 MacBook Pro) to run a virtual machine with the webserver and php and all.

To easily create the vagrant environment you can use this great tool https://puphpet.com/

  1. http://www.vagrantup.com/
  2. https://www.virtualbox.org/

Eclipse error: 'Failed to create the Java Virtual Machine'

This worked for me:

I closed all the other memory intensive applications on my Windows 7 machine. And I tried to open Eclipse, and, voila, it worked.

How to create a list of objects?

You can create a list of objects in one line using a list comprehension.

class MyClass(object): pass

objs = [MyClass() for i in range(10)]

print(objs)

Call child component method from parent class - Angular

user6779899's answer is neat and more generic However, based on the request by Imad El Hitti, a light weight solution is proposed here. This can be used when a child component is tightly connected to one parent only.

Parent.component.ts

export class Notifier {
    valueChanged: (data: number) => void = (d: number) => { };
}

export class Parent {
    notifyObj = new Notifier();
    tellChild(newValue: number) {
        this.notifyObj.valueChanged(newValue); // inform child
    }
}

Parent.component.html

<my-child-comp [notify]="notifyObj"></my-child-comp>

Child.component.ts

export class ChildComp implements OnInit{
    @Input() notify = new Notifier(); // create object to satisfy typescript
    ngOnInit(){
      this.notify.valueChanged = (d: number) => {
            console.log(`Parent has notified changes to ${d}`);
            // do something with the new value 
        };
    }
 }

how to pass variable from shell script to sqlplus

You appear to have a heredoc containing a single SQL*Plus command, though it doesn't look right as noted in the comments. You can either pass a value in the heredoc:

sqlplus -S user/pass@localhost << EOF
@/opt/D2RQ/file.sql BUILDING
exit;
EOF

or if BUILDING is $2 in your script:

sqlplus -S user/pass@localhost << EOF
@/opt/D2RQ/file.sql $2
exit;
EOF

If your file.sql had an exit at the end then it would be even simpler as you wouldn't need the heredoc:

sqlplus -S user/pass@localhost @/opt/D2RQ/file.sql $2

In your SQL you can then refer to the position parameters using substitution variables:

...
}',SEM_Models('&1'),NULL,
...

The &1 will be replaced with the first value passed to the SQL script, BUILDING; because that is a string it still needs to be enclosed in quotes. You might want to set verify off to stop if showing you the substitutions in the output.


You can pass multiple values, and refer to them sequentially just as you would positional parameters in a shell script - the first passed parameter is &1, the second is &2, etc. You can use substitution variables anywhere in the SQL script, so they can be used as column aliases with no problem - you just have to be careful adding an extra parameter that you either add it to the end of the list (which makes the numbering out of order in the script, potentially) or adjust everything to match:

sqlplus -S user/pass@localhost << EOF
@/opt/D2RQ/file.sql total_count BUILDING
exit;
EOF

or:

sqlplus -S user/pass@localhost << EOF
@/opt/D2RQ/file.sql total_count $2
exit;
EOF

If total_count is being passed to your shell script then just use its positional parameter, $4 or whatever. And your SQL would then be:

SELECT COUNT(*) as &1
FROM TABLE(SEM_MATCH(
'{
        ?s rdf:type :ProcessSpec .
        ?s ?p ?o
}',SEM_Models('&2'),NULL,
SEM_ALIASES(SEM_ALIAS('','http://VISION/DataSource/SEMANTIC_CACHE#')),NULL));

If you pass a lot of values you may find it clearer to use the positional parameters to define named parameters, so any ordering issues are all dealt with at the start of the script, where they are easier to maintain:

define MY_ALIAS = &1
define MY_MODEL = &2

SELECT COUNT(*) as &MY_ALIAS
FROM TABLE(SEM_MATCH(
'{
        ?s rdf:type :ProcessSpec .
        ?s ?p ?o
}',SEM_Models('&MY_MODEL'),NULL,
SEM_ALIASES(SEM_ALIAS('','http://VISION/DataSource/SEMANTIC_CACHE#')),NULL));

From your separate question, maybe you just wanted:

SELECT COUNT(*) as &1
FROM TABLE(SEM_MATCH(
'{
        ?s rdf:type :ProcessSpec .
        ?s ?p ?o
}',SEM_Models('&1'),NULL,
SEM_ALIASES(SEM_ALIAS('','http://VISION/DataSource/SEMANTIC_CACHE#')),NULL));

... so the alias will be the same value you're querying on (the value in $2, or BUILDING in the original part of the answer). You can refer to a substitution variable as many times as you want.

That might not be easy to use if you're running it multiple times, as it will appear as a header above the count value in each bit of output. Maybe this would be more parsable later:

select '&1' as QUERIED_VALUE, COUNT(*) as TOTAL_COUNT

If you set pages 0 and set heading off, your repeated calls might appear in a neat list. You might also need to set tab off and possibly use rpad('&1', 20) or similar to make that column always the same width. Or get the results as CSV with:

select '&1' ||','|| COUNT(*)

Depends what you're using the results for...

XAMPP keeps showing Dashboard/Welcome Page instead of the Configuration Page

Easiest solution for this to remove the index.php code which is allocated on

xammp-> htdocs-> index.php 

you can delete the code of this page to solution your problem but have another way which is .htaccss file. Some time you show this problem because of have some issue or miss code on .htaccss file thas way yo saw the xammp dashboard every time. Hop it will resolve your problem. Happy Coding and Good Luck

How do I get JSON data from RESTful service using Python?

Well first of all I think rolling out your own solution for this all you need is urllib2 or httplib2 . Anyways in case you do require a generic REST client check this out .

https://github.com/scastillo/siesta

However i think the feature set of the library will not work for most web services because they shall probably using oauth etc .. . Also I don't like the fact that it is written over httplib which is a pain as compared to httplib2 still should work for you if you don't have to handle a lot of redirections etc ..

How to execute XPath one-liners from shell?

One package that is very likely to be installed on a system already is python-lxml. If so, this is possible without installing any extra package:

python -c "from lxml.etree import parse; from sys import stdin; print('\n'.join(parse(stdin).xpath('//element/@attribute')))"

Numpy: Checking if a value is NaT

Very simple and surprisingly fast: (without numpy or pandas)

    str( myDate ) == 'NaT'            # True if myDate is NaT

Ok, it's a little nasty, but given the ambiguity surrounding 'NaT' it does the job nicely.

It's also useful when comparing two dates either of which might be NaT as follows:

   str( date1 ) == str( date1 )       # True
   str( date1 ) == str( NaT )         # False
   str( NaT )   == str( date1 )       # False

wait for it...

   str( NaT )   == str( Nat )         # True    (hooray!)

Hiding elements in responsive layout?

New visible classes added to Bootstrap

Extra small devices Phones (<768px) (Class names : .visible-xs-block, hidden-xs)

Small devices Tablets (=768px) (Class names : .visible-sm-block, hidden-sm)

Medium devices Desktops (=992px) (Class names : .visible-md-block, hidden-md)

Large devices Desktops (=1200px) (Class names : .visible-lg-block, hidden-lg)

For more information : http://getbootstrap.com/css/#responsive-utilities


Below is deprecated as of v3.2.0


Extra small devices Phones (<768px) (Class names : .visible-xs, hidden-xs)

Small devices Tablets (=768px) (Class names : .visible-sm, hidden-sm)

Medium devices Desktops (=992px) (Class names : .visible-md, hidden-md)

Large devices Desktops (=1200px) (Class names : .visible-lg, hidden-lg)


Much older Bootstrap


.hidden-phone, .hidden-tablet etc. are unsupported/obsolete.

UPDATE:

In Bootstrap 4 there are 2 types of classes:

  • The hidden-*-up which hide the element when the viewport is at the given breakpoint or wider.
  • hidden-*-down which hide the element when the viewport is at the given breakpoint or smaller.

Also, the new xl viewport is added for devices that are more then 1200px width. For more information click here.

how to change php version in htaccess in server

Note that all above answers are correct for Apache+ setups. They're less likely to work with more current PHP-FPM setups. Those can typically only be defined in VirtualHost section, not .htaccess.

Again, this highly depends on how your hoster has configured PHP. Each domain/user will typically have it's own running PHP FPM instance. And subsequently a generic …/x-httpd-php52 type will not be recognized.

See ServerFault: Alias a FastCGI proxy protocol handler via Action/ScriptAlias/etc for some overview.

For Apache 2.4.10+/ configs you might be able to use something like:

 AddHandler "proxy:unix:/var/run/php-fpm-usr123.sock|fcgi://localhost" .php

Or SetHandler with name mapping from your .htaccess. But again, consulting your hoster on the concrete FPM socket is unavoidable. There's no generic answer to this on modern PHP-FPM setups.

assign headers based on existing row in dataframe in R

A new answer that uses dplyr and tidyr:

Extracts the desired column names and converts to a list

library(tidyverse)

col_names <- raw_dta %>% 
  slice(2) %>%
  pivot_longer(
    cols = "X2":"X10", # until last named column
    names_to = "old_names",
    values_to = "new_names") %>% 
  pull(new_names)

Removes the incorrect rows and adds the correct column names

dta <- raw_dta %>% 
  slice(-1, -2) %>% # Removes the rows containing new and original names
  set_names(., nm = col_names)

Visual Studio 2013 Install Fails: Program Compatibility Mode is on (Windows 10)

Answer that worked here.

They recommend checking the installer file name. It needs to be the original name oddly enough for the setup to work.

npm start error with create-react-app

it's possible that conflict with other library, delete node_modules and again npm install.

How to install pandas from pip on windows cmd?

If you are a windows user:
make sure you added the script(dir) path to environment variables
C:\Python34\Scripts
for more how to set path vist

How remove border around image in css?

Another thing - remember that if you have an with an empty src attribute, then none of these suggestions will work, a border will still get shown.

<img src="" style="width:30px;height:30px;">

LINQ to read XML

Or, if you want a more general approach - i.e. for nesting up to "levelN":

void Main()
{
    XElement rootElement = XElement.Load(@"c:\events\test.xml");

    Console.WriteLine(GetOutline(0, rootElement));  
}

private string GetOutline(int indentLevel, XElement element)
{
    StringBuilder result = new StringBuilder();

    if (element.Attribute("name") != null)
    {
        result = result.AppendLine(new string(' ', indentLevel * 2) + element.Attribute("name").Value);
    }

    foreach (XElement childElement in element.Elements())
    {
        result.Append(GetOutline(indentLevel + 1, childElement));
    }

    return result.ToString();
}

MySQL Incorrect datetime value: '0000-00-00 00:00:00'

I have this error as well after upgrading MySQL from 5.6 to 5.7

I figured out that the best solution for me was to combine some of the solutions here and make something of it that worked with the minimum of input.

I use MyPHPAdmin for the simplicity of sending the queries through the interface because then I can check the structure and all that easily. You might use ssh directly or some other interface. The method should be similar or same anyway.

...

1.

First check out the actual error when trying to repair the db:

joomla.jos_menu Note : TIME/TIMESTAMP/DATETIME columns of old format have been upgraded to the new format.

Warning : Incorrect datetime value: '0000-00-00 00:00:00' for column 'checked_out_time' at row 1

Error : Invalid default value for 'checked_out_time'

status : Operation failed

This tells me the column checked_out_time in the table jos_menu needs to have all bad dates fixed as well as the "default" changed.

...

2.

I run the SQL query based on the info in the error message:

UPDATE jos_menu SET checked_out_time = '1970-01-01 08:00:00' WHERE checked_out_time = 0

If you get an error you can use the below query instead that seems to always work:

UPDATE jos_menu SET checked_out_time = '1970-01-01 08:00:00' WHERE CAST(checked_out_time AS CHAR(20)) = '0000-00-00 00:00:00'

...

3.

Then once that is done I run the second SQL query:

ALTER TABLE `jos_menu` CHANGE `checked_out_time` `checked_out_time` DATETIME NULL DEFAULT CURRENT_TIMESTAMP;

Or in the case it is a date that has to be NULL

ALTER TABLE `jos_menu` CHANGE `checked_out_time` `checked_out_time` DATETIME NULL DEFAULT NULL;

...

If I run repair database now I get:

joomla.jos_menu OK

...

Works just fine :)

Select elements by attribute in CSS

You can combine multiple selectors and this is so cool knowing that you can select every attribute and attribute based on their value like href based on their values with CSS only..

Attributes selectors allows you play around some extra with id and class attributes

Here is an awesome read on Attribute Selectors

Fiddle

_x000D_
_x000D_
a[href="http://aamirshahzad.net"][title="Aamir"] {_x000D_
  color: green;_x000D_
  text-decoration: none;_x000D_
}_x000D_
_x000D_
a[id*="google"] {_x000D_
  color: red;_x000D_
}_x000D_
_x000D_
a[class*="stack"] {_x000D_
  color: yellow;_x000D_
}
_x000D_
<a href="http://aamirshahzad.net" title="Aamir">Aamir</a>_x000D_
<br>_x000D_
<a href="http://google.com" id="google-link" title="Google">Google</a>_x000D_
<br>_x000D_
<a href="http://stackoverflow.com" class="stack-link" title="stack">stack</a>
_x000D_
_x000D_
_x000D_

Browser support:
IE6+, Chrome, Firefox & Safari

You can check detail here.

Get current URL with jQuery?

Very Commonly Used top 3 ones are

1. window.location.hostname 
2. window.location.href
3. window.location.pathname

What is the Python equivalent for a case/switch statement?

While the official docs are happy not to provide switch, I have seen a solution using dictionaries.

For example:

# define the function blocks
def zero():
    print "You typed zero.\n"

def sqr():
    print "n is a perfect square\n"

def even():
    print "n is an even number\n"

def prime():
    print "n is a prime number\n"

# map the inputs to the function blocks
options = {0 : zero,
           1 : sqr,
           4 : sqr,
           9 : sqr,
           2 : even,
           3 : prime,
           5 : prime,
           7 : prime,
}

Then the equivalent switch block is invoked:

options[num]()

This begins to fall apart if you heavily depend on fall through.

Does WGET timeout?

Since in your question you said it's a PHP script, maybe the best solution could be to simply add in your script:

ignore_user_abort(TRUE);

In this way even if wget terminates, the PHP script goes on being processed at least until it does not exceeds max_execution_time limit (ini directive: 30 seconds by default).

As per wget anyay you should not change its timeout, according to the UNIX manual the default wget timeout is 900 seconds (15 minutes), whis is much larger that the 5-6 minutes you need.

How do I simulate a low bandwidth, high latency environment?

Take a look at the NE-ONE Network Emulator which allows you to configure bandwidth, latency, packet loss, packet reordering, packet duplication, packet fragmentation, network congestion and many more impairments so that you can create real-world network conditions in the lab. Different impairments can be configured for the up and downlink so you could have a really good uplink but a really bad downlink experience, great for seeing how the app handles TCP queuing because the acks don't come back in a timely manner and the overall latency therefore increases!

There's an overview video here http://www.youtube.com/watch?v=DwtqlE7LcrQ specifically aimed at game developers, but it shows what it's about. NE-ONE is configured using a web browser so it's really easy to get installed and configured - you don't need to be a network guru :-)

There's a hardware version - http://www.itrinegy.com/index.php/products/network-emulators/ne-one - or you can download a Virtual Appliance (software) version that runs under VMware ESXi Server. The Virtual Appliance can be download from VMware's Solution Exchange - solutionexchange.vmware.com/store/products/ne-one-flex-network-emulator

How can I make my website's background transparent without making the content (images & text) transparent too?

I think the simplest solution, rather than making the body element partially transparent, would be to add an extra div to hold the background, and change the opacity there, instead.

So you would add a div like:

<div id="background"></div>

And move your body element's background CSS to it, as well as some additional positioning properties, like this:

#background {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-image: url('images/background.jpg');
    background-repeat: no-repeat;
    background-attachment: fixed;
    background-size: 100%;
    opacity: 0.8;
    filter:alpha(opacity=80);
}

Here's an example: http://jsfiddle.net/nbVg4/4/

Regular Expression - 2 letters and 2 numbers in C#

This should get you for starting with two letters and ending with two numbers.

[A-Za-z]{2}(.*)[0-9]{2}

If you know it will always be just two and two you can

[A-Za-z]{2}[0-9]{2}

Swap two variables without using a temporary variable

var a = 15;
var b = -214;
a = b | !(b = a);

This works great.

AngularJs event to call after content is loaded

fixed - 2015.06.09

Use a directive and the angular element ready method like so:

js

.directive( 'elemReady', function( $parse ) {
   return {
       restrict: 'A',
       link: function( $scope, elem, attrs ) {    
          elem.ready(function(){
            $scope.$apply(function(){
                var func = $parse(attrs.elemReady);
                func($scope);
            })
          })
       }
    }
})

html

<div elem-ready="someMethod()"></div>

or for those using controller-as syntax...

<div elem-ready="vm.someMethod()"></div>

The benefit of this is that you can be as broad or granular w/ your UI as you like and you are removing DOM logic from your controllers. I would argue this is the recommended Angular way.

You may need to prioritize this directive in case you have other directives operating on the same node.

Bootstrap: 'TypeError undefined is not a function'/'has no method 'tab'' when using bootstrap-tabs

I actually managed to work out what I was doing wrong (and it was my fault).

I'm used to using pre-jQuery Rails, so when I included the Bootstrap JS files I didn't think that including the version of jQuery bundled with them would cause any issues, however when I removed that one JS file everything started working perfectly.

Lesson learnt, triple check which JS files are loaded, see if there's any conflicts.

How should I escape commas and speech marks in CSV files so they work in Excel?

Single quotes work fine too, even without escaping the double quotes, at least in Excel 2016:

'text with spaces, and a comma','more text with spaces','spaces and "quoted text" and more spaces','nospaces','NOSPACES1234'

Excel will put that in 5 columns (if you choose the single quote as "Text qualifier" in the "Text to columns" wizard)

Saving binary data as file using JavaScript from a browser

Use FileSaver.js. It supports Chrome, Edge, Firefox, and IE 10+ (and probably IE < 10 with a few "polyfills" - see Note 4). FileSaver.js implements the saveAs() FileSaver interface in browsers that do not natively support it:
     https://github.com/eligrey/FileSaver.js

Minified version is really small at < 2.5KB, gzipped < 1.2KB.

Usage:

/* TODO: replace the blob content with your byte[] */
var blob = new Blob([yourBinaryDataAsAnArrayOrAsAString], {type: "application/octet-stream"});
var fileName = "myFileName.myExtension";
saveAs(blob, fileName);

You might need Blob.js in some browsers (see Note 3). Blob.js implements the W3C Blob interface in browsers that do not natively support it. It is a cross-browser implementation:
     https://github.com/eligrey/Blob.js

Consider StreamSaver.js if you have files larger than blob's size limitations.

Complete example:

_x000D_
_x000D_
/* Two options_x000D_
 * 1. Get FileSaver.js from here_x000D_
 *     https://github.com/eligrey/FileSaver.js/blob/master/FileSaver.min.js -->_x000D_
 *     <script src="FileSaver.min.js" />_x000D_
 *_x000D_
 * Or_x000D_
 *_x000D_
 * 2. If you want to support only modern browsers like Chrome, Edge, Firefox, etc., _x000D_
 *    then a simple implementation of saveAs function can be:_x000D_
 */_x000D_
function saveAs(blob, fileName) {_x000D_
    var url = window.URL.createObjectURL(blob);_x000D_
_x000D_
    var anchorElem = document.createElement("a");_x000D_
    anchorElem.style = "display: none";_x000D_
    anchorElem.href = url;_x000D_
    anchorElem.download = fileName;_x000D_
_x000D_
    document.body.appendChild(anchorElem);_x000D_
    anchorElem.click();_x000D_
_x000D_
    document.body.removeChild(anchorElem);_x000D_
_x000D_
    // On Edge, revokeObjectURL should be called only after_x000D_
    // a.click() has completed, atleast on EdgeHTML 15.15048_x000D_
    setTimeout(function() {_x000D_
        window.URL.revokeObjectURL(url);_x000D_
    }, 1000);_x000D_
}_x000D_
_x000D_
(function() {_x000D_
    // convert base64 string to byte array_x000D_
    var byteCharacters = atob("R0lGODlhkwBYAPcAAAAAAAABGRMAAxUAFQAAJwAANAgwJSUAACQfDzIoFSMoLQIAQAAcQwAEYAAHfAARYwEQfhkPfxwXfQA9aigTezchdABBckAaAFwpAUIZflAre3pGHFpWVFBIf1ZbYWNcXGdnYnl3dAQXhwAXowkgigIllgIxnhkjhxktkRo4mwYzrC0Tgi4tiSQzpwBIkBJIsyxCmylQtDVivglSxBZu0SlYwS9vzDp94EcUg0wziWY0iFROlElcqkxrtW5OjWlKo31kmXp9hG9xrkty0ziG2jqQ42qek3CPqn6Qvk6I2FOZ41qn7mWNz2qZzGaV1nGOzHWY1Gqp3Wy93XOkx3W1x3i33G6z73nD+ZZIHL14KLB4N4FyWOsECesJFu0VCewUGvALCvACEfEcDfAcEusKJuoINuwYIuoXN+4jFPEjCvAgEPM3CfI5GfAxKuoRR+oaYustTus2cPRLE/NFJ/RMO/dfJ/VXNPVkNvFPTu5KcfdmQ/VuVvl5SPd4V/Nub4hVj49ol5RxoqZfl6x0mKp5q8Z+pu5NhuxXiu1YlvBdk/BZpu5pmvBsjfBilvR/jvF3lO5nq+1yre98ufBoqvBrtfB6p/B+uPF2yJiEc9aQMsSKQOibUvqKSPmEWPyfVfiQaOqkSfaqTfyhXvqwU+u7dfykZvqkdv+/bfy1fpGvvbiFnL+fjLGJqqekuYmTx4SqzJ2+2Yy36rGawrSwzpjG3YjB6ojG9YrU/5XI853U75bV/J3l/6PB6aDU76TZ+LHH6LHX7rDd+7Lh3KPl/bTo/bry/MGJm82VqsmkjtSptfWMj/KLsfu0je6vsNW1x/GIxPKXx/KX1ea8w/Wnx/Oo1/a3yPW42/S45fvFiv3IlP/anvzLp/fGu/3Xo/zZt//knP7iqP7qt//xpf/0uMTE3MPd1NXI3MXL5crS6cfe99fV6cXp/cj5/tbq+9j5/vbQy+bY5/bH6vbJ8vfV6ffY+f7px/3n2f/4yP742OPm8ef9//zp5vjn/f775/7+/gAAACwAAAAAkwBYAAAI/wD9CRxIsKDBgwgTKlzIsKHDhxAjSpxIsaLFixgzatzIsaPHjxD7YQrSyp09TCFSrQrxCqTLlzD9bUAAAMADfVkYwCIFoErMn0AvnlpAxR82A+tGWWgnLoCvoFCjOsxEopzRAUYwBFCQgEAvqWDDFgTVQJhRAVI2TUj3LUAusXDB4jsQxZ8WAMNCrW37NK7foN4u1HThD0sBWpoANPnL+GG/OV2gSUT24Yi/eltAcPAAooO+xqAVbkPT5VDo0zGzfemyqLE3a6hhmurSpRLjcGDI0ItdsROXSAn5dCGzTOC+d8j3gbzX5ky8g+BoTzq4706XL1/KzONdEBWXL3AS3v/5YubavU9fuKg/44jfQmbK4hdn+Jj2/ILRv0wv+MnLdezpweEed/i0YcYXkCQkB3h+tPEfgF3AsdtBzLSxGm1ftCHJQqhc54Y8B9UzxheJ8NfFgWakSF6EA57WTDN9kPdFJS+2ONAaKq6Whx88enFgeAYx892FJ66GyEHvvGggeMs0M01B9ajRRYkD1WMgF60JpAx5ZEgGWjZ44MHFdSkeSBsceIAoED5gqFgGbAMxQx4XlxjESRdcnFENcmmcGBlBfuDh4Ikq0kYGHoxUKSWVApmCnRsFCddlaEPSVuaFED7pDz5F5nGQJ9cJWFA/d1hSUCfYlSFQfdgRaqal6UH/epmUjRDUx3VHEtTPHp5SOuYyn5x4xiMv3jEmlgKNI+w1B/WTxhdnwLnQY2ZwEY1AeqgHRzN0/PiiMmh8x8Vu9YjRxX4CjYcgdwhhE6qNn8DBrD/5AXnQeF3ct1Ap1/VakB3YbThQgXEIVG4X1w7UyXUFs2tnvwq5+0XDBy38RZYMKQuejf7Yw4YZXVCjEHwFyQmyyA4TBPAXhiiUDcMJzfaFvwXdgWYbz/jTjxjgTTiQN2qYQca8DxV44KQpC7SyIi7DjJCcExeET7YAplcGNQvC8RxB3qS6XUTacHEgF7mmvHTTUT+Nnb06Ozi2emOWYeEZRAvUdXZfR/SJ2AdS/8zuymUf9HLaFGLnt3DkPTIQqTLSXRDQ2W0tETbYHSgru3eyjLbfJa9dpYEIG6QHdo4T5LHQdUfUjduas9vhxglJzLaJhKtGOEHdhKrm4gB3YapFdlznHLvhiB1tQtqEmpDFFL9umkH3hNGzQTF+8YZjzGi6uBgg58yuHH0nFM67CIH/xfP+OH9Q9LAXRHn3Du1NhuQCgY80dyZ/4caee58xocYSOgg+uOe7gWzDcwaRWMsOQocVLQI5bOBCggzSDzx8wQsTFEg4RnQ8h1nnVdchA8rucZ02+Iwg4xOaly4DOu8tbg4HogRC6uGfVx3oege5FbQ0VQ8Yts9hnxiUpf9qtapntYF+AxFFqE54qwPlYR772Mc2xpAiLqSOIPiwIG3OJC0ooQFAOVrNFbnTj/jEJ3U4MgPK/oUdmumMDUWCm6u6wDGDbMOMylhINli3IjO4MGkLqcMX7rc4B1nRIPboXdVUdLmNvExFGAMkQxZGHAHmYYXQ4xGPogGO1QBHkn/ZhhfIsDuL3IMLbjghKDECj3O40pWrjIk6XvkZj9hDCEKggAh26QAR9IAJsfzILXkpghj0RSPOYAEJdikCEjjTmczURTA3cgxmQlMEJbBFRlixAms+85vL3KUVpomRQOwSnMtUwTos8g4WnBOd8BTBCNxBzooA4p3oFAENKLL/Dx/g85neRCcEblDPifjzm/+UJz0jkgx35tMBSWDFCZqZTxWwo6AQYQVFwzkFh17zChG550YBKoJx9iMHIwVoCY6J0YVUk6K7TII/UEpSJRQNpSkNZy1WRdN8lgAXLWXIOyYKUIv2o5sklWlD7EHUfIrApsbxKDixqc2gJqQfOBipA4qwqRVMdQgNaWdOw2kD00kVodm0akL+MNJdfuYdbRWBUhVy1LGmc6ECEWs8S0AMtR4kGfjcJREEAliEPnUh9uipU1nqD8COVQQqwKtfBWIPXSJUBcEQCFsNO06F3BOe4ZzrQDQKWhHMYLIFEURKRVCDz5w0rlVFiEbtCtla/xLks/B0wBImAo98iJSZIrDBRTPSjqECd5c7hUgzElpSyjb1msNF0j+nCtJRaeCxIoiuQ2YhhF4el5cquIg9kJAD735Xt47RwWqzS9iEhjch/qTtaQ0C18fO1yHvQAFzmflTiwBiohv97n0bstzV3pcQCR0sQlQxXZLGliDVjGdzwxrfADvgBULo60WSEQHm8uAJE8EHUqfaWX8clKSMHViDAfoC2xJksxWVbEKSMWKSOgGvhOCBjlO8kPgi1AEqAMbifqDjsjLkpVNVZ15rvMwWI4SttBXBLQR41muWWCFQnuoLhquOCoNXxggRa1yVuo9Z6PK4okVklZdpZH8YY//MYWZykhFS4Io2JMsIjQE97cED814TstpFkgSY29lk4DTAMZ1xTncJVX+oF60aNgiMS8vVg4h0qiJ4MEJ8jNAX0FPMpR2wQaRRZUYLZBArDueVCXJdn0rzMgmttEHwYddr8riy603zQfBM0uE6o5u0dcCqB/IOyxq2zeasNWTBvNx4OtkfSL4mmE9d6yZPm8EVdfFBZovpRm/qzBJ+tq7WvEvtclvCw540QvepsxOH09u6UqxTdd3V1UZ2IY7FdAy0/drSrtQg7ibpsJsd6oLoNZ+vdsY7d9nmUT/XqcP2RyGYy+NxL9oB1TX4isVZkHxredq4zec8CXJuhI5guCH/L3dCLu3vYtD3rCpfCKoXPQJFl7bh/TC2YendbuwOg9WPZXd9ba2QgNtZ0ohWQaQTYo81L5PdzZI3QBse4XyS4NV/bfAusQ7X0ioVxrvUdEHsIeepQn0gdQ6nqBOCagmLneRah3rTH6sCbeuq7LvMeNUxPU69hn0hBAft0w0ycxEAORYI2YcrWJoBuq8zIdLQeps9PtWG73rRUh6I0aHZ3wqrAKiArzYJ0FsQbjjAASWIRTtkywIH3Hfo+RQ3ksjd5pCDU9gyx/zPN+V0EZiAGM3o5YVXP5Bk1OAgbxa8M3EfEXNUgJltnnk8bWB3i+dztzprfGkzTmfMDzftH8fH/w9igHWBBF8EuzBI8pUvAu43JNnLL7G6EWp5Na8X9GQXvAjKf5DAF3Ug0fZxCPFaIrB7BOF/8fR2COFYMFV3q7IDtFV/Y1dqniYQ3KBs/GcQhXV72OcPtpdn1eeBzBRo/tB1ysd8C+EMELhwIqBg/rAPUjd1IZhXMBdcaKdsCjgQbWdYx7R50KRn28ZM71UQ+6B9+gdvFMRp16RklOV01qYQARhOWLd3AoWEBfFoJCVuPrhM+6aB52SDllZt+pQQswAE3jVVpPeAUZaBBGF0pkUQJuhsCgF714R4mkdbTDhavRROoGcQUThVJQBmrLADZ4hpQzgQ87duCUGH4fRgIuOmfyXAhgLBctDkgHfob+UHf00Wgv1WWpDFC+qADuZwaNiVhwCYarvEY1gFZwURg9fUhV4YV0vnD+bkiS+ADurACoW4dQoBfk71XcFmA9NWD6mWTozVD+oVYBAge9SmfyIgAwbhDINmWEhIeZh2XNckgQVBicrHfrvkBFgmhsW0UC+FaMxIg8qGTZ3FD0r4bgfBVKKnbzM4EP1UjN64Sz1AgmOHU854eoUYTg4gjIqGirx0eoGFTVbYjN0IUMs4bc1yXfFoWIZHA/ngEGRnjxImVwwxWxFpWCPgclfVagtpeC9AfKIPwY3eGAM94JCehZGGFQOzuIj8uJDLhHrgKFRlh2k8xxCz8HwBFU4FaQOzwJIMQQ5mCFzXaHg28AsRUWbA9pNA2UtQ8HgNAQ8QuV6HdxHvkALudFwpAAMtEJMWMQgsAAPAyJVgxU47AANdCVwlAJaSuJEsAGDMBJYGiBH94Ap6uZdEiRGysJd7OY8S8Q6AqZe8kBHOUJiCiVqM2ZiO+ZgxERAAOw==");_x000D_
    var byteNumbers = new Array(byteCharacters.length);_x000D_
    for (var i = 0; i < byteCharacters.length; i++) {_x000D_
        byteNumbers[i] = byteCharacters.charCodeAt(i);_x000D_
    }_x000D_
    var byteArray = new Uint8Array(byteNumbers);_x000D_
    _x000D_
    // now that we have the byte array, construct the blob from it_x000D_
    var blob1 = new Blob([byteArray], {type: "application/octet-stream"});_x000D_
_x000D_
    var fileName1 = "cool.gif";_x000D_
    saveAs(blob1, fileName1);_x000D_
_x000D_
    // saving text file_x000D_
    var blob2 = new Blob(["cool"], {type: "text/plain"});_x000D_
    var fileName2 = "cool.txt";_x000D_
    saveAs(blob2, fileName2);_x000D_
})();
_x000D_
_x000D_
_x000D_


Tested on Chrome, Edge, Firefox, and IE 11 (use FileSaver.js for supporting IE 11).
You can also save from a canvas element. See https://github.com/eligrey/FileSaver.js#saving-a-canvas.

Demos: https://eligrey.com/demos/FileSaver.js/

Blog post by author of FileSaver.js: http://eligrey.com/blog/post/saving-generated-files-on-the-client-side

Note 1: Browser support: https://github.com/eligrey/FileSaver.js#supported-browsers

Note 2: Failed to execute 'atob' on 'Window'

Note 3: Polyfill for browsers not supporting Blob: https://github.com/eligrey/Blob.js
                See http://caniuse.com/#search=blob

Note 4: IE < 10 support (I've not tested this part):
                https://github.com/eligrey/FileSaver.js#ie--10
                https://github.com/eligrey/FileSaver.js/issues/56#issuecomment-30917476

Downloadify is a Flash-based polyfill for supporting IE6-9: https://github.com/dcneiner/downloadify (I don't recommend Flash-based solutions in general, though.)
Demo using Downloadify and FileSaver.js for supporting IE6-9 also: http://sheetjs.com/demos/table.html

Note 5: Creating a BLOB from a Base64 string in JavaScript

Note 6: FileSaver.js examples: https://github.com/eligrey/FileSaver.js#examples

How to sort a dataframe by multiple column(s)

I learned about order with the following example which then confused me for a long time:

set.seed(1234)

ID        = 1:10
Age       = round(rnorm(10, 50, 1))
diag      = c("Depression", "Bipolar")
Diagnosis = sample(diag, 10, replace=TRUE)

data = data.frame(ID, Age, Diagnosis)

databyAge = data[order(Age),]
databyAge

The only reason this example works is because order is sorting by the vector Age, not by the column named Age in the data frame data.

To see this create an identical data frame using read.table with slightly different column names and without making use of any of the above vectors:

my.data <- read.table(text = '

  id age  diagnosis
   1  49 Depression
   2  50 Depression
   3  51 Depression
   4  48 Depression
   5  50 Depression
   6  51    Bipolar
   7  49    Bipolar
   8  49    Bipolar
   9  49    Bipolar
  10  49 Depression

', header = TRUE)

The above line structure for order no longer works because there is no vector named age:

databyage = my.data[order(age),]

The following line works because order sorts on the column age in my.data.

databyage = my.data[order(my.data$age),]

I thought this was worth posting given how confused I was by this example for so long. If this post is not deemed appropriate for the thread I can remove it.

EDIT: May 13, 2014

Below is a generalized way of sorting a data frame by every column without specifying column names. The code below shows how to sort from left to right or by right to left. This works if every column is numeric. I have not tried with a character column added.

I found the do.call code a month or two ago in an old post on a different site, but only after extensive and difficult searching. I am not sure I could relocate that post now. The present thread is the first hit for ordering a data.frame in R. So, I thought my expanded version of that original do.call code might be useful.

set.seed(1234)

v1  <- c(0,0,0,0, 0,0,0,0, 1,1,1,1, 1,1,1,1)
v2  <- c(0,0,0,0, 1,1,1,1, 0,0,0,0, 1,1,1,1)
v3  <- c(0,0,1,1, 0,0,1,1, 0,0,1,1, 0,0,1,1)
v4  <- c(0,1,0,1, 0,1,0,1, 0,1,0,1, 0,1,0,1)

df.1 <- data.frame(v1, v2, v3, v4) 
df.1

rdf.1 <- df.1[sample(nrow(df.1), nrow(df.1), replace = FALSE),]
rdf.1

order.rdf.1 <- rdf.1[do.call(order, as.list(rdf.1)),]
order.rdf.1

order.rdf.2 <- rdf.1[do.call(order, rev(as.list(rdf.1))),]
order.rdf.2

rdf.3 <- data.frame(rdf.1$v2, rdf.1$v4, rdf.1$v3, rdf.1$v1) 
rdf.3

order.rdf.3 <- rdf.1[do.call(order, as.list(rdf.3)),]
order.rdf.3

Python Finding Prime Factors

My code:

# METHOD: PRIME FACTORS
def prime_factors(n):
    '''PRIME FACTORS: generates a list of prime factors for the number given
    RETURNS: number(being factored), list(prime factors), count(how many loops to find factors, for optimization)
    '''
    num = n                         #number at the end
    count = 0                       #optimization (to count iterations)
    index = 0                       #index (to test)
    t = [2, 3, 5, 7]                #list (to test)
    f = []                          #prime factors list
    while t[index] ** 2 <= n:
        count += 1                  #increment (how many loops to find factors)
        if len(t) == (index + 1):
            t.append(t[-2] + 6)     #extend test list (as much as needed) [2, 3, 5, 7, 11, 13...]
        if n % t[index]:            #if 0 does else (otherwise increments, or try next t[index])
            index += 1              #increment index
        else:
            n = n // t[index]       #drop max number we are testing... (this should drastically shorten the loops)
            f.append(t[index])      #append factor to list
    if n > 1:
        f.append(n)                 #add last factor...
    return num, f, f'count optimization: {count}'

Which I compared to the code with the most votes, which was very fast

    def prime_factors2(n):
        i = 2
        factors = []
        count = 0                           #added to test optimization
        while i * i <= n:
            count += 1                      #added to test optimization
            if n % i:
                i += 1
            else:
                n //= i
                factors.append(i)
        if n > 1:
            factors.append(n)
        return factors, f'count: {count}'   #print with (count added)

TESTING, (note, I added a COUNT in each loop to test the optimization)

# >>> prime_factors2(600851475143)
# ([71, 839, 1471, 6857], 'count: 1472')
# >>> prime_factors(600851475143)
# (600851475143, [71, 839, 1471, 6857], 'count optimization: 494')

I figure this code could be modified easily to get the (largest factor) or whatever else is needed. I'm open to any questions, my goal is to improve this much more as well for larger primes and factors.

Get paragraph text inside an element

If you use eg. "id" you can do it this way:

_x000D_
_x000D_
   (function() {_x000D_
    let x = document.getElementById("idName");_x000D_
    let y = document.getElementById("liName");_x000D_
    _x000D_
    y.addEventListener('click', function(e) {_x000D_
        y.appendChild(x);_x000D_
    });_x000D_
_x000D_
  _x000D_
})();
_x000D_
<html lang="en">_x000D_
_x000D_
<head>_x000D_
    <title></title>_x000D_
    <meta charset="UTF-8">_x000D_
    <meta name="viewport" content="width=device-width, initial-scale=1.0">_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
    <p id="idName">TEXT</p>_x000D_
    <ul>_x000D_
        <li id="liName">_x000D_
_x000D_
        </li>_x000D_
    </ul>_x000D_
</body>_x000D_
<script src="js/scripts/script.js"></script>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

In Bash, how to add "Are you sure [Y/n]" to any command or alias?

This isn't exactly an "asking for yes or no" but just a hack: alias the hg push ... not to hgpushrepo but to hgpushrepoconfirmedpush and by the time I can spell out the whole thing, the left brain has made a logical choice.

Find control by name from Windows Forms controls

TextBox tbx = this.Controls.Find("textBox1", true).FirstOrDefault() as TextBox;
tbx.Text = "found!";

If Controls.Find is not found "textBox1" => error. You must add code.

If(tbx != null)

Edit:

TextBox tbx = this.Controls.Find("textBox1", true).FirstOrDefault() as TextBox;
If(tbx != null)
   tbx.Text = "found!";

Detect rotation of Android phone in the browser with JavaScript

you can try the solution, compatible with all browser.

Following is orientationchange compatibility pic: compatibility therefore, I author a orientaionchange polyfill, it is a based on @media attribute to fix orientationchange utility library——orientationchange-fix

window.addEventListener('orientationchange', function(){
 if(window.neworientation.current === 'portrait|landscape'){
    // do something……
 } else {
    // do something……
 }
}, false);

How to predict input image using trained model in Keras?

Forwarding the example by @ritiek, I'm a beginner in ML too, maybe this kind of formatting will help see the name instead of just class number.

images = np.vstack([x, y])

prediction = model.predict(images)

print(prediction)

i = 1

for things in prediction:  
    if(things == 0):
        print('%d.It is cancer'%(i))
    else:
        print('%d.Not cancer'%(i))
    i = i + 1

How to keep the local file or the remote file during merge using Git and the command line?

You can as well do:

git checkout --theirs /path/to/file

to keep the remote file, and:

git checkout --ours /path/to/file

to keep local file.

Then git add them and everything is done.

Edition: Keep in mind that this is for a merge scenario. During a rebase --theirs refers to the branch where you've been working.

How to develop Desktop Apps using HTML/CSS/JavaScript?

Sorry to burst your bubble but Spotify desktop client is just a Webkit-based browser. Of course it exposes specific additional functionality, but it's only able to run JS and render HTML/CSS because it has a JS engine as well as a Chromium rendering engine. This does not help you with coding a client-side web-app and deploying to multiple platforms.

What you're looking for is similar to Sencha Touch - a framework that allows for HTML5 apps to be natively deployed to iOS, Android and Blackberry devices. It basically acts as an intermediary between certain API calls and device-specific functionality available.

I have no experience with appcelerator, bit it appears to be doing exactly that - and get very favourable reviews online. You should give it a go (unless you wanted to go back to 1999 and roll with MS HTA ;)

EnterKey to press button in VBA Userform

Be sure to avoid "magic numbers" whenever possible, either by defining your own constants, or by using the built-in vbXXX constants.

In this instance we could use vbKeyReturn to indicate the enter key's keycode (replacing YourInputControl and SubToBeCalled).

   Private Sub YourInputControl_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
        If KeyCode = vbKeyReturn Then
             SubToBeCalled
        End If
   End Sub

This prevents a whole category of compatibility issues and simple typos, especially because VBA capitalizes identifiers for us.

Cheers!

DropDownList in MVC 4 with Razor

Here is the easiest answer:

in your view only just add:

@Html.DropDownListFor(model => model.tipo, new SelectList(new[]{"Exemplo1",
"Exemplo2", "Exemplo3"}))

OR in your controller add:

var exemploList= new SelectList(new[] { "Exemplo1:", "Exemplo2", "Exemplo3" });
        ViewBag.ExemploList = exemploList;

and your view just add:

@Html.DropDownListFor(model => model.tipo, (SelectList)ViewBag.ExemploList )

I learned this with Jess Chadwick

How To Inject AuthenticationManager using Java Configuration in a Custom Filter

In addition to what Angular University said above you may want to use @Import to aggregate @Configuration classes to the other class (AuthenticationController in my case) :

@Import(SecurityConfig.class)
@RestController
public class AuthenticationController {
@Autowired
private AuthenticationManager authenticationManager;
//some logic
}

Spring doc about Aggregating @Configuration classes with @Import: link

Using CSS to align a button bottom of the screen using relative positions

<button style="position: absolute; left: 20%; right: 20%; bottom: 5%;"> Button </button>

ASP.NET MVC Html.ValidationSummary(true) does not display model errors

If nearly everything seems right, another thing to look out for is to ensure that the validation summary is not being explicitly hidden via some CSS override like this:

.validation-summary-valid {
    display: none;
}

This may also cause the @Html.ValidationSummary to appear hidden, as the summary is dynamically rendered with the validation-summary-valid class.

PHP json_encode json_decode UTF-8

I had the same problem. It might differ depending on how You put the data to the db, but try what worked for me:

$str = json_encode($data);
$str = addslashes($str);

Do this before saving data to db.

Handle Guzzle exception and get HTTP body

The question was:

I would like to handle errors from Guzzle when the server returns 4xx and 5xx status codes

The other answers are mostly incomplete. 404 and 500 will throw different exceptions.

Also, the question is do you just want to handle the errors or do you want to get the body? I think in most cases it would be sufficient to handle the errors and not get the message body.

I would look at the documentation to check how your version of Guzzle handles it because this may change: https://docs.guzzlephp.org/en/stable/quickstart.html#exceptions

Guzzle 7 (from the docs):

. \RuntimeException
+-- TransferException (implements GuzzleException)
    +-- RequestException
        +-- BadResponseException
        ¦   +-- ServerException
        ¦   +-- ClientException
        +-- ConnectException
        +-- TooManyRedirectsException

So, you code might look like this:

try {
    $response = $client->request('GET', $url);
    if ($response->getStatusCode() >= 300) {
       $statusCode = $response->getStatusCode();
       // handle error 
    } else {
      // is valid URL
    }
            
} catch (TooManyRedirectsException $e) {
    // handle too many redirects
} catch (ClientException | ServerException $e) {
    // ClientException - A GuzzleHttp\Exception\ClientException is thrown for 400 level errors if the http_errors request option is set to true.
    // ServerException - A GuzzleHttp\Exception\ServerException is thrown for 500 level errors if the http_errors request option is set to true.
    if ($e->hasResponse()) {
       $statusCode = $e->getResponse()->getStatusCode();
    }
} catch (ConnectException $e) {
    // ConnectException - A GuzzleHttp\Exception\ConnectException exception is thrown in the event of a networking error. This may be any libcurl error, including certificate problems
    $handlerContext = $e->getHandlerContext();
    if ($handlerContext['errno'] ?? 0) {
       // this is the libcurl error code, not the HTTP status code!!!
       $errno = (int)($handlerContext['errno']);
    }     
} catch (\Exception $e) {
    // fallback, in case of other exception
}

If you really need the body, you can retrieve it as usual:

https://docs.guzzlephp.org/en/stable/quickstart.html#using-responses

$body = $response->getBody();

How can I color dots in a xy scatterplot according to column value?

Try this:

Dim xrndom As Random
    Dim x As Integer
    xrndom = New Random

    Dim yrndom As Random
    Dim y As Integer
    yrndom = New Random
    'chart creation
    Chart1.Series.Add("a")
    Chart1.Series("a").ChartType = DataVisualization.Charting.SeriesChartType.Point
    Chart1.Series("a").MarkerSize = 10
    Chart1.Series.Add("b")
    Chart1.Series("b").ChartType = DataVisualization.Charting.SeriesChartType.Point
    Chart1.Series("b").MarkerSize = 10
    Chart1.Series.Add("c")
    Chart1.Series("c").ChartType = DataVisualization.Charting.SeriesChartType.Point
    Chart1.Series("c").MarkerSize = 10
    Chart1.Series.Add("d")
    Chart1.Series("d").ChartType = DataVisualization.Charting.SeriesChartType.Point
    Chart1.Series("d").MarkerSize = 10
    'color
    Chart1.Series("a").Color = Color.Red
    Chart1.Series("b").Color = Color.Orange
    Chart1.Series("c").Color = Color.Black
    Chart1.Series("d").Color = Color.Green
    Chart1.Series("Chart 1").Color = Color.Blue

    For j = 0 To 70
        x = xrndom.Next(0, 70)
        y = xrndom.Next(0, 70)
        'Conditions
        If j < 10 Then
            Chart1.Series("a").Points.AddXY(x, y)
        ElseIf j < 30 Then
            Chart1.Series("b").Points.AddXY(x, y)
        ElseIf j < 50 Then
            Chart1.Series("c").Points.AddXY(x, y)
        ElseIf 50 < j Then
            Chart1.Series("d").Points.AddXY(x, y)
        Else
            Chart1.Series("Chart 1").Points.AddXY(x, y)
        End If
    Next

How do I install pip on macOS or OS X?

To install or upgrade pip, download get-pip.py from http://www.pip-installer.org/en/latest/installing.html

Then run the following: sudo python get-pip.py

For example:

sudo python Desktop/get-pip.py 
Password:
  Downloading/unpacking pip
  Downloading pip-1.5.2-py2.py3-none-any.whl (1.2MB): 1.2MB downloaded
Installing collected packages: pip
Successfully installed pip
Cleaning up...

sudo pip install pymongo
Password:
Downloading/unpacking pymongo
  Downloading pymongo-2.6.3.tar.gz (324kB): 324kB downloaded
  Running setup.py (path:/private/var/folders/0c/jb79t3bx7cz6h7p71ydhwb_m0000gn/T/pip_build_goker/pymongo/setup.py) egg_info for package pymongo

Installing collected packages: pymongo
...

SLF4J: Class path contains multiple SLF4J bindings

Seems removing .m2 directory and :

mvn install -DskipTests -T 4 resolved this issue for me.

Launch Bootstrap Modal on page load

Just wrap the modal you want to call on page load inside a jQuery load event on the head section of your document and it should popup, like so:

JS

<script type="text/javascript">
    $(window).on('load', function() {
        $('#myModal').modal('show');
    });
</script>

HTML

<div class="modal hide fade" id="myModal">
    <div class="modal-header">
        <a class="close" data-dismiss="modal">×</a>
        <h3>Modal header</h3>
    </div>
    <div class="modal-body">
        <p>One fine body…</p>
    </div>
    <div class="modal-footer">
        <a href="#" class="btn">Close</a>
        <a href="#" class="btn btn-primary">Save changes</a>
    </div>
</div>

You can still call the modal within your page with by calling it with a link like so:

<a class="btn" data-toggle="modal" href="#myModal">Launch Modal</a>

Flatten List in LINQ

iList.SelectMany(x => x).ToArray()

Showing which files have changed between two revisions

If you are using Github / Github Enterprise, you can use the Web UI by hitting the url /compare of your repository path, for instance, https://github.com/http4s/http4s/compare. You can select the branch / commit / tag that you want to compare: Github Compare Screenshot

And the diff will be presented in the github interface at the url /compare/{x1}...{x2} where are x2 and x1 are the branch / commit / tag you want to compare, for instance: https://github.com/http4s/http4s/compare/main...dotty

You can see more in the Github Doc.

Git push results in "Authentication Failed"

I tried the token verification method and got it to work ~3 times and wasted around 2 hours of time for that. For some reason it does not work very well for our company.

My solution was to change the authentication method from HTTPS to SSH. Here is a Github guide (https://help.github.com/en/github/authenticating-to-github/generating-a-new-ssh-key-and-adding-it-to-the-ssh-agent).

After you have created the SSH key, remember to change the SSH address origin:

git remote add origin [email protected]:user/repo.git

Convert string[] to int[] in one line of code using LINQ

EDIT: to convert to array

int[] asIntegers = arr.Select(s => int.Parse(s)).ToArray();

This should do the trick:

var asIntegers = arr.Select(s => int.Parse(s));

jQuery to remove an option from drop down list, given option's text/value

$('#id option').remove();

This will clear the Drop Down list. if you want to clear to select value then $("#id option:selected").remove();

convert strtotime to date time format in php

$unixtime = 1307595105;
echo $time = date("m/d/Y h:i:s A T",$unixtime);

Where

http://php.net/manual/en/function.date.php

How to debug (only) JavaScript in Visual Studio?

Yes you can put the break-point on client side page in Visual studio

First Put the debugger in java-script code and run the page in browser

debugger

enter image description here

After that open your page in browser and view the inspect element you see the following view

enter image description here

Sending POST parameters with Postman doesn't work, but sending GET parameters does

For me, the server was expect HTTPS requests, but I didn't specify that in the URL. The hook would reach the server, but the body would be empty.

How to Specify Eclipse Proxy Authentication Credentials?

If you have still problems, try deactivating ("Clear") SOCKS

see: https://bugs.eclipse.org/bugs/show_bug.cgi?id=281384 "I believe the reason for this is because it uses the SOCKS proxy instead of the HTTP proxy if SOCKS is configured."

jQuery Find and List all LI elements within a UL within a specific DIV

$('li[rel=7]').siblings().andSelf();

// or:

$('li[rel=7]').parent().children();

Now that you added that comment explaining that you want to "form an array of rels per column", you should do this:

var rels = [];

$('ul').each(function() {
    var localRels = [];

    $(this).find('li').each(function(){
        localRels.push( $(this).attr('rel') );
    });

    rels.push(localRels);
});

Iterate through DataSet

foreach (DataTable table in dataSet.Tables)
{
    foreach (DataRow row in table.Rows)
    {
        foreach (object item in row.ItemArray)
        {
            // read item
        }
    }
}

Or, if you need the column info:

foreach (DataTable table in dataSet.Tables)
{
    foreach (DataRow row in table.Rows)
    {
        foreach (DataColumn column in table.Columns)
        {
            object item = row[column];
            // read column and item
        }
    }
}

C++ for each, pulling from vector elements

For next examples assumed that you use C++11. Example with ranged-based for loops:

for (auto &attack : m_attack) // access by reference to avoid copying
{  
    if (attack->m_num == input)
    {
        attack->makeDamage();
    }
}

You should use const auto &attack depending on the behavior of makeDamage().

You can use std::for_each from standard library + lambdas:

std::for_each(m_attack.begin(), m_attack.end(),
        [](Attack * attack)
        {
            if (attack->m_num == input)
            {
                attack->makeDamage();
            }
        }
);

If you are uncomfortable using std::for_each, you can loop over m_attack using iterators:

for (auto attack = m_attack.begin(); attack != m_attack.end(); ++attack)
{  
    if (attack->m_num == input)
    {
        attack->makeDamage();
    }
}

Use m_attack.cbegin() and m_attack.cend() to get const iterators.

Call another rest api from my server in Spring-Boot

Instead of String you are trying to get custom POJO object details as output by calling another API/URI, try the this solution. I hope it will be clear and helpful for how to use RestTemplate also,

In Spring Boot, first we need to create Bean for RestTemplate under the @Configuration annotated class. You can even write a separate class and annotate with @Configuration like below.

@Configuration
public class RestTemplateConfig {

    @Bean
    public RestTemplate restTemplate(RestTemplateBuilder builder) {
       return builder.build();
    }
}

Then, you have to define RestTemplate with @Autowired or @Injected under your service/Controller, whereever you are trying to use RestTemplate. Use the below code,

@Autowired
private RestTemplate restTemplate;

Now, will see the part of how to call another api from my application using above created RestTemplate. For this we can use multiple methods like execute(), getForEntity(), getForObject() and etc. Here I am placing the code with example of execute(). I have even tried other two, I faced problem of converting returned LinkedHashMap into expected POJO object. The below, execute() method solved my problem.

ResponseEntity<List<POJO>> responseEntity = restTemplate.exchange(
    URL, 
    HttpMethod.GET, 
    null, 
    new ParameterizedTypeReference<List<POJO>>() {
    });
List<POJO> pojoObjList = responseEntity.getBody();

Happy Coding :)

Finding local IP addresses using Python's stdlib

If the computer has a route to the Internet, this will always work to get the preferred local ip address, even if /etc/hosts is not set correctly.

import socket

s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(('8.8.8.8', 1))  # connect() for UDP doesn't send packets
local_ip_address = s.getsockname()[0]

How to check if datetime happens to be Saturday or Sunday in SQL Server 2008

This expression

SELECT (((DATEPART(DW, @my_date_var) - 1 ) + @@DATEFIRST ) % 7)

will always return a number between 0 and 6 where

0 -> Sunday
1 -> Monday
2 -> Tuesday
3 -> Wednesday
4 -> Thursday
5 -> Friday
6 -> Saturday

Independently from @@DATEFIRST

So a weekend day is tested like this

SELECT (CASE
           WHEN (((DATEPART(DW, @my_date_var) - 1 ) + @@DATEFIRST ) % 7) IN (0,6)
           THEN 1
           ELSE 0
       END) AS is_weekend_day

OS X Bash, 'watch' command

I had a similar problem.

When I googled, I came across the blog post Install Watch Command on Mac OS X recently. This is not exactly 'installing software', but simply getting the binary for the 'watch' command.

How can I list all tags for a Docker image on a remote registry?

I have done this thing when I have to implement a task in which if user somehow type the wrong tag then we have to give the list of all the tag present in the repo(Docker repo) present in the register. So I have code in batch Script.

<html>
<pre style="background-color:#bcbbbb;">
@echo off

docker login --username=xxxx --password=xxxx
docker pull %1:%2

IF NOT %ERRORLEVEL%==0 (
echo "Specified Version is Not Found "
echo "Available Version for this image is :"
for /f %%i in (' curl -s -H "Content-Type:application/json" -X POST -d "{\"username\":\"user\",\"password\":\"password\"}" https://hub.docker.com/v2/users/login ^|jq -r .token ') do set TOKEN=%%i
curl -sH "Authorization: JWT %TOKEN%" "https://hub.docker.com/v2/repositories/%1/tags/" | jq .results[].name
)
</pre>
</html>

So in this we can give arguments to out batch file like:

Dockerfile java version7 

Eclipse: How to build an executable jar with external jar?

As a good practice you can use an Ant Script (Eclipse comes with it) to generate your JAR file. Inside this JAR you can have all dependent libs.

You can even set the MANIFEST's Class-path header to point to files in your filesystem, it's not a good practice though.

Ant build.xml script example:

<project name="jar with libs" default="compile and build" basedir=".">
<!-- this is used at compile time -->
<path id="example-classpath">
    <pathelement location="${root-dir}" />
    <fileset dir="D:/LIC/xalan-j_2_7_1" includes="*.jar" />
</path>

<target name="compile and build">
    <!-- deletes previously created jar -->
    <delete file="test.jar" />

    <!-- compile your code and drop .class into "bin" directory -->
    <javac srcdir="${basedir}" destdir="bin" debug="true" deprecation="on">
        <!-- this is telling the compiler where are the dependencies -->
        <classpath refid="example-classpath" />
    </javac>

    <!-- copy the JARs that you need to "bin" directory  -->
    <copy todir="bin">
        <fileset dir="D:/LIC/xalan-j_2_7_1" includes="*.jar" />
    </copy>

    <!-- creates your jar with the contents inside "bin" (now with your .class and .jar dependencies) -->
    <jar destfile="test.jar" basedir="bin" duplicate="preserve">
        <manifest>
            <!-- Who is building this jar? -->
            <attribute name="Built-By" value="${user.name}" />
            <!-- Information about the program itself -->
            <attribute name="Implementation-Vendor" value="ACME inc." />
            <attribute name="Implementation-Title" value="GreatProduct" />
            <attribute name="Implementation-Version" value="1.0.0beta2" />
            <!-- this tells which class should run when executing your jar -->
            <attribute name="Main-class" value="ApplyXPath" />
        </manifest>
    </jar>
</target>

jar not loaded. See Servlet Spec 2.3, section 9.7.2. Offending class: javax/servlet/Servlet.class

To fix it, set the scope to provided. This tells Maven use code servlet-api.jar for compiling and testing only, but NOT include it in the WAR file. The deployed container will “provide” the servlet-api.jar at runtime.

<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>servlet-api</artifactId>
    <version>2.5</version>
    <scope>provided</scope>
</dependency>

How to reverse a singly linked list using only two pointers?

Robert Sedgewick, "Algorithms in C", Addison-Wesley, 3rd Edition, 1997, [Section 3.4]

In case that is not a cyclic list ,hence NULL is the last link.

typedef struct node* link;

struct node{ int item; link next; };

/* you send the existing list to reverse() and returns the reversed one */

link reverse(link x){ link t, y = x, r = NULL; while(y != NULL){ t = y->next; y-> next = r; r = y; y = t; } return r; }

How do I change the font size of a UILabel in Swift?

Programmatically

label.font = UIFont.systemFont(ofSize: 20.0)
label.font = UIFont.boldSystemFont(ofSize: 20.0)
label.font = UIFont.italicSystemFont(ofSize: 20.0)

label.font = UIFont(name:"Helvetica Neue", size: 20.0)//Set your font name here

Through Story board

To display multiple lines set 0(Zero), this will display more than one line in your label.

If you want to display only 2 lines set 2.

enter image description here

If you want to set minimum font size for label Click Autoshrink and Select Minimum Font Size option

See below screens

enter image description here

Here set minimum font size

EX: 9 (In this image)

If your label get more text at that time your label text will be shrink upto 9

enter image description here

Filtering DataSet

You can use DataTable.Select:

var strExpr = "CostumerID = 1 AND OrderCount > 2";
var strSort = "OrderCount DESC";

// Use the Select method to find all rows matching the filter.
foundRows = ds.Table[0].Select(strExpr, strSort);  

Or you can use DataView:

ds.Tables[0].DefaultView.RowFilter = strExpr;  

UPDATE I'm not sure why you want to have a DataSet returned. But I'd go with the following solution:

var dv = ds.Tables[0].DefaultView;
dv.RowFilter = strExpr;
var newDS = new DataSet();
var newDT = dv.ToTable();
newDS.Tables.Add(newDT);

Difference between `npm start` & `node app.js`, when starting app?

The documentation has been updated. My answer has substantial changes vs the accepted answer: I wanted to reflect documentation is up-to-date, and accepted answer has a few broken links.

Also, I didn't understand when the accepted answer said "it defaults to node server.js". I think the documentation clarifies the default behavior:

npm-start

Start a package

Synopsis

npm start [-- <args>]

Description

This runs an arbitrary command specified in the package's "start" property of its "scripts" object. If no "start" property is specified on the "scripts" object, it will run node server.js.

In summary, running npm start could do one of two things:

  1. npm start {command_name}: Run an arbitrary command (i.e. if such command is specified in the start property of package.json's scripts object)
  2. npm start: Else if no start property exists (or no command_name is passed): Run node server.js, (which may not be appropriate, for example the OP doesn't have server.js; the OP runs nodeapp.js )
  3. I said I would list only 2 items, but are other possibilities (i.e. error cases). For example, if there is no package.json in the directory where you run npm start, you may see an error: npm ERR! enoent ENOENT: no such file or directory, open '.\package.json'

Iterating over a 2 dimensional python list

>>> mylist = [["%s,%s"%(i,j) for j in range(columns)] for i in range(rows)]
>>> mylist
[['0,0', '0,1', '0,2'], ['1,0', '1,1', '1,2'], ['2,0', '2,1', '2,2']]
>>> zip(*mylist)
[('0,0', '1,0', '2,0'), ('0,1', '1,1', '2,1'), ('0,2', '1,2', '2,2')]
>>> sum(zip(*mylist),())
('0,0', '1,0', '2,0', '0,1', '1,1', '2,1', '0,2', '1,2', '2,2')

How do I set the timeout for a JAX-WS webservice client?

In case your appserver is WebLogic (for me it was 10.3.6) then properties responsible for timeouts are:

com.sun.xml.ws.connect.timeout 
com.sun.xml.ws.request.timeout

How to set dropdown arrow in spinner?

dummy.xml (drawable should be of very less size. i have taken 24dp)

<?xml version="1.0" encoding="utf-8"?>
<layer-list android:opacity="transparent" xmlns:android="http://schemas.android.com/apk/res/android">
            <item android:width="100dp" android:gravity="right" android:start="300dp">
                <bitmap android:src="@drawable/down_button_dummy_dummy" android:gravity="center"/>
            </item>
</layer-list>

layout file snippet

<android.support.v7.widget.CardView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:cardUseCompatPadding="true"
        app:cardElevation="5dp"
        >
     <Spinner
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:background="@drawable/dummy">

     </Spinner>
    </android.support.v7.widget.CardView>

click here to see resultant rendered layout

How can I ping a server port with PHP?

Test different ports:

$wait = 1; // wait Timeout In Seconds
$host = 'example.com';
$ports = [
    'http'  => 80,
    'https' => 443,
    'ftp'   => 21,
];

foreach ($ports as $key => $port) {
    $fp = @fsockopen($host, $port, $errCode, $errStr, $wait);
    echo "Ping $host:$port ($key) ==> ";
    if ($fp) {
        echo 'SUCCESS';
        fclose($fp);
    } else {
        echo "ERROR: $errCode - $errStr";
    }
    echo PHP_EOL;
}


// Ping example.com:80 (http) ==> SUCCESS
// Ping example.com:443 (https) ==> SUCCESS
// Ping example.com:21 (ftp) ==> ERROR: 110 - Connection timed out

Increase number of axis ticks

Additionally,

ggplot(dat, aes(x,y)) +
geom_point() +
scale_x_continuous(breaks = seq(min(dat$x), max(dat$x), by = 0.05))

Works for binned or discrete scaled x-axis data (I.e., rounding not necessary).

How do I add a newline using printf?

Try this:

printf '\n%s\n' 'I want this on a new line!'

That allows you to separate the formatting from the actual text. You can use multiple placeholders and multiple arguments.

quantity=38; price=142.15; description='advanced widget'
$ printf '%8d%10.2f  %s\n' "$quantity" "$price" "$description"
      38    142.15  advanced widget

What exactly does the .join() method do?

join takes an iterable thing as an argument. Usually it's a list. The problem in your case is that a string is itself iterable, giving out each character in turn. Your code breaks down to this:

"wlfgALGbXOahekxSs".join("595")

which acts the same as this:

"wlfgALGbXOahekxSs".join(["5", "9", "5"])

and so produces your string:

"5wlfgALGbXOahekxSs9wlfgALGbXOahekxSs5"

Strings as iterables is one of the most confusing beginning issues with Python.

How do I use properly CASE..WHEN in MySQL

Remove the course_enrollment_settings.base_price immediately after CASE:

SELECT
   CASE
    WHEN course_enrollment_settings.base_price = 0      THEN 1
    ...
    END

CASE has two different forms, as detailed in the manual. Here, you want the second form since you're using search conditions.

datetime dtypes in pandas read_csv

There is a parse_dates parameter for read_csv which allows you to define the names of the columns you want treated as dates or datetimes:

date_cols = ['col1', 'col2']
pd.read_csv(file, sep='\t', header=None, names=headers, parse_dates=date_cols)

print arraylist element?

Do you want to print the entire list or you want to iterate through each element of the list? Either way to print anything meaningful your Dog class need to override the toString() method (as mentioned in other answers) from the Object class to return a valid result.

public class Print {
    public static void main(final String[] args) {
        List<Dog> list = new ArrayList<Dog>();
        Dog e = new Dog("Tommy");
        list.add(e);
        list.add(new Dog("tiger"));
        System.out.println(list);
        for(Dog d:list) {
            System.out.println(d);
            // prints [Tommy, tiger]
        }
    }

    private static class Dog {
        private final String name;
        public Dog(final String name) {
            this.name = name;
        }

        @Override
        public String toString() {
            return name;
        }
    }
}

The output of this code is:

[Tommy, tiger]  
Tommy  
tiger

Angular (4, 5, 6, 7) - Simple example of slide in out animation on ngIf

I answered a very similar question, and here is a way of doing this :

First, create a file where you would define your animations and export them. Just to make it more clear in your app.component.ts

In the following example, I used a max-height of the div that goes from 0px (when it's hidden), to 500px, but you would change that according to what you need.

This animation uses states (in and out), that will be toggle when we click on the button, which will run the animtion.

animations.ts

import { trigger, state, style, transition,
    animate, group, query, stagger, keyframes
} from '@angular/animations';

export const SlideInOutAnimation = [
    trigger('slideInOut', [
        state('in', style({
            'max-height': '500px', 'opacity': '1', 'visibility': 'visible'
        })),
        state('out', style({
            'max-height': '0px', 'opacity': '0', 'visibility': 'hidden'
        })),
        transition('in => out', [group([
            animate('400ms ease-in-out', style({
                'opacity': '0'
            })),
            animate('600ms ease-in-out', style({
                'max-height': '0px'
            })),
            animate('700ms ease-in-out', style({
                'visibility': 'hidden'
            }))
        ]
        )]),
        transition('out => in', [group([
            animate('1ms ease-in-out', style({
                'visibility': 'visible'
            })),
            animate('600ms ease-in-out', style({
                'max-height': '500px'
            })),
            animate('800ms ease-in-out', style({
                'opacity': '1'
            }))
        ]
        )])
    ]),
]

Then in your app.component, we import the animation and create the method that will toggle the animation state.

app.component.ts

import { SlideInOutAnimation } from './animations';

@Component({
  ...
  animations: [SlideInOutAnimation]
})
export class AppComponent  {
  animationState = 'in';

  ...

  toggleShowDiv(divName: string) {
    if (divName === 'divA') {
      console.log(this.animationState);
      this.animationState = this.animationState === 'out' ? 'in' : 'out';
      console.log(this.animationState);
    }
  }
}

And here is how your app.component.html would look like :

<div class="wrapper">
  <button (click)="toggleShowDiv('divA')">TOGGLE DIV</button>
  <div [@slideInOut]="animationState" style="height: 100px; background-color: red;">
  THIS DIV IS ANIMATED</div>
  <div class="content">THIS IS CONTENT DIV</div>
</div>

slideInOut refers to the animation trigger defined in animations.ts

Here is a StackBlitz example I have created : https://angular-muvaqu.stackblitz.io/

Side note : If an error ever occurs and asks you to add BrowserAnimationsModule, just import it in your app.module.ts:

import { BrowserAnimationsModule } from '@angular/platform-browser/animations';

@NgModule({
  imports: [ ..., BrowserAnimationsModule ],
  ...
})

change array size

In case you cannot use Array.Reset (the variable is not local) then Concat & ToArray helps:

anObject.anArray.Concat(new string[] { newArrayItem }).ToArray();

What are the basic rules and idioms for operator overloading?

The General Syntax of operator overloading in C++

You cannot change the meaning of operators for built-in types in C++, operators can only be overloaded for user-defined types1. That is, at least one of the operands has to be of a user-defined type. As with other overloaded functions, operators can be overloaded for a certain set of parameters only once.

Not all operators can be overloaded in C++. Among the operators that cannot be overloaded are: . :: sizeof typeid .* and the only ternary operator in C++, ?:

Among the operators that can be overloaded in C++ are these:

  • arithmetic operators: + - * / % and += -= *= /= %= (all binary infix); + - (unary prefix); ++ -- (unary prefix and postfix)
  • bit manipulation: & | ^ << >> and &= |= ^= <<= >>= (all binary infix); ~ (unary prefix)
  • boolean algebra: == != < > <= >= || && (all binary infix); ! (unary prefix)
  • memory management: new new[] delete delete[]
  • implicit conversion operators
  • miscellany: = [] -> ->* , (all binary infix); * & (all unary prefix) () (function call, n-ary infix)

However, the fact that you can overload all of these does not mean you should do so. See the basic rules of operator overloading.

In C++, operators are overloaded in the form of functions with special names. As with other functions, overloaded operators can generally be implemented either as a member function of their left operand's type or as non-member functions. Whether you are free to choose or bound to use either one depends on several criteria.2 A unary operator @3, applied to an object x, is invoked either as operator@(x) or as x.operator@(). A binary infix operator @, applied to the objects x and y, is called either as operator@(x,y) or as x.operator@(y).4

Operators that are implemented as non-member functions are sometimes friend of their operand’s type.

1 The term “user-defined” might be slightly misleading. C++ makes the distinction between built-in types and user-defined types. To the former belong for example int, char, and double; to the latter belong all struct, class, union, and enum types, including those from the standard library, even though they are not, as such, defined by users.

2 This is covered in a later part of this FAQ.

3 The @ is not a valid operator in C++ which is why I use it as a placeholder.

4 The only ternary operator in C++ cannot be overloaded and the only n-ary operator must always be implemented as a member function.


Continue to The Three Basic Rules of Operator Overloading in C++.

SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: YES) symfony2

Countercheck if boostrap/cache/config.php database details are correct. That should give you an hint if they are.

If they are not, then you need to clear the cache using the following steps :

  1. rm -fr bootstrap/cache/*
  2. php artisan optimize

How to declare local variables in postgresql?

Postgresql historically doesn't support procedural code at the command level - only within functions. However, in Postgresql 9, support has been added to execute an inline code block that effectively supports something like this, although the syntax is perhaps a bit odd, and there are many restrictions compared to what you can do with SQL Server. Notably, the inline code block can't return a result set, so can't be used for what you outline above.

In general, if you want to write some procedural code and have it return a result, you need to put it inside a function. For example:

CREATE OR REPLACE FUNCTION somefuncname() RETURNS int LANGUAGE plpgsql AS $$
DECLARE
  one int;
  two int;
BEGIN
  one := 1;
  two := 2;
  RETURN one + two;
END
$$;
SELECT somefuncname();

The PostgreSQL wire protocol doesn't, as far as I know, allow for things like a command returning multiple result sets. So you can't simply map T-SQL batches or stored procedures to PostgreSQL functions.

What is the Java equivalent for LINQ?

There is no such feature in java. By using the other API you will get this feature. Like suppose we have a animal Object containing name and id. We have list object having animal objects. Now if we want to get the all the animal name which contains 'o' from list object. we can write the following query

from(animals).where("getName", contains("o")).all();

Above Query statement will list of the animals which contains 'o' alphabet in their name. More information please go through following blog. http://javaworldwide.blogspot.in/2012/09/linq-in-java.html

Python csv string to array

Use this to have a csv loaded into a list

import csv

csvfile = open(myfile, 'r')
reader = csv.reader(csvfile, delimiter='\t')
my_list = list(reader)
print my_list
>>>[['1st_line', '0'],
    ['2nd_line', '0']]

How do JavaScript closures work?

A function is executed in the scope of the object/function in which it is defined. The said function can access the variables defined in the object/function where it has been defined while it is executing.

And just take it literally.... as the code is written :P

How to redirect to another page in node.js

The If else statement needs to be wrapped in a .get or a .post to redirect. Such as

app.post('/login', function(req, res) {
});

or

app.get('/login', function(req, res) {
});

How to get number of entries in a Lua table?

There's one way, but it might be disappointing: use an additional variable (or one of the table's field) for storing the count, and increase it every time you make an insertion.

count = 0
tbl = {}

tbl["test"] = 47
count = count + 1

tbl[1] = 48
count = count + 1

print(count)   -- prints "2"

There's no other way, the # operator will only work on array-like tables with consecutive keys.

How to request Administrator access inside a batch file

@echo off 
Net session >nul 2>&1 || (PowerShell start -verb runas '%~0' &exit /b)
Echo Administrative privileges have been got. & pause

The above works on my Windows 10 Version 1903

How do I erase an element from std::vector<> by index?

here is one more way to do this if you want to delete a element by finding this with its value in vector,you just need to do this on vector.

vector<int> ar(n);
ar.erase(remove(ar.begin(), ar.end()), (place your value here from vector array));

it will remove your value from here. thanks

How do I empty an input value with jQuery?

$('.reset').on('click',function(){
           $('#upload input, #upload select').each(
                function(index){  
                    var input = $(this);
                    if(input.attr('type')=='text'){
                        document.getElementById(input.attr('id')).value = null;
                    }else if(input.attr('type')=='checkbox'){
                        document.getElementById(input.attr('id')).checked = false;
                    }else if(input.attr('type')=='radio'){
                        document.getElementById(input.attr('id')).checked = false;
                    }else{
                        document.getElementById(input.attr('id')).value = '';
                        //alert('Type: ' + input.attr('type') + ' -Name: ' + input.attr('name') + ' -Value: ' + input.val());
                    }
                }
            );
        });

How can I compare a date and a datetime in Python?

Here is another take, "stolen" from a comment at can't compare datetime.datetime to datetime.date ... convert the date to a datetime using this construct:

datetime.datetime(d.year, d.month, d.day)

Suggestion:

from datetime import datetime

def ensure_datetime(d):
    """
    Takes a date or a datetime as input, outputs a datetime
    """
    if isinstance(d, datetime):
        return d
    return datetime.datetime(d.year, d.month, d.day)

def datetime_cmp(d1, d2):
    """
    Compares two timestamps.  Tolerates dates.
    """
    return cmp(ensure_datetime(d1), ensure_datetime(d2))

Iterate through string array in Java

String[] elements = { "a", "a","a","a" };

for( int i=0; i<elements.length-1; i++)
{
    String s1 = elements[i];
    String s2 = elements[i+1];
}

Convert/cast an stdClass object to another class

consider adding a new method to BusinessClass:

public static function fromStdClass(\stdClass $in): BusinessClass
{
  $out                   = new self();
  $reflection_object     = new \ReflectionObject($in);
  $reflection_properties = $reflection_object->getProperties();
  foreach ($reflection_properties as $reflection_property)
  {
    $name = $reflection_property->getName();
    if (property_exists('BusinessClass', $name))
    {
      $out->{$name} = $in->$name;
    }
  }
  return $out;
}

then you can make a new BusinessClass from $stdClass:

$converted = BusinessClass::fromStdClass($stdClass);

CSS force new line

Use the display property

a{
    display: block;
}

This will make the link to display in new line

If you want to remove list styling, use

li{
    list-style: none;
}

ECMAScript 6 arrow function that returns an object

You must wrap the returning object literal into parentheses. Otherwise curly braces will be considered to denote the function’s body. The following works:

p => ({ foo: 'bar' });

You don't need to wrap any other expression into parentheses:

p => 10;
p => 'foo';
p => true;
p => [1,2,3];
p => null;
p => /^foo$/;

and so on.

Reference: MDN - Returning object literals

Signtool error: No certificates were found that met all given criteria with a Windows Store App?

The criteria include account name (whose private key it is associated with), domain, company, expiration date, intended purposes, among other things.

There are many different possible reasons for this error to occur, some have been listed already. Here is another tip: When importing a certificate, be sure you work with the original file received from the certificate authority (CA), or else some of the properties might be lost.

Example: recently I tried to import a certificate exported from a different account on the same machine. The certificate became visible to my account but was not associated with my account, and as a result signtool refused to recognize it without explicitly providing the file name and a password. Which, when done as part of the build process and written out explicitly in a batch file or source file, may not be sufficiently secure. (Importing the original CA-issued certificate solved it.)

Deleting records before a certain date

This is another example using defined column/table names.

DELETE FROM jos_jomres_gdpr_optins WHERE `date_time` < '2020-10-21 08:21:22';

Undefined columns selected when subsetting data frame

You want rows where that condition is true so you need a comma:

data[data$Ozone > 14, ]

How to force composer to reinstall a library?

For some reason no one suggested the obvious and the most straight forward way to force re-install:

> composer remove vendor-name/package-name && composer vendor-name/package-name

How do I count the number of occurrences of a char in a String?

In case you're using Spring framework, you might also use "StringUtils" class. The method would be "countOccurrencesOf".

Setting TIME_WAIT TCP

setting the tcp_reuse is more useful than changing time_wait, as long as you have the parameter (kernels 3.2 and above, unfortunately that disqualifies all versions of RHEL and XenServer).

Dropping the value, particularly for VPN connected users, can result in constant recreation of proxy tunnels on the outbound connection. With the default Netscaler (XenServer) config, which is lower than the default Linux config, Chrome will sometimes have to recreate the proxy tunnel up to a dozen times to retrieve one web page. Applications that don't retry, such as Maven and Eclipse P2, simply fail.

The original motive for the parameter (avoid duplication) was made redundant by a TCP RFC that specifies timestamp inclusion on all TCP requests.

Which type of folder structure should be used with Angular 2?

So after doing more investigating I ended up going with a slightly revised version of Method 3 (mgechev/angular2-seed).

I basically moved components to be a main level directory and then each feature will be inside of it.

Can "list_display" in a Django ModelAdmin display attributes of ForeignKey fields?

AlexRobbins' answer worked for me, except that the first two lines need to be in the model (perhaps this was assumed?), and should reference self:

def book_author(self):
  return self.book.author

Then the admin part works nicely.

Android - Launcher Icon Size

Don't Create 9-patch images for launcher icons . You have to make separate image for each one.

LDPI - 36 x 36
MDPI - 48 x 48
HDPI - 72 x 72
XHDPI - 96 x 96
XXHDPI - 144 x 144
XXXHDPI - 192 x 192.
WEB - 512 x 512 (Require when upload application on Google Play)

Note: WEB(512 x 512) image is used when you upload your android application on Market.

|| Android App Icon Size ||

All Devices

hdpi=281*164
mdpi=188*110
xhdpi=375*219
xxhdpi=563*329
xxxhdpi=750*438

48 × 48 (mdpi)
72 × 72 (hdpi)
96 × 96 (xhdpi)
144 × 144 (xxhdpi)
192 × 192 (xxxhdpi)
512 × 512 (Google Play store)

Reading a UTF8 CSV file with Python

Worth noting that if nothing worked for you, you may have forgotten to escape your path.
For example, this code:

f = open("C:\Some\Path\To\file.csv")

Would result in an error:

SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape

To fix, simply do:

f = open("C:\\Some\\Path\\To\\file.csv")

Windows XP or later Windows: How can I run a batch file in the background with no window displayed?

Do you need the second batch file to run asynchronously? Typically one batch file runs another synchronously with the call command, and the second one would share the first one's window.

You can use start /b second.bat to launch a second batch file asynchronously from your first that shares your first one's window. If both batch files write to the console simultaneously, the output will be overlapped and probably indecipherable. Also, you'll want to put an exit command at the end of your second batch file, or you'll be within a second cmd shell once everything is done.

Checking if form has been submitted - PHP

Actually, the submit button already performs this function.

Try in the FORM:

<form method="post">
<input type="submit" name="treasure" value="go!">
</form>

Then in the PHP handler:

if (isset($_POST['treasure'])){
echo "treasure will be set if the form has been submitted (to TRUE, I believe)";
}

Java serialization - java.io.InvalidClassException local class incompatible

@DanielChapman gives a good explanation of serialVersionUID, but no solution. the solution is this: run the serialver program on all your old classes. put these serialVersionUID values in your current versions of the classes. as long as the current classes are serial compatible with the old versions, you should be fine. (note for future code: you should always have a serialVersionUID on all Serializable classes)

if the new versions are not serial compatible, then you need to do some magic with a custom readObject implementation (you would only need a custom writeObject if you were trying to write new class data which would be compatible with old code). generally speaking adding or removing class fields does not make a class serial incompatible. changing the type of existing fields usually will.

Of course, even if the new class is serial compatible, you may still want a custom readObject implementation. you may want this if you want to fill in any new fields which are missing from data saved from old versions of the class (e.g. you have a new List field which you want to initialize to an empty list when loading old class data).

Linking a qtDesigner .ui file to python/pyqt?

The cleaner way in my opinion is to first export to .py as aforementioned:

pyuic4 foo.ui > foo.py

And then use it inside your code (e.g main.py), like:

from foo import Ui_MyWindow


class MyWindow(QtGui.QDialog):
    def __init__(self):
        super(MyWindow, self).__init__()

        self.ui = Ui_MyWindow()
        self.ui.setupUi(self)

        # go on setting up your handlers like:
        # self.ui.okButton.clicked.connect(function_name)
        # etc...

def main():
    app = QtGui.QApplication(sys.argv)
    w = MyWindow()
    w.show()
    sys.exit(app.exec_())

if __name__ == "__main__":
    main()

This way gives the ability to other people who don't use qt-designer to read the code, and also keeps your functionality code outside foo.py that could be overwritten by designer. You just reference ui through MyWindow class as seen above.

MySQL skip first 10 results

select * from table where id not in (select id from table limit 10)

where id be the key in your table.

setState(...): Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component. This is a no-op

removeEventListener has the same signature as addEventListener. All of the arguments must be exactly the same for it to remove the listener.

var onEnded = () => {};
audioNode.addEventListener('ended', onEnded, false);

this.cleanup = () => {
  audioNode.removeEventListener('ended', onEnded, false);
}

And in componentWillUnmount call this.cleanup().

Remove a data connection from an Excel 2010 spreadsheet in compatibility mode

Select a cell in the cell range in which the data is imported, then Menu > Data > Properties > uncheck save query definition.

Properties will be greyed out unless a cell in the data import range is selected.

You can find out the range in which the data isimported by:

Menu > Data > Connections > (select connection) > Click here to see where the selected connections are used.

YouTube Video Embedded via iframe Ignoring z-index?

Joshc's answer was on the right track, but I found that it totally deletes the ?rel=0 querystring and replaces it with the ?wmode=transparent item - which has the effect of displaying the YouTube Suggested Videos list at the end of the playback, even though you originally didn't want this to happen.

I changed the code so that the src attribute of the embedded video is scanned first, to see if there is a question mark ? in it already (because this denotes the presence of a pre-existing query string, which might be something like ?rel=0 but could in theory be anything that YouTube choose to append in the future). If there's a query string already there, we want to preserve it, not destroy it, because it represents a setting chosen by whoever pasted in this YouTube video, and they presumably chose it for a reason!

So, if ? is found, the wmode=transparent will be appended using the format: &mode=transparent to just tag it on the end of the pre-existing query string.

If no ? is found, then the code will work in exactly the same way as it did originally (in toomanyairmiles's post), appending just ?wmode=transparent as a new query string to the URL.

Now, regardless of what may or may not be on the end of the YouTube URL as a query string already, it gets preserved, and the required wmode parameters get injected or added without damage to what was there before.

Here's the code to drop into your document.ready function:

$('iframe').each(function() {
  var url = $(this).attr("src");
  if (url.indexOf("?") > 0) {
    $(this).attr({
      "src" : url + "&wmode=transparent",
      "wmode" : "opaque"
    });
  }
  else {
    $(this).attr({
      "src" : url + "?wmode=transparent",
      "wmode" : "opaque"
    });
  }
});

WCF Exception: Could not find a base address that matches scheme http for the endpoint

Your configuration should look similar to that. You may have to change <transport clientCredentialType="None" proxyCredentialType="None" /> depending on your needs for authentication. The config below doesn't require any authentication.

<bindings>
    <basicHttpBinding>
        <binding name="basicHttpBindingConfiguration">
            <security mode="Transport">
                <transport clientCredentialType="None" proxyCredentialType="None" />
            </security>
        </binding>       
    </basicHttpBinding>
</bindings>

<services>
    <service name="XXX">
        <endpoint
            name="AAA"
            address=""
            binding="basicHttpBinding"
            bindingConfiguration="basicHttpBindingConfiguration"
            contract="YourContract" />
    </service>
<services>

That will allow a WCF service with basicHttpBinding to use HTTPS.

Android Studio Run/Debug configuration error: Module not specified

I would like to add some more information while I was facing this issue:

Ref: Answer from @Eli:

  1. Cut line include ':app' from the file.
  2. On Android Studio, click on the File Menu, and select Sync Project with Gradle files.
  3. After synchronisation, paste back line include ':app' to the settings.gradle file.
  4. Re-run Sync Project with Gradle files again.

So, let's follow the instruction and try to keep one thing in mind, that what is showing in your build configuration. Make sure you are seeing the name of your configuration app like the image below:

enter image description here

If you are seeing anything else, then the steps mentioned by @Eli (the most accepted answer) will not work.

An alternative Solution If you have a different name on the Run/Debug Configurations window and the above process is not working, please change the config name to 'app'

then -> hit Apply -> then Ok.

After that follow this:-

File->Sync project with gradle files (if needed).

Now check the issue will be resolved hopefully. I have faced this issue and I think it might help others as well.

Command output redirect to file and terminal

It is worth mentioning that 2>&1 means that standard error will be redirected too, together with standard output. So

someCommand | tee someFile

gives you just the standard output in the file, but not the standard error: standard error will appear in console only. To get standard error in the file too, you can use

someCommand 2>&1 | tee someFile

(source: In the shell, what is " 2>&1 "? ). Finally, both the above commands will truncate the file and start clear. If you use a sequence of commands, you may want to get output&error of all of them, one after another. In this case you can use -a flag to "tee" command:

someCommand 2>&1 | tee -a someFile

How do I format a number with commas in T-SQL?

For SQL Server 2012+ implementations, you will have the ability to use the FORMAT to apply string formatting to non-string data types.

In the original question, the user had requested the ability to use commas as thousands separators. In a closed as duplicate question, the user had asked how they could apply currency formatting. The following query shows how to perform both tasks. It also demonstrates the application of culture to make this a more generic solution (addressing Tsiridis Dimitris's function to apply Greek special formatting)

-- FORMAT
-- http://msdn.microsoft.com/en-us/library/hh213505(v=sql.110).aspx
-- FORMAT does not do conversion, that's the domain of cast/convert/parse etc
-- Only accepts numeric and date/time data types for formatting. 
--
-- Formatting Types
-- http://msdn.microsoft.com/en-us/library/26etazsy.aspx

-- Standard numeric format strings
-- http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx
SELECT
    -- c => currency
    -- n => numeric
    FORMAT(987654321, N'N', C.culture) AS some_number
,   FORMAT(987654321, N'c', C.culture) AS some_currency
,   C.culture
FROM
    (
        -- Language culture names
        -- http://msdn.microsoft.com/en-us/library/ee825488(v=cs.20).aspx
        VALUES
            ('en-US')
        ,   ('en-GB')
        ,   ('ja-JP')
        ,   ('Ro-RO')
        ,   ('el-GR')
    ) C (culture);

SQLFiddle for the above

Understanding the Rails Authenticity Token

Minimal attack example that would be prevented: CSRF

On my website evil.com I convince you to submit the following form:

<form action="http://bank.com/transfer" method="post">
  <p><input type="hidden" name="to"      value="ciro"></p>
  <p><input type="hidden" name="ammount" value="100"></p>
  <p><button type="submit">CLICK TO GET PRIZE!!!</button></p>
</form>

If you are logged into your bank through session cookies, then the cookies would be sent and the transfer would be made without you even knowing it.

That is were the CSRF token comes into play:

  • with the GET response that that returned the form, Rails sends a very long random hidden parameter
  • when the browser makes the POST request, it will send the parameter along, and the server will only accept it if it matches

So the form on an authentic browser would look like:

<form action="http://bank.com/transfer" method="post">
  <p><input type="hidden" name="authenticity_token" value="j/DcoJ2VZvr7vdf8CHKsvjdlDbmiizaOb5B8DMALg6s=" ></p>
  <p><input type="hidden" name="to"                 value="ciro"></p>
  <p><input type="hidden" name="ammount"            value="100"></p>
  <p><button type="submit">Send 100$ to Ciro.</button></p>
</form>

Thus, my attack would fail, since it was not sending the authenticity_token parameter, and there is no way I could have guessed it since it is a huge random number.

This prevention technique is called Synchronizer Token Pattern.

Same Origin Policy

But what if the attacker made two requests with JavaScript, one to read the token, and the second one to make the transfer?

The synchronizer token pattern alone is not enough to prevent that!

This is where the Same Origin Policy comes to the rescue, as I have explained at: https://security.stackexchange.com/questions/8264/why-is-the-same-origin-policy-so-important/72569#72569

How Rails sends the tokens

Covered at: Rails: How Does csrf_meta_tag Work?

Basically:

  • HTML helpers like form_tag add a hidden field to the form for you if it's not a GET form

  • AJAX is dealt with automatically by jquery-ujs, which reads the token from the meta elements added to your header by csrf_meta_tags (present in the default template), and adds it to any request made.

    uJS also tries to update the token in forms in outdated cached fragments.

Other prevention approaches

How to find which version of TensorFlow is installed in my system?

python -c 'import tensorflow as tf; print(tf.__version__)'  # for Python 2
python3 -c 'import tensorflow as tf; print(tf.__version__)'  # for Python 3

Here -c represents program passed in as string (terminates option list)

Measuring the distance between two coordinates in PHP

Here the simple and perfect code for calculating the distance between two latitude and longitude. The following code have been found from here - http://www.codexworld.com/distance-between-two-addresses-google-maps-api-php/

$latitudeFrom = '22.574864';
$longitudeFrom = '88.437915';

$latitudeTo = '22.568662';
$longitudeTo = '88.431918';

//Calculate distance from latitude and longitude
$theta = $longitudeFrom - $longitudeTo;
$dist = sin(deg2rad($latitudeFrom)) * sin(deg2rad($latitudeTo)) +  cos(deg2rad($latitudeFrom)) * cos(deg2rad($latitudeTo)) * cos(deg2rad($theta));
$dist = acos($dist);
$dist = rad2deg($dist);
$miles = $dist * 60 * 1.1515;

$distance = ($miles * 1.609344).' km';

How does C compute sin() and other math functions?

If you want an implementation in software, not hardware, the place to look for a definitive answer to this question is Chapter 5 of Numerical Recipes. My copy is in a box, so I can't give details, but the short version (if I remember this right) is that you take tan(theta/2) as your primitive operation and compute the others from there. The computation is done with a series approximation, but it's something that converges much more quickly than a Taylor series.

Sorry I can't rembember more without getting my hand on the book.

Cannot deserialize instance of object out of START_ARRAY token in Spring Webservice

I've had a very similar issue using spring-boot-starter-data-redis. To my implementation there was offered a @Bean for RedisTemplate as follows:

@Bean
public RedisTemplate<String, List<RoutePlantCache>> redisTemplate(RedisConnectionFactory connectionFactory) {
    final RedisTemplate<String, List<RoutePlantCache>> template = new RedisTemplate<>();
    template.setConnectionFactory(connectionFactory);
    template.setKeySerializer(new StringRedisSerializer());
    template.setValueSerializer(new Jackson2JsonRedisSerializer<>(RoutePlantCache.class));

    // Add some specific configuration here. Key serializers, etc.
    return template;
}

The fix was to specify an array of RoutePlantCache as following:

template.setValueSerializer(new Jackson2JsonRedisSerializer<>(RoutePlantCache[].class));

Below the exception I had:

com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `[...].RoutePlantCache` out of START_ARRAY token
 at [Source: (byte[])"[{ ... },{ ... [truncated 1478 bytes]; line: 1, column: 1]
    at com.fasterxml.jackson.databind.exc.MismatchedInputException.from(MismatchedInputException.java:59) ~[jackson-databind-2.11.4.jar:2.11.4]
    at com.fasterxml.jackson.databind.DeserializationContext.reportInputMismatch(DeserializationContext.java:1468) ~[jackson-databind-2.11.4.jar:2.11.4]
    at com.fasterxml.jackson.databind.DeserializationContext.handleUnexpectedToken(DeserializationContext.java:1242) ~[jackson-databind-2.11.4.jar:2.11.4]
    at com.fasterxml.jackson.databind.DeserializationContext.handleUnexpectedToken(DeserializationContext.java:1190) ~[jackson-databind-2.11.4.jar:2.11.4]
    at com.fasterxml.jackson.databind.deser.BeanDeserializer._deserializeFromArray(BeanDeserializer.java:604) ~[jackson-databind-2.11.4.jar:2.11.4]
    at com.fasterxml.jackson.databind.deser.BeanDeserializer._deserializeOther(BeanDeserializer.java:190) ~[jackson-databind-2.11.4.jar:2.11.4]
    at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:166) ~[jackson-databind-2.11.4.jar:2.11.4]
    at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:4526) ~[jackson-databind-2.11.4.jar:2.11.4]
    at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3572) ~[jackson-databind-2.11.4.jar:2.11.4]

Find column whose name contains a specific string

Getting name and subsetting based on Start, Contains, and Ends:

# from: https://stackoverflow.com/questions/21285380/find-column-whose-name-contains-a-specific-string
# from: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.contains.html
# from: https://cmdlinetips.com/2019/04/how-to-select-columns-using-prefix-suffix-of-column-names-in-pandas/
# from: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.filter.html




import pandas as pd



data = {'spike_starts': [1,2,3], 'ends_spike_starts': [4,5,6], 'ends_spike': [7,8,9], 'not': [10,11,12]}
df = pd.DataFrame(data)



print("\n")
print("----------------------------------------")
colNames_contains = df.columns[df.columns.str.contains(pat = 'spike')].tolist() 
print("Contains")
print(colNames_contains)



print("\n")
print("----------------------------------------")
colNames_starts = df.columns[df.columns.str.contains(pat = '^spike')].tolist() 
print("Starts")
print(colNames_starts)



print("\n")
print("----------------------------------------")
colNames_ends = df.columns[df.columns.str.contains(pat = 'spike$')].tolist() 
print("Ends")
print(colNames_ends)



print("\n")
print("----------------------------------------")
df_subset_start = df.filter(regex='^spike',axis=1)
print("Starts")
print(df_subset_start)



print("\n")
print("----------------------------------------")
df_subset_contains = df.filter(regex='spike',axis=1)
print("Contains")
print(df_subset_contains)



print("\n")
print("----------------------------------------")
df_subset_ends = df.filter(regex='spike$',axis=1)
print("Ends")
print(df_subset_ends)

NULL value for int in Update statement

If this is nullable int field then yes.

update TableName
set FiledName = null
where Id = SomeId

How to find if an array contains a string

Another simple way using JOIN and INSTR

Sub Sample()
    Dim Mainfram(4) As String, strg As String
    Dim cel As Range
    Dim Delim As String

    Delim = "#"

    Mainfram(0) = "apple"
    Mainfram(1) = "pear"
    Mainfram(2) = "orange"
    Mainfram(3) = "fruit"

    strg = Join(Mainfram, Delim)
    strg = Delim & strg

    For Each cel In Selection
        If InStr(1, strg, Delim & cel.Value & Delim, vbTextCompare) Then _
        Rows(cel.Row).Style = "Accent1"
    Next cel
End Sub

What is the difference between cache and persist?

For impatient:

Same

Without passing argument, persist() and cache() are the same, with default settings:

  • when RDD: MEMORY_ONLY
  • when Dataset: MEMORY_AND_DISK

Difference:

Unlike cache(), persist() allows you to pass argument inside the bracket, in order to specify the level:

  • persist(MEMORY_ONLY)
  • persist(MEMORY_ONLY_SER)
  • persist(MEMORY_AND_DISK)
  • persist(MEMORY_AND_DISK_SER )
  • persist(DISK_ONLY )

Voilà!

Format numbers in thousands (K) in Excel

Non-Americans take note! If you use Excel with "." as 1000 separator, you need to replace the "," with a "." in the formula, such as:

[>=1000]€ #.##0." K";[<=-1000]-€ #.##0." K";0

The code above will display € 62.123 as "€ 62 K".

Date query with ISODate in mongodb doesn't seem to work

In json strict mode, you'll have to keep the order:

{
    "dt": {
        "$gte": {
            "$date": "2013-10-01T00:00:00.000Z"
        }
    }
}

Only thing which worked to define my search queries on mlab.com.

How to hide status bar in Android

Add this to your Activity class

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    this.getWindow().setFlags(
                        WindowManager.LayoutParams.FLAG_FULLSCREEN, 
                        WindowManager.LayoutParams.FLAG_FULLSCREEN);
    setContentView(R.layout.activity_main);
    // some your code
}

How to use the CSV MIME-type?

You could try to force the browser to open a "Save As..." dialog by doing something like:

header('Content-type: text/csv');
header('Content-disposition: attachment;filename=MyVerySpecial.csv');
echo "cell 1, cell 2";

Which should work across most major browsers.

Play a Sound with Python

Definitely use Pyglet for this. It's kind of a large package, but it is pure python with no extension modules. That will definitely be the easiest for deployment. It's also got great format and codec support.

import pyglet

music = pyglet.resource.media('music.mp3')
music.play()

pyglet.app.run()

Focus Next Element In Tab Index

This is a potential enhancement to the great solution that @Kano and @Mx offered. If you want to preserve TabIndex ordering, add this sort in the middle:

// Sort by explicit Tab Index, if any
var sort_by_TabIndex = function (elementA, elementB) {
    let a = elementA.tabIndex || 1;
    let b = elementB.tabIndex || 1;
    if (a < b) { return -1; }
    if (a > b) { return 1; }
    return 0;
}
focussable.sort(sort_by_TabIndex);

JAVA_HOME should point to a JDK not a JRE

I met the same problem. (Window 10 environment) I solved it by deleting the JAVA_HOME="C:\Program Files\Java\jdk1.8.0_161\bin" in the User Variables instead of adding to the System Variables directly.

Then I test that editing JAVA_HOME="C:\Program Files\Java\jdk1.8.0_161\" worked too. When I run "mvn -version" in command prompt window, it shows "Java home: C:\Program Files\Java\jdk1.8.0_161\jre".

In conclusion, I guess the JAVA_HOME shouldn't include bin directory.

Python strip() multiple characters?

I did a time test here, using each method 100000 times in a loop. The results surprised me. (The results still surprise me after editing them in response to valid criticism in the comments.)

Here's the script:

import timeit

bad_chars = '(){}<>'

setup = """import re
import string
s = 'Barack (of Washington)'
bad_chars = '(){}<>'
rgx = re.compile('[%s]' % bad_chars)"""

timer = timeit.Timer('o = "".join(c for c in s if c not in bad_chars)', setup=setup)
print "List comprehension: ",  timer.timeit(100000)


timer = timeit.Timer("o= rgx.sub('', s)", setup=setup)
print "Regular expression: ", timer.timeit(100000)

timer = timeit.Timer('for c in bad_chars: s = s.replace(c, "")', setup=setup)
print "Replace in loop: ", timer.timeit(100000)

timer = timeit.Timer('s.translate(string.maketrans("", "", ), bad_chars)', setup=setup)
print "string.translate: ", timer.timeit(100000)

Here are the results:

List comprehension:  0.631745100021
Regular expression:  0.155561923981
Replace in loop:  0.235936164856
string.translate:  0.0965719223022

Results on other runs follow a similar pattern. If speed is not the primary concern, however, I still think string.translate is not the most readable; the other three are more obvious, though slower to varying degrees.

org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':app:transformClassesWithDexForDebug'

My Simple Answer is and only solution...

Please Check The layout files, which you added lastly there MUST be a error in the .xml file for sure.

We may simply copy and pasting .xml file from other project and something missing in the xml file..

Error in the .xml file would be some of the below....

  1. Something missing in Drawable folder or String.xml Or Dimen.xml...

After Placing all the available code in the respected folders do not forget to CLEAN The Project...

POST data in JSON format

Another example is available here:

Sending a JSON to server and retrieving a JSON in return, without JQuery

Which is the same as jans answer, but also checks the servers response by setting a onreadystatechange callback on the XMLHttpRequest.

Removing padding gutter from grid columns in Bootstrap 4

You should use built-in bootstrap4 spacing classes for customizing the spacing of elements, that's more convenient method .

How to remove item from list in C#?

{
    class Program
    {
        public static List<Product> list;
        static void Main(string[] args)
        {

            list = new List<Product>() { new Product() { ProductId=1, Name="Nike 12N0",Brand="Nike",Price=12000,Quantity=50},
                 new Product() { ProductId =2, Name = "Puma 560K", Brand = "Puma", Price = 120000, Quantity = 55 },
                 new Product() { ProductId=3, Name="WoodLand V2",Brand="WoodLand",Price=21020,Quantity=25},
                 new Product() { ProductId=4, Name="Adidas S52",Brand="Adidas",Price=20000,Quantity=35},
                 new Product() { ProductId=5, Name="Rebook SPEED2O",Brand="Rebook",Price=1200,Quantity=15}};


            Console.WriteLine("Enter ProductID to remove");
            int uno = Convert.ToInt32(Console.ReadLine());
            var itemToRemove = list.Find(r => r.ProductId == uno);
            if (itemToRemove != null)
                list.Remove(itemToRemove);
            Console.WriteLine($"{itemToRemove.ProductId}{itemToRemove.Name}{itemToRemove.Brand}{itemToRemove.Price}{ itemToRemove.Quantity}");
            Console.WriteLine("------------sucessfully Removed---------------");

            var query2 = from x in list select x;
            foreach (var item in query2)
            {
                /*Console.WriteLine(item.ProductId+" "+item.Name+" "+item.Brand+" "+item.Price+" "+item.Quantity );*/
                Console.WriteLine($"{item.ProductId}{item.Name}{item.Brand}{item.Price}{ item.Quantity}");
            }

        }

    }
}

Django: Get list of model fields?

I find adding this to django models quite helpful:

def __iter__(self):
    for field_name in self._meta.get_all_field_names():
        value = getattr(self, field_name, None)
        yield (field_name, value)

This lets you do:

for field, val in object:
    print field, val

Global variable Python classes

What you have is correct, though you will not call it global, it is a class attribute and can be accessed via class e.g Shape.lolwut or via an instance e.g. shape.lolwut but be careful while setting it as it will set an instance level attribute not class attribute

class Shape(object):
    lolwut = 1

shape = Shape()

print Shape.lolwut,  # 1
print shape.lolwut,  # 1

# setting shape.lolwut would not change class attribute lolwut 
# but will create it in the instance
shape.lolwut = 2

print Shape.lolwut,  # 1
print shape.lolwut,  # 2

# to change class attribute access it via class
Shape.lolwut = 3

print Shape.lolwut,  # 3
print shape.lolwut   # 2 

output:

1 1 1 2 3 2

Somebody may expect output to be 1 1 2 2 3 3 but it would be incorrect

Chrome says my extension's manifest file is missing or unreadable

In my case it was the problem of building the extension, I was pointing at an extension src (with manifest and everything) but without a build.

If you run into this scenario run npm i then npm build

ORA-12505, TNS:listener does not currently know of SID given in connect descriptor

There are a few things that can cause this problem, but before you get started with JDBC, you need to be sure that you can connect to the database using SQL*Plus. If you're not familiar with SQL*Plus, it's a command-line tool for connecting to Oracle databases that has been a standard part of Oracle for a long time and it is included with Oracle XE.

When connecting to an Oracle database using JDBC, you don't connect to the database directly. Instead, you connect to a TNS listener, which then connects you to the database. The error ORA-12505 means that the listener was up and you could connect to it, but it couldn't connect you to the database because it doesn't know that that database is up. There are two reasons for this:

  • the database has not been started up,
  • the database has not registered with the listener, e.g. because the database was started before the listener. (When the database starts, it registers itself with a listener if it is already running. If the listener isn't running, the database doesn't register itself, and if the listener starts, it doesn't go looking for databases that might register with it.)

ORA-12505 means that the listener knows about that database, but the listener hasn't received a notification from the database that the database is up. (If you were trying to connect to the wrong database, using the wrong SID, you would get an ORA-12154 error "TNS: could not resolve the connect identifier specified".)

What Oracle services are running in the Services snap-in? (Open this from Control Panel > Administrative Tools > Services, or just Start > Run > services.msc.) You need the services OracleServiceXE and OracleXETNSListener to be running.

If the services have both been started, can you connect to the database in SQL*Plus using any of the following at a command prompt? (I'm assuming you're running these on the machine you've installed Oracle XE on.)

sqlplus system/system-password@XE
sqlplus system/system-password
sqlplus / as sysdba

(Replace system-password with the password you set for the SYS and SYSTEM users during the Oracle XE installation.)

The first of these three connect via the TNS listener, but the second two connect directly to the database without going via the listener, and only work if you're on the same machine as the database. If the first one fails but the other two succeed, then JDBC connections will also fail. If so, connect to the database using either of the other two and run ALTER SYSTEM REGISTER. Then exit from SQL*Plus and try the first form again.

If the third one fails but the second one works, add your user account to the ora_dba group. Do this in Control Panel > Computer Management > Local Users and Groups.

Once you can get connections of the form

sqlplus system/system-password@XE

to work, you ought to be able to connect to Oracle XE via JDBC. (Incidentally, you haven't shown us the JDBC code you're using to connect to the database, but I would suspect that it is quite probably correct; there would be various other errors if parts of the connection string were wrong.)

Reset the database (purge all), then seed a database

As of Rails 5, the rake commandline tool has been aliased as rails so now

rails db:reset instead of rake db:reset

will work just as well

How do you list all triggers in a MySQL database?

For showing a particular trigger in a particular schema you can try the following:

select * from information_schema.triggers where 
information_schema.triggers.trigger_name like '%trigger_name%' and 
information_schema.triggers.trigger_schema like '%data_base_name%'

float:left; vs display:inline; vs display:inline-block; vs display:table-cell;

For the record only, to add to Spudley's answer, there is also the possibility to use position: absolute and margins if you know the column widths.

For me, the main issue when chossing a method is whether you need the columns to fill the whole height (equal heights), where table-cell is the easiest method (if you don't care much for older browsers).

jQuery find file extension (from string)

How about something like this.

Test the live example: http://jsfiddle.net/6hBZU/1/

It assumes that the string will always end with the extension:

function openFile(file) {
    var extension = file.substr( (file.lastIndexOf('.') +1) );
    switch(extension) {
        case 'jpg':
        case 'png':
        case 'gif':
            alert('was jpg png gif');  // There's was a typo in the example where
        break;                         // the alert ended with pdf instead of gif.
        case 'zip':
        case 'rar':
            alert('was zip rar');
        break;
        case 'pdf':
            alert('was pdf');
        break;
        default:
            alert('who knows');
    }
};

openFile("somestring.png");

EDIT: I mistakenly deleted part of the string in openFile("somestring.png");. Corrected. Had it in the Live Example, though.

How to check if smtp is working from commandline (Linux)

The only thing about using telnet to test postfix, or other SMTP, is that you have to know the commands and syntax. Instead, just use swaks :)

thufir@dur:~$ 
thufir@dur:~$ mail -f Maildir
"/home/thufir/Maildir": 4 messages
>    1 [email protected]                   15/553   test Mon, 30 Dec 2013 10:15:12 -0800
     2 [email protected]                   15/581   test Mon, 30 Dec 2013 10:15:55 -0800
     3 [email protected]                   15/581   test Mon, 30 Dec 2013 10:29:57 -0800
     4 [email protected]                   15/581   test Mon, 30 Dec 2013 11:54:16 -0800
? q
Held 4 messages in /home/thufir/Maildir
thufir@dur:~$ 
thufir@dur:~$ swaks --to [email protected]
=== Trying dur.bounceme.net:25...
=== Connected to dur.bounceme.net.
<-  220 dur.bounceme.net ESMTP Postfix (Ubuntu)
 -> EHLO dur.bounceme.net
<-  250-dur.bounceme.net
<-  250-PIPELINING
<-  250-SIZE 10240000
<-  250-VRFY
<-  250-ETRN
<-  250-STARTTLS
<-  250-ENHANCEDSTATUSCODES
<-  250-8BITMIME
<-  250 DSN
 -> MAIL FROM:<[email protected]>
<-  250 2.1.0 Ok
 -> RCPT TO:<[email protected]>
<-  250 2.1.5 Ok
 -> DATA
<-  354 End data with <CR><LF>.<CR><LF>
 -> Date: Mon, 30 Dec 2013 14:33:17 -0800
 -> To: [email protected]
 -> From: [email protected]
 -> Subject: test Mon, 30 Dec 2013 14:33:17 -0800
 -> X-Mailer: swaks v20130209.0 jetmore.org/john/code/swaks/
 -> 
 -> This is a test mailing
 -> 
 -> .
<-  250 2.0.0 Ok: queued as 52D162C3EFF
 -> QUIT
<-  221 2.0.0 Bye
=== Connection closed with remote host.
thufir@dur:~$ 
thufir@dur:~$ mail -f Maildir
"/home/thufir/Maildir": 5 messages 1 new
     1 [email protected]                   15/553   test Mon, 30 Dec 2013 10:15:12 -0800
     2 [email protected]                   15/581   test Mon, 30 Dec 2013 10:15:55 -0800
     3 [email protected]                   15/581   test Mon, 30 Dec 2013 10:29:57 -0800
     4 [email protected]                   15/581   test Mon, 30 Dec 2013 11:54:16 -0800
>N   5 [email protected]                   15/581   test Mon, 30 Dec 2013 14:33:17 -0800
? 5
Return-Path: <[email protected]>
X-Original-To: [email protected]
Delivered-To: [email protected]
Received: from dur.bounceme.net (localhost [127.0.0.1])
    by dur.bounceme.net (Postfix) with ESMTP id 52D162C3EFF
    for <[email protected]>; Mon, 30 Dec 2013 14:33:17 -0800 (PST)
Date: Mon, 30 Dec 2013 14:33:17 -0800
To: [email protected]
From: [email protected]
Subject: test Mon, 30 Dec 2013 14:33:17 -0800
X-Mailer: swaks v20130209.0 jetmore.org/john/code/swaks/
Message-Id: <[email protected]>

This is a test mailing

New mail has arrived.
? q
Held 5 messages in /home/thufir/Maildir
thufir@dur:~$ 

It's just one easy command.

Should I make HTML Anchors with 'name' or 'id'?

There's no semantic difference; the trend in the standards is toward the use of id rather than name. However, there are differences that may lead one to prefer name in some cases. The HTML 4.01 specification offers the following hints:

Use id or name? Authors should consider the following issues when deciding whether to use id or name for an anchor name:

  • The id attribute can act as more than just an anchor name (e.g., style sheet selector, processing identifier, etc.).
  • Some older user agents don't support anchors created with the id attribute.
  • The name attribute allows richer anchor names (with entities).

How to update a git clone --mirror?

This is the command that you need to execute on the mirror:

git remote update

Mac zip compress without __MACOSX folder?

do not zip any hidden file:

zip newzipname filename.any  -x "\.*"

with this question, it should be like:

zip newzipname filename.any  -x "\__MACOSX"

It must be said, though, zip command runs in terminal just compressing the file, it does not compress any others. So do this the result is the same:

zip newzipname filename.any