Programs & Examples On #Lines

Batch / Find And Edit Lines in TXT file

You can always use "FAR" = "Find and Replace". It's written under java, so it works where Java works (pretty much everywhere). Works with directories and subdirectories, searches and replaces within files, also can renames them. Also can rename bulk files.Licence = free, for both individuals or comapnies. Very fast and maintained by the developer. Find it here: http://findandreplace.sourceforge.net/

Also you can use GrepWin. Works pretty much the same. You can find it here: http://tools.tortoisesvn.net/grepWin.html

remove empty lines from text file with PowerShell

(Get-Content c:\FileWithEmptyLines.txt) | 
    Foreach { $_ -Replace  "Old content", " New content" } | 
    Set-Content c:\FileWithEmptyLines.txt;

count (non-blank) lines-of-code in bash

awk '/^[[:space:]]*$/ {++x} END {print x}' "$testfile"

Find duplicate lines in a file and count how many time each line was duplicated?

Assuming you've got access to a standard Unix shell and/or cygwin environment:

tr -s ' ' '\n' < yourfile | sort | uniq -d -c
       ^--space char

Basically: convert all space characters to linebreaks, then sort the tranlsated output and feed that to uniq and count duplicate lines.

Skip first couple of lines while reading lines in Python file

You can use a List-Comprehension to make it a one-liner:

[fl.readline() for i in xrange(17)]

More about list comprehension in PEP 202 and in the Python documentation.

Plot multiple lines (data series) each with unique color in R

In case the x-axis is a factor / discrete variable, and one would like to keep the order of the variable (different values corresponding to different groups) to visualise the group effect. The following code wold do:

library(ggplot2)
set.seed(45)

# dummy data
df <- data.frame(x=rep(letters[1:5], 9), val=sample(1:100, 45), 
                   variable=rep(paste0("category", 1:9), each=5))

# This ensures that x-axis (which is a factor variable)  will be ordered appropriately
df$x <- ordered(df$x, levels=letters[1:5])

ggplot(data = df, aes(x=x, y=val, group=variable, color=variable)) + geom_line() + geom_point() + ggtitle("Multiple lines with unique color")

enter image description here Also note that: adding group=variable remove the warning information: "geom_path: Each group consists of only one observation. Do you need to adjust the group aesthetic?"

More than 1 row in <Input type="textarea" />

As said by Sparky in comments on many answers to this question, there is NOT any textarea value for the type attribute of the input tag.

On other terms, the following markup is not valid :

<input type="textarea" />

And the browser replaces it by the default :

<input type="text" />

To define a multi-lines text input, use :

<textarea></textarea>

See the textarea element documentation for more details.

Beautiful way to remove GET-variables with PHP?

basename($_SERVER['REQUEST_URI']) returns everything after and including the '?',

In my code sometimes I need only sections, so separate it out so I can get the value of what I need on the fly. Not sure on the performance speed compared to other methods, but it's really useful for me.

$urlprotocol = 'http'; if ($_SERVER["HTTPS"] == "on") {$urlprotocol .= "s";} $urlprotocol .= "://";
$urldomain = $_SERVER["SERVER_NAME"];
$urluri = $_SERVER['REQUEST_URI'];
$urlvars = basename($urluri);
$urlpath = str_replace($urlvars,"",$urluri);

$urlfull = $urlprotocol . $urldomain . $urlpath . $urlvars;

Node.js setting up environment specific configs to be used with everyauth

The way we do this is by passing an argument in when starting the app with the environment. For instance:

node app.js -c dev

In app.js we then load dev.js as our configuration file. You can parse these options with optparse-js.

Now you have some core modules that are depending on this config file. When you write them as such:

var Workspace = module.exports = function(config) {
    if (config) {
         // do something;
    }
}

(function () {
    this.methodOnWorkspace = function () {

    };
}).call(Workspace.prototype);

And you can call it then in app.js like:

var Workspace = require("workspace");
this.workspace = new Workspace(config);

Can I edit an iPad's host file?

No. Apps can only modify files within the documents directory, within their own sandbox. This is for security, and ease of installing/uninstalling. So you could only do this on a jailbroken device.

Using FileSystemWatcher to monitor a directory

The problem was the notify filters. The program was trying to open a file that was still copying. I removed all of the notify filters except for LastWrite.

private void watch()
{
  FileSystemWatcher watcher = new FileSystemWatcher();
  watcher.Path = path;
  watcher.NotifyFilter = NotifyFilters.LastWrite;
  watcher.Filter = "*.*";
  watcher.Changed += new FileSystemEventHandler(OnChanged);
  watcher.EnableRaisingEvents = true;
}

How to set gradle home while importing existing project in Android studio

I am using Lubuntu, I ended up finding it in :

/usr/share/gradle

How to add 10 days to current time in Rails

Use

Time.now + 10.days

or even

10.days.from_now

Both definitely work. Are you sure you're in Rails and not just Ruby?

If you definitely are in Rails, where are you trying to run this from? Note that Active Support has to be loaded.

JavaScript string encryption and decryption?

How about CryptoJS?

It's a solid crypto library, with a lot of functionality. It implements hashers, HMAC, PBKDF2 and ciphers. In this case ciphers is what you need. Check out the quick-start quide on the project's homepage.

You could do something like with the AES:

<script src="http://crypto-js.googlecode.com/svn/tags/3.1.2/build/rollups/aes.js"></script>

<script>
    var encryptedAES = CryptoJS.AES.encrypt("Message", "My Secret Passphrase");
    var decryptedBytes = CryptoJS.AES.decrypt(encryptedAES, "My Secret Passphrase");
    var plaintext = decryptedBytes.toString(CryptoJS.enc.Utf8);
</script>

As for security, at the moment of my writing AES algorithm is thought to be unbroken

Edit :

Seems online URL is down & you can use the downloaded files for encryption from below given link & place the respective files in your root folder of the application.

https://code.google.com/archive/p/crypto-js/downloads

or used other CDN like https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.2/components/aes-min.js

Getting a better understanding of callback functions in JavaScript

There are 3 main possibilities to execute a function:

var callback = function(x, y) {
    // "this" may be different depending how you call the function
    alert(this);
};
  1. callback(argument_1, argument_2);
  2. callback.call(some_object, argument_1, argument_2);
  3. callback.apply(some_object, [argument_1, argument_2]);

The method you choose depends whether:

  1. You have the arguments stored in an Array or as distinct variables.
  2. You want to call that function in the context of some object. In this case, using the "this" keyword in that callback would reference the object passed as argument in call() or apply(). If you don't want to pass the object context, use null or undefined. In the latter case the global object would be used for "this".

Docs for Function.call, Function.apply

How do I properly 'printf' an integer and a string in C?

Try this code my friend...

#include<stdio.h>
int main(){
   char *s1, *s2;
   char str[10];

   printf("type a string: ");
   scanf("%s", str);

   s1 = &str[0];
   s2 = &str[2];

   printf("%c\n", *s1);   //use %c instead of %s and *s1 which is the content of position 1
   printf("%c\n", *s2);   //use %c instead of %s and *s3 which is the content of position 1

   return 0;
}

Get height and width of a layout programmatically

The first snippet is correct, but you need to call it after onMeasure() gets executed. Otherwise the size is not yet measured for the view.

How to install maven on redhat linux

Sometimes you may get "Exception in thread "main" java.lang.NoClassDefFoundError: org/codehaus/classworlds/Launcher" even after setting M2_HOME and PATH parameters correctly.

This exception is because your JDK/Java version need to be updated/installed.

How to split a string to 2 strings in C

You can use strtok() for that Example: it works for me

#include <stdio.h>
#include <string.h>

int main ()
{
    char str[] ="- This, a sample string.";
    char * pch;
    printf ("Splitting string \"%s\" into tokens:\n",str);
    pch = strtok (str," ,.-");
    while (pch != NULL)
    {
        printf ("%s\n",pch);
        pch = strtok (NULL, " ,.-");
    }
    return 0;
}

Draw a curve with css

@Navaneeth and @Antfish, no need to transform you can do like this also because in above solution only top border is visible so for inside curve you can use bottom border.

_x000D_
_x000D_
.box {_x000D_
  width: 500px;_x000D_
  height: 100px;_x000D_
  border: solid 5px #000;_x000D_
  border-color: transparent transparent #000 transparent;_x000D_
  border-radius: 0 0 240px 50%/60px;_x000D_
}
_x000D_
<div class="box"></div>
_x000D_
_x000D_
_x000D_

Spring Data JPA and Exists query

You can use Case expression for returning a boolean in your select query like below.

@Query("SELECT CASE WHEN count(e) > 0 THEN true ELSE false END FROM MyEntity e where e.my_column = ?1")

Remove directory which is not empty

graph-fs


Install

npm i graph-fs

Use

const {Node} = require("graph-fs");
const directory = new Node("/path/to/directory");

directory.delete(); // <--

Drawing in Java using Canvas

You've got to override your Canvas's paint(Graphics g) method and perform your drawing there. See the paint() documentation.

As it states, the default operation is to clear the canvas, so your call to the canvas' graphics object doesn't perform as you would expect.

How do I increase the contrast of an image in Python OpenCV

Brightness and contrast can be adjusted using alpha (a) and beta (ß), respectively. The expression can be written as

enter image description here

OpenCV already implements this as cv2.convertScaleAbs(), just provide user defined alpha and beta values

import cv2

image = cv2.imread('1.jpg')

alpha = 1.5 # Contrast control (1.0-3.0)
beta = 0 # Brightness control (0-100)

adjusted = cv2.convertScaleAbs(image, alpha=alpha, beta=beta)

cv2.imshow('original', image)
cv2.imshow('adjusted', adjusted)
cv2.waitKey()

Before -> After

enter image description here enter image description here

Note: For automatic brightness/contrast adjustment take a look at automatic contrast and brightness adjustment of a color photo

C++ getters/setters coding style

It tends to be a bad idea to make non-const fields public because it then becomes hard to force error checking constraints and/or add side-effects to value changes in the future.

In your case, you have a const field, so the above issues are not a problem. The main downside of making it a public field is that you're locking down the underlying implementation. For example, if in the future you wanted to change the internal representation to a C-string or a Unicode string, or something else, then you'd break all the client code. With a getter, you could convert to the legacy representation for existing clients while providing the newer functionality to new users via a new getter.

I'd still suggest having a getter method like the one you have placed above. This will maximize your future flexibility.

ExecuteNonQuery doesn't return results

if you want to run an update, delete, or insert statement, you should use the ExecuteNonQuery. ExecuteNonQuery returns the number of rows affected by the statement.

How to Set Count On

Executing Javascript code "on the spot" in Chrome?

Right click on the page and choose 'inspect element'. In the screen that opens now (the developer tools), clicking the second icon from the left @ the bottom of it opens a console, where you can type javascript. The console is linked to the current page.

How to drop all tables from the database with manage.py CLI in Django?

If you are using psql and have django-more 2.0.0 installed, you can do

manage.py reset_schema

Converting std::__cxx11::string to std::string

In my case, I was having a similar problem:

/usr/bin/ld: Bank.cpp:(.text+0x19c): undefined reference to 'Account::SetBank(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >)' collect2: error: ld returned 1 exit status

After some researches, I realized that the problem was being generated by the way that Visual Studio Code was compiling the Bank.cpp file. So, to solve that, I just prompted the follow command in order to compile the c++ file sucessful:

g++ Bank.cpp Account.cpp -o Bank

With the command above, It was able to linkage correctly the Header, Implementations and Main c++ files.

OBS: My g++ version: 9.3.0 on Ubuntu 20.04

What is the ultimate postal code and zip regex?

As others have pointed out, one regex to rule them all is unlikely. However, you can craft regular expressions for as many countries as you need using the address formatting info from the Universal Postal Union -- a little-known UN agency.

For example, here are the address formatting rules, including postal code, for a handful of countries (PDF format):

How to get first 5 characters from string

Use substr():

$result = substr($myStr, 0, 5);

Exists Angularjs code/naming conventions?

If you are a beginner, it is better you first go through some basic tutorials and after that learn about naming conventions. I have gone through the following to learn Angular, some of which are very effective.

Tutorials :

  1. http://www.toptal.com/angular-js/a-step-by-step-guide-to-your-first-angularjs-app
  2. http://viralpatel.net/blogs/angularjs-controller-tutorial/
  3. http://www.angularjstutorial.com/

Details of application structure and naming conventions can be found in a variety of places. I've gone through 100's of sites and I think these are among the best:

Unable to create Genymotion Virtual Device

I solved the problem.It was my mistake.
It works fine by running genymotion with administrative privileges.

android button selector

You can't achieve text size change with a state list drawable. To change text color and text size do this:

Text color

To change the text color, you can create color state list resource. It will be a separate resource located in res/color/ directory. In layout xml you have to set it as the value for android:textColor attribute. The color selector will then contain something like this:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true" android:color="@color/text_pressed" />
    <item android:color="@color/text_normal" />
</selector>

Text size

You can't change the size of the text simply with resources. There's no "dimen selector". You have to do it in code. And there is no straightforward solution.

Probably the easiest solution might be utilizing View.onTouchListener() and handle the up and down events accordingly. Use something like this:

view.setOnTouchListener(new OnTouchListener() {

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                // change text size to the "pressed value"
                return true;
            case MotionEvent.ACTION_UP:
                // change text size to the "normal value"
                return true;
            default:
                return false;
            }
        }
});

A different solution might be to extend the view and override the setPressed(Boolean) method. The method is internally called when the change of the pressed state happens. Then change the size of the text accordingly in the method call (don't forget to call the super).

How can I programmatically check whether a keyboard is present in iOS app?

BOOL isTxtOpen = [txtfieldObjct isFirstReponder]. If it returns YES, then the the keyboard is active.

Setting the default Java character encoding

Recently I bumped into a local company's Notes 6.5 system and found out the webmail would show unidentifiable characters on a non-Zhongwen localed Windows installation. Have dug for several weeks online, figured it out just few minutes ago:

In Java properties, add the following string to Runtime Parameters

-Dfile.encoding=MS950 -Duser.language=zh -Duser.country=TW -Dsun.jnu.encoding=MS950

UTF-8 setting would not work in this case.

What does '<?=' mean in PHP?

It means assign the key to $user and the variable to $pass

When you assign an array, you do it like this

$array = array("key" => "value");

It uses the same symbol for processing arrays in foreach statements. The '=>' links the key and the value.

According to the PHP Manual, the '=>' created key/value pairs.

Also, Equal or Greater than is the opposite way: '>='. In PHP the greater or less than sign always goes first: '>=', '<='.

And just as a side note, excluding the second value does not work like you think it would. Instead of only giving you the key, It actually only gives you a value:

$array = array("test" => "foo");

foreach($array as $key => $value)
{
    echo $key . " : " . $value; // Echoes "test : foo"
}

foreach($array as $value)
{
    echo $value; // Echoes "foo"
}

CSS: Position text in the middle of the page

Even though you've accepted an answer, I want to post this method. I use jQuery to center it vertically instead of css (although both of these methods work). Here is a fiddle, and I'll post the code here anyways.

HTML:

<h1>Hello world!</h1>

Javascript (jQuery):

$(document).ready(function(){
  $('h1').css({ 'width':'100%', 'text-align':'center' });
  var h1 = $('h1').height();
  var h = h1/2;
  var w1 = $(window).height();
  var w = w1/2;
  var m = w - h
  $('h1').css("margin-top",m + "px")
});

This takes the height of the viewport, divides it by two, subtracts half the height of the h1, and sets that number to the margin-top of the h1. The beauty of this method is that it works on multiple-line h1s.

EDIT: I modified it so that it centered it every time the window is resized.

add a temporary column with a value

select field1, field2, NewField = 'example' from table1 

java.util.Date and getYear()

Year.now()

There's an easier way to use the java.time library in Java 8+. The expression:

java.time.Year.now().getValue()

returns the current year as a four-digit int, using your default time zone. There are lots of options for different time ZoneIds, Calendars and Clocks, but I think this is what you will want most of the time. If you want the code to look cleaner (and don't need any other java.time.*.now() functions), put:

import static java.time.Year.now;

at the top of your file, and call:

now().getValue()

as needed.

Angular routerLink does not navigate to the corresponding component

For not very sharp eyes like mine, I had href instead of routerLink, took me a few searches to figure that out #facepalm.

How to read html from a url in python 3

Note that Python3 does not read the html code as a string but as a bytearray, so you need to convert it to one with decode.

import urllib.request

fp = urllib.request.urlopen("http://www.python.org")
mybytes = fp.read()

mystr = mybytes.decode("utf8")
fp.close()

print(mystr)

Good way of getting the user's location in Android

To select the right location provider for your app, you can use Criteria objects:

Criteria myCriteria = new Criteria();
myCriteria.setAccuracy(Criteria.ACCURACY_HIGH);
myCriteria.setPowerRequirement(Criteria.POWER_LOW);
// let Android select the right location provider for you
String myProvider = locationManager.getBestProvider(myCriteria, true); 

// finally require updates at -at least- the desired rate
long minTimeMillis = 600000; // 600,000 milliseconds make 10 minutes
locationManager.requestLocationUpdates(myProvider,minTimeMillis,0,locationListener); 

Read the documentation for requestLocationUpdates for more details on how the arguments are taken into account:

The frequency of notification may be controlled using the minTime and minDistance parameters. If minTime is greater than 0, the LocationManager could potentially rest for minTime milliseconds between location updates to conserve power. If minDistance is greater than 0, a location will only be broadcasted if the device moves by minDistance meters. To obtain notifications as frequently as possible, set both parameters to 0.

More thoughts

  • You can monitor the accuracy of the Location objects with Location.getAccuracy(), which returns the estimated accuracy of the position in meters.
  • the Criteria.ACCURACY_HIGH criterion should give you errors below 100m, which is not as good as GPS can be, but matches your needs.
  • You also need to monitor the status of your location provider, and switch to another provider if it gets unavailable or disabled by the user.
  • The passive provider may also be a good match for this kind of application: the idea is to use location updates whenever they are requested by another app and broadcast systemwide.

What is the meaning of Bus: error 10 in C

Your code attempts to overwrite a string literal. This is undefined behaviour.

There are several ways to fix this:

  1. use malloc() then strcpy() then free();
  2. turn str into an array and use strcpy();
  3. use strdup().

Refresh Fragment at reload

protected void onResume() {
        super.onResume();
        viewPagerAdapter.notifyDataSetChanged();
    }

Do write viewpagerAdapter.notifyDataSetChanged(); in onResume() in MainActivity. Good Luck :)

How to get indices of a sorted array in Python

myList = [1, 2, 3, 100, 5]    
sorted(range(len(myList)),key=myList.__getitem__)

[0, 1, 2, 4, 3]

Is it a bad practice to use an if-statement without curly braces?

It is a matter of preference. I personally use both styles, if I am reasonably sure that I won't need to add anymore statements, I use the first style, but if that is possible, I use the second. Since you cannot add anymore statements to the first style, I have heard some people recommend against using it. However, the second method does incur an additional line of code and if you (or your project) uses this kind of coding style, the first method is very much preferred for simple if statements:

if(statement)
{
    do this;
}
else
{
    do this;
}

However, I think the best solution to this problem is in Python. With the whitespace-based block structure, you don't have two different methods of creating an if statement: you only have one:

if statement:
    do this
else:
    do this

While that does have the "issue" that you can't use the braces at all, you do gain the benefit that it is no more lines that the first style and it has the power to add more statements.

Is it possible to reference one CSS rule within another?

Just add the classes to your html

<div class="someDiv radius opacity"></div>

Getting the last element of a split string array

You can also consider to reverse your array and take the first element. That way you don't have to know about the length, but it brings no real benefits and the disadvantage that the reverse operation might take longer with big arrays:

array1.split(",").reverse()[0]

It's easy though, but also modifies the original array in question. That might or might not be a problem.

Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reverse

Probably you might want to use this though:

array1.split(",").pop()

How to inject a Map using the @Value Spring Annotation?

Here is how we did it. Two sample classes as follow:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.kafka.annotation.EnableKafka;
@EnableKafka
@Configuration
@EnableConfigurationProperties(KafkaConsumerProperties.class)
public class KafkaContainerConfig {

    @Autowired
    protected KafkaConsumerProperties kafkaConsumerProperties;

    @Bean
    public ConsumerFactory<String, String> consumerFactory() {
        return new DefaultKafkaConsumerFactory<>(kafkaConsumerProperties.getKafkaConsumerConfig());
    }
...

@Configuration
@ConfigurationProperties
public class KafkaConsumerProperties {
    protected Map<String, Object> kafkaConsumerConfig = new HashMap<>();

    @ConfigurationProperties("kafkaConsumerConfig")
    public Map<String, Object> getKafkaConsumerConfig() {
        return (kafkaConsumerConfig);
    }
...

To provide the kafkaConsumer config from a properties file, you can use: mapname[key]=value

//application.properties
kafkaConsumerConfig[bootstrap.servers]=localhost:9092, localhost:9093, localhost:9094
kafkaConsumerConfig[group.id]=test-consumer-group-local
kafkaConsumerConfig[value.deserializer]=org.apache.kafka.common.serialization.StringDeserializer
kafkaConsumerConfig[key.deserializer=org.apache.kafka.common.serialization.StringDeserializer

To provide the kafkaConsumer config from a yaml file, you can use "[key]": value In application.yml file:

kafkaConsumerConfig:
  "[bootstrap.servers]": localhost:9092, localhost:9093, localhost:9094
  "[group.id]": test-consumer-group-local
  "[value.deserializer]": org.apache.kafka.common.serialization.StringDeserializer
  "[key.deserializer]": org.apache.kafka.common.serialization.StringDeserializer

How could others, on a local network, access my NodeJS app while it's running on my machine?

I had this problem. The solution was to allow node.js through the server's firewall.

How can I get npm start at a different directory?

This one-liner should work too:

(cd /path/to/your/app && npm start)

Note that the current directory will be changed to /path/to/your/app after executing this command. To preserve the working directory:

(cd /path/to/your/app && npm start && cd -)

I used this solution because a program configuration file I was editing back then didn't support specifying command line arguments.

Remove Trailing Spaces and Update in Columns in SQL Server

I had the same problem after extracting data from excel file using ETL and finaly i found solution there :

https://www.codeproject.com/Tips/330787/LTRIM-RTRIM-doesn-t-always-work

hope it helps ;)

How to change the date format from MM/DD/YYYY to YYYY-MM-DD in PL/SQL?

Basically , Data in a Date column in Oracle can be stored in any user defined format or kept as default. It all depends on NLS parameter.

Current format can be seen by : SELECT SYSDATE FROM DUAL;

If you try to insert a record and insert statement is NOT in THIS format then it will give : ORA-01843 : not a valid month error. So first change the database date format before insert statements ( I am assuming you have bulk load of insert statements) and then execute insert script.

Format can be changed by : ALTER SESSION SET nls_date_format = 'mm/dd/yyyy hh24:mi:ss';

Also You can Change NLS settings from SQL Developer GUI , (Tools > preference> database > NLS)

Ref: http://oracle.ittoolbox.com/groups/technical-functional/oracle-sql-l/how-to-view-current-date-format-1992815

How to get the path of a running JAR file?

String path = getClass().getResource("").getPath();

The path always refers to the resource within the jar file.

XML Schema (XSD) validation tool?

After some research, I think the best answer is Xerces, as it implements all of XSD, is cross-platform and widely used. I've created a small Java project on github to validate from the command line using the default JRE parser, which is normally Xerces. This can be used on Windows/Mac/Linux.

There is also a C++ version of Xerces available if you'd rather use that. The StdInParse utility can be used to call it from the command line. Also, a commenter below points to this more complete wrapper utility.

You could also use xmllint, which is part of libxml. You may well already have it installed. Example usage:

xmllint --noout --schema XSD_FILE XML_FILE

One problem is that libxml doesn't implement all of the specification, so you may run into issues :(

Alternatively, if you are on Windows, you can use msxml, but you will need some sort of wrapper to call it, such as the GUI one described in this DDJ article. However, it seems most people on Windows use an XML Editor, such as Notepad++ (as described in Nate's answer) or XML Notepad 2007 as suggested by SteveC (there are also several commercial editors which I won't mention here).

Finally, you'll find different programs will, unfortunately, give different results. This is largely due to the complexity of the XSD spec. You may want to test your schema with several tools.

UPDATE: I've expanded on this in a blog post.

Sending HTTP POST Request In Java

Sending a POST request is easy in vanilla Java. Starting with a URL, we need t convert it to a URLConnection using url.openConnection();. After that, we need to cast it to a HttpURLConnection, so we can access its setRequestMethod() method to set our method. We finally say that we are going to send data over the connection.

URL url = new URL("https://www.example.com/login");
URLConnection con = url.openConnection();
HttpURLConnection http = (HttpURLConnection)con;
http.setRequestMethod("POST"); // PUT is another valid option
http.setDoOutput(true);

We then need to state what we are going to send:

Sending a simple form

A normal POST coming from a http form has a well defined format. We need to convert our input to this format:

Map<String,String> arguments = new HashMap<>();
arguments.put("username", "root");
arguments.put("password", "sjh76HSn!"); // This is a fake password obviously
StringJoiner sj = new StringJoiner("&");
for(Map.Entry<String,String> entry : arguments.entrySet())
    sj.add(URLEncoder.encode(entry.getKey(), "UTF-8") + "=" 
         + URLEncoder.encode(entry.getValue(), "UTF-8"));
byte[] out = sj.toString().getBytes(StandardCharsets.UTF_8);
int length = out.length;

We can then attach our form contents to the http request with proper headers and send it.

http.setFixedLengthStreamingMode(length);
http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
http.connect();
try(OutputStream os = http.getOutputStream()) {
    os.write(out);
}
// Do something with http.getInputStream()

Sending JSON

We can also send json using java, this is also easy:

byte[] out = "{\"username\":\"root\",\"password\":\"password\"}" .getBytes(StandardCharsets.UTF_8);
int length = out.length;

http.setFixedLengthStreamingMode(length);
http.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
http.connect();
try(OutputStream os = http.getOutputStream()) {
    os.write(out);
}
// Do something with http.getInputStream()

Remember that different servers accept different content-types for json, see this question.


Sending files with java post

Sending files can be considered more challenging to handle as the format is more complex. We are also going to add support for sending the files as a string, since we don't want to buffer the file fully into the memory.

For this, we define some helper methods:

private void sendFile(OutputStream out, String name, InputStream in, String fileName) {
    String o = "Content-Disposition: form-data; name=\"" + URLEncoder.encode(name,"UTF-8") 
             + "\"; filename=\"" + URLEncoder.encode(filename,"UTF-8") + "\"\r\n\r\n";
    out.write(o.getBytes(StandardCharsets.UTF_8));
    byte[] buffer = new byte[2048];
    for (int n = 0; n >= 0; n = in.read(buffer))
        out.write(buffer, 0, n);
    out.write("\r\n".getBytes(StandardCharsets.UTF_8));
}

private void sendField(OutputStream out, String name, String field) {
    String o = "Content-Disposition: form-data; name=\"" 
             + URLEncoder.encode(name,"UTF-8") + "\"\r\n\r\n";
    out.write(o.getBytes(StandardCharsets.UTF_8));
    out.write(URLEncoder.encode(field,"UTF-8").getBytes(StandardCharsets.UTF_8));
    out.write("\r\n".getBytes(StandardCharsets.UTF_8));
}

We can then use these methods to create a multipart post request as follows:

String boundary = UUID.randomUUID().toString();
byte[] boundaryBytes = 
           ("--" + boundary + "\r\n").getBytes(StandardCharsets.UTF_8);
byte[] finishBoundaryBytes = 
           ("--" + boundary + "--").getBytes(StandardCharsets.UTF_8);
http.setRequestProperty("Content-Type", 
           "multipart/form-data; charset=UTF-8; boundary=" + boundary);

// Enable streaming mode with default settings
http.setChunkedStreamingMode(0); 

// Send our fields:
try(OutputStream out = http.getOutputStream()) {
    // Send our header (thx Algoman)
    out.write(boundaryBytes);

    // Send our first field
    sendField(out, "username", "root");

    // Send a seperator
    out.write(boundaryBytes);

    // Send our second field
    sendField(out, "password", "toor");

    // Send another seperator
    out.write(boundaryBytes);

    // Send our file
    try(InputStream file = new FileInputStream("test.txt")) {
        sendFile(out, "identification", file, "text.txt");
    }

    // Finish the request
    out.write(finishBoundaryBytes);
}


// Do something with http.getInputStream()

How do I get the name of the current executable in C#?

System.AppDomain.CurrentDomain.FriendlyName

How do you UDP multicast in Python?

Better use:

sock.bind((MCAST_GRP, MCAST_PORT))

instead of:

sock.bind(('', MCAST_PORT))

because, if you want to listen to multiple multicast groups on the same port, you'll get all messages on all listeners.

How do I select an entire row which has the largest ID in the table?

You could use a subselect:

SELECT row 
FROM table 
WHERE id=(
    SELECT max(id) FROM table
    )

Note that if the value of max(id) is not unique, multiple rows are returned.

If you only want one such row, use @MichaelMior's answer,

SELECT row from table ORDER BY id DESC LIMIT 1

How to change XML Attribute

Here's the beginnings of a parser class to get you started. This ended up being my solution to a similar problem:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;

namespace XML
{
    public class Parser
    {

        private string _FilePath = string.Empty;

        private XDocument _XML_Doc = null;


        public Parser(string filePath)
        {
            _FilePath = filePath;
            _XML_Doc = XDocument.Load(_FilePath);
        }


        /// <summary>
        /// Replaces values of all attributes of a given name (attributeName) with the specified new value (newValue) in all elements.
        /// </summary>
        /// <param name="attributeName"></param>
        /// <param name="newValue"></param>
        public void ReplaceAtrribute(string attributeName, string newValue)
        {
            ReplaceAtrribute(string.Empty, attributeName, new List<string> { }, newValue);
        }

        /// <summary>
        /// Replaces values of all attributes of a given name (attributeName) with the specified new value (newValue) in elements with a given name (elementName).
        /// </summary>
        /// <param name="elementName"></param>
        /// <param name="attributeName"></param>
        /// <param name="newValue"></param>
        public void ReplaceAtrribute(string elementName, string attributeName, string newValue)
        {
            ReplaceAtrribute(elementName, attributeName, new List<string> { }, newValue);
        }


        /// <summary>
        /// Replaces values of all attributes of a given name (attributeName) and value (oldValue)  
        /// with the specified new value (newValue) in elements with a given name (elementName).
        /// </summary>
        /// <param name="elementName"></param>
        /// <param name="attributeName"></param>
        /// <param name="oldValue"></param>
        /// <param name="newValue"></param>
        public void ReplaceAtrribute(string elementName, string attributeName, string oldValue, string newValue)
        {
            ReplaceAtrribute(elementName, attributeName, new List<string> { oldValue }, newValue);              
        }


        /// <summary>
        /// Replaces values of all attributes of a given name (attributeName), which has one of a list of values (oldValues), 
        /// with the specified new value (newValue) in elements with a given name (elementName).
        /// If oldValues is empty then oldValues will be ignored.
        /// </summary>
        /// <param name="elementName"></param>
        /// <param name="attributeName"></param>
        /// <param name="oldValues"></param>
        /// <param name="newValue"></param>
        public void ReplaceAtrribute(string elementName, string attributeName, List<string> oldValues, string newValue)
        {
            List<XElement> elements = _XML_Doc.Elements().Descendants().ToList();

            foreach (XElement element in elements)
            {
                if (elementName == string.Empty | element.Name.LocalName.ToString() == elementName)
                {
                    if (element.Attribute(attributeName) != null)
                    {

                        if (oldValues.Count == 0 || oldValues.Contains(element.Attribute(attributeName).Value))
                        { element.Attribute(attributeName).Value = newValue; }
                    }
                }
            }

        }

        public void SaveChangesToFile()
        {
            _XML_Doc.Save(_FilePath);
        }

    }
}

Get Maven artifact version at runtime

Here's a method for getting the version from the pom.properties, falling back to getting it from the manifest

public synchronized String getVersion() {
    String version = null;

    // try to load from maven properties first
    try {
        Properties p = new Properties();
        InputStream is = getClass().getResourceAsStream("/META-INF/maven/com.my.group/my-artefact/pom.properties");
        if (is != null) {
            p.load(is);
            version = p.getProperty("version", "");
        }
    } catch (Exception e) {
        // ignore
    }

    // fallback to using Java API
    if (version == null) {
        Package aPackage = getClass().getPackage();
        if (aPackage != null) {
            version = aPackage.getImplementationVersion();
            if (version == null) {
                version = aPackage.getSpecificationVersion();
            }
        }
    }

    if (version == null) {
        // we could not compute the version so use a blank
        version = "";
    }

    return version;
} 

How to downgrade tensorflow, multiple versions possible?

Click to green checkbox on installed tensorflow and choose needed versionscreenshot Anaconda navigator

If/else else if in Jquery for a condition

A few more things in addition to the existing answers. Have a look at this:

var seatsValid = true;
// cache the selector
var seatsVal = $("#seats").val();
if(seatsVal!=''){
    seatsValid = false;
    alert("Not a valid character")
    // convert seatsVal to an integer for comparison
}else if(parseInt(seatsVal) < 99999){
    seatsValid = false;
    alert("Not a valid Number");
}

The variable name setFlag is very generic, if your only using it in conjunction with the number of seats you should rename it (I called it seatsValid). I also initialized it to true which gets rid of the need for the final else in your original code. Next, I put the selector and call to .val() in a variable. It's good practice to cache your selectors so jquery doesn't need to traverse the DOM more than it needs to. Lastly when comparing two values you should try to make sure they are the same type, in this case seatsVal is a string so in order to properly compare it to 99999 you should use parseInt() on it.

Sql Server string to date conversion

This page has some references for all of the specified datetime conversions available to the CONVERT function. If your values don't fall into one of the acceptable patterns, then I think the best thing is to go the ParseExact route.

Installing SetupTools on 64-bit Windows

Create a file named python2.7.reg (registry file) and put this content into it:

Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Python\PythonCore\2.7]

[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Python\PythonCore\2.7\Help]

[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Python\PythonCore\2.7\Help\MainPythonDocumentation]
@="C:\\Python27\\Doc\\python26.chm"

[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Python\PythonCore\2.7\InstallPath]
@="C:\\Python27\\"

[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Python\PythonCore\2.7\InstallPath\InstallGroup]
@="Python 2.7"

[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Python\PythonCore\2.7\Modules]

[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Python\PythonCore\2.7\PythonPath]
@="C:\\Python27\\Lib;C:\\Python27\\DLLs;C:\\Python27\\Lib\\lib-tk"

And make sure every path is right!

Then run (merge) it and done :)

Bootstrap 3 Navbar with Logo

You must use code as this:

<div class="navbar-header">
    <button type="button" class="navbar-toggle" data-toggle="collapse" 
            data-target=".navbar-ex1-collapse">
        <span class="sr-only">Toggle navigation</span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
    </button>
    <a class="logo" rel="home" href="#" title="Buy Sell Rent Everyting">
        <img style=""
             src="/img/transparent-white-logo.png">
    </a>
</div>

Class of A tag must be "logo" not navbar-brand.

Run react-native application on iOS device directly from command line?

The following worked for me (tested on react native 0.38 and 0.40):

npm install -g ios-deploy
# Run on a connected device, e.g. Max's iPhone:
react-native run-ios --device "Max's iPhone"

If you try to run run-ios, you will see that the script recommends to do npm install -g ios-deploy when it reach install step after building.

While the documentation on the various commands that react-native offers is a little sketchy, it is worth going to react-native/local-cli. There, you can see all the commands available and the code that they run - you can thus work out what switches are available for undocumented commands.

gdb: how to print the current line or find the current line number?

The 'frame' command will give you what you are looking for. (This can be abbreviated just 'f'). Here is an example:

(gdb) frame
\#0  zmq::xsub_t::xrecv (this=0x617180, msg_=0x7ffff00008e0) at xsub.cpp:139
139         int rc = fq.recv (msg_);
(gdb)

Without an argument, 'frame' just tells you where you are at (with an argument it changes the frame). More information on the frame command can be found here.

MVC4 Passing model from view to controller

I hope this complete example will help you.

This is the TaxiInfo class which holds information about a taxi ride:

namespace Taxi.Models
{
    public class TaxiInfo
    {
        public String Driver { get; set; }
        public Double Fare { get; set; }
        public Double Distance { get; set; }
        public String StartLocation { get; set; }
        public String EndLocation { get; set; }
    }
}

We also have a convenience model which holds a List of TaxiInfo(s):

namespace Taxi.Models
{
    public class TaxiInfoSet
    {
        public List<TaxiInfo> TaxiInfoList { get; set; }

        public TaxiInfoSet(params TaxiInfo[] TaxiInfos)
        {
            TaxiInfoList = new List<TaxiInfo>();

            foreach(var TaxiInfo in TaxiInfos)
            {
                TaxiInfoList.Add(TaxiInfo);
            }
        }
    }
}

Now in the home controller we have the default Index action which for this example makes two taxi drivers and adds them to the list contained in a TaxiInfo:

public ActionResult Index()
{
    var taxi1 = new TaxiInfo() { Fare = 20.2, Distance = 15, Driver = "Billy", StartLocation = "Perth", EndLocation = "Brisbane" };
    var taxi2 = new TaxiInfo() { Fare = 2339.2, Distance = 1500, Driver = "Smith", StartLocation = "Perth", EndLocation = "America" };

    return View(new TaxiInfoSet(taxi1,taxi2));
}

The code for the view is as follows:

@model Taxi.Models.TaxiInfoSet
@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

@foreach(var TaxiInfo in Model.TaxiInfoList){
    <form>
        <h1>Cost: [email protected]</h1>
        <h2>Distance: @(TaxiInfo.Distance) km</h2>
        <p>
            Our diver, @TaxiInfo.Driver will take you from @TaxiInfo.StartLocation to @TaxiInfo.EndLocation
        </p>
        @Html.ActionLink("Home","Booking",TaxiInfo)
    </form>
}

The ActionLink is responsible for the re-directing to the booking action of the Home controller (and passing in the appropriate TaxiInfo object) which is defiend as follows:

    public ActionResult Booking(TaxiInfo Taxi)
    {
        return View(Taxi);
    }

This returns a the following view:

@model Taxi.Models.TaxiInfo

@{
    ViewBag.Title = "Booking";
}

<h2>Booking For</h2>
<h1>@Model.Driver, going from @Model.StartLocation to @Model.EndLocation (a total of @Model.Distance km) for [email protected]</h1>

A visual tour:

The Index view

The Booking view

How can I see if a Perl hash already has a certain key?

You can just go with:

if(!$strings{$string}) ....

How to implement a binary search tree in Python?

The Op's Tree.insert method qualifies for the "Gross Misnomer of the Week" award -- it doesn't insert anything. It creates a node which is not attached to any other node (not that there are any nodes to attach it to) and then the created node is trashed when the method returns.

For the edification of @Hugh Bothwell:

>>> class Foo(object):
...    bar = None
...
>>> a = Foo()
>>> b = Foo()
>>> a.bar
>>> a.bar = 42
>>> b.bar
>>> b.bar = 666
>>> a.bar
42
>>> b.bar
666
>>>

Linq: GroupBy, Sum and Count

sometimes you need to select some fields by FirstOrDefault() or singleOrDefault() you can use the below query:

List<ResultLine> result = Lines
    .GroupBy(l => l.ProductCode)
    .Select(cl => new Models.ResultLine
            {
                ProductName = cl.select(x=>x.Name).FirstOrDefault(),
                Quantity = cl.Count().ToString(),
                Price = cl.Sum(c => c.Price).ToString(),
            }).ToList();

Where does VBA Debug.Print log to?

Debug.Print outputs to the "Immediate" window.

Debug.Print outputs to the Immediate window

Also, you can simply type ? and then a statement directly into the immediate window (and then press Enter) and have the output appear right below, like this:

simply type ? and then a statement directly into the immediate window

This can be very handy to quickly output the property of an object...

? myWidget.name

...to set the property of an object...

myWidget.name = "thingy"

...or to even execute a function or line of code, while in debugging mode:

Sheet1.MyFunction()

Python: Assign print output to a variable

This is a standalone example showing how to save the output of a user-written function in Python 3:

from io import StringIO
import sys

def print_audio_tagging_result(value):
    print(f"value = {value}")

tag_list = []
for i in range(0,1):
    save_stdout = sys.stdout
    result = StringIO()
    sys.stdout = result
    print_audio_tagging_result(i)
    sys.stdout = save_stdout
    tag_list.append(result.getvalue())
print(tag_list)

How do I change the color of radio buttons?

It may be helpful to bind radio-button to styled label. Futher details in this answer.

Using GitLab token to clone without authentication

These days (Oct 2020) you can use just the following

git clone $CI_REPOSITORY_URL

Which will expand to something like:

git clone https://gitlab-ci-token:[MASKED]@gitlab.com/gitlab-examples/ci-debug-trace.git

Where the "token" password is ephemeral token, it should be revoked after a build is complete.

Measure execution time for a Java method

You might want to think about aspect-oriented programming. You don't want to litter your code with timings. You want to be able to turn them off and on declaratively.

If you use Spring, take a look at their MethodInterceptor class.

Select all 'tr' except the first one

sounds like the 'first line' you're talking of is your table-header - so you realy should think of using thead and tbody in your markup (click here) which would result in 'better' markup (semantically correct, useful for things like screenreaders) and easier, cross-browser-friendly possibilitys for css-selection (table thead ... { ... })

Common xlabel/ylabel for matplotlib subplots

This looks like what you actually want. It applies the same approach of this answer to your specific case:

import matplotlib.pyplot as plt

fig, ax = plt.subplots(nrows=3, ncols=3, sharex=True, sharey=True, figsize=(6, 6))

fig.text(0.5, 0.04, 'common X', ha='center')
fig.text(0.04, 0.5, 'common Y', va='center', rotation='vertical')

Multiple plots with common axes label

How to select different app.config for several build configurations

See if the XDT (web.config) transform engine can help you. Currently it's only natively supported for web projects, but technically there is nothing stopping you from using it in other application types. There are many guides on how to use XDT by manually editing the project files, but I found a plugin that works great: https://visualstudiogallery.msdn.microsoft.com/579d3a78-3bdd-497c-bc21-aa6e6abbc859

The plugin is only helping to setup the configuration, it's not needed to build and the solution can be built on other machines or on a build server without the plugin or any other tools being required.

Xcode iOS 8 Keyboard types not supported

This error had come when your keyboard input type is Number Pad.I got same error than I change my Textfield keyboard input type to Default fix my issue.

java.lang.VerifyError: Expecting a stackmap frame at branch target JDK 1.7

I ran into this problem and try using the flag -noverify which really works. It is because of the new bytecode verifier. So the flag should really work. I am using JDK 1.7.

Note: This would not work if you are using JDK 1.8

ssl.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:749)

Open a terminal and take a look at:

/Applications/Python 3.6/Install Certificates.command

Python 3.6 on MacOS uses an embedded version of OpenSSL, which does not use the system certificate store. More details here.

(To be explicit: MacOS users can probably resolve by opening Finder and double clicking Install Certificates.command)

How to get the jQuery $.ajax error response text?

The best simple approach :

error: function (xhr) {
var err = JSON.parse(xhr.responseText);
alert(err.message);
}

How to display multiple images in one figure correctly?

Here is my approach that you may try:

import numpy as np
import matplotlib.pyplot as plt

w=10
h=10
fig=plt.figure(figsize=(8, 8))
columns = 4
rows = 5
for i in range(1, columns*rows +1):
    img = np.random.randint(10, size=(h,w))
    fig.add_subplot(rows, columns, i)
    plt.imshow(img)
plt.show()

The resulting image:

output_image

(Original answer date: Oct 7 '17 at 4:20)

Edit 1

Since this answer is popular beyond my expectation. And I see that a small change is needed to enable flexibility for the manipulation of the individual plots. So that I offer this new version to the original code. In essence, it provides:-

  1. access to individual axes of subplots
  2. possibility to plot more features on selected axes/subplot

New code:

import numpy as np
import matplotlib.pyplot as plt

w = 10
h = 10
fig = plt.figure(figsize=(9, 13))
columns = 4
rows = 5

# prep (x,y) for extra plotting
xs = np.linspace(0, 2*np.pi, 60)  # from 0 to 2pi
ys = np.abs(np.sin(xs))           # absolute of sine

# ax enables access to manipulate each of subplots
ax = []

for i in range(columns*rows):
    img = np.random.randint(10, size=(h,w))
    # create subplot and append to ax
    ax.append( fig.add_subplot(rows, columns, i+1) )
    ax[-1].set_title("ax:"+str(i))  # set title
    plt.imshow(img, alpha=0.25)

# do extra plots on selected axes/subplots
# note: index starts with 0
ax[2].plot(xs, 3*ys)
ax[19].plot(ys**2, xs)

plt.show()  # finally, render the plot

The resulting plot:

enter image description here

Edit 2

In the previous example, the code provides access to the sub-plots with single index, which is inconvenient when the figure has many rows/columns of sub-plots. Here is an alternative of it. The code below provides access to the sub-plots with [row_index][column_index], which is more suitable for manipulation of array of many sub-plots.

import matplotlib.pyplot as plt
import numpy as np

# settings
h, w = 10, 10        # for raster image
nrows, ncols = 5, 4  # array of sub-plots
figsize = [6, 8]     # figure size, inches

# prep (x,y) for extra plotting on selected sub-plots
xs = np.linspace(0, 2*np.pi, 60)  # from 0 to 2pi
ys = np.abs(np.sin(xs))           # absolute of sine

# create figure (fig), and array of axes (ax)
fig, ax = plt.subplots(nrows=nrows, ncols=ncols, figsize=figsize)

# plot simple raster image on each sub-plot
for i, axi in enumerate(ax.flat):
    # i runs from 0 to (nrows*ncols-1)
    # axi is equivalent with ax[rowid][colid]
    img = np.random.randint(10, size=(h,w))
    axi.imshow(img, alpha=0.25)
    # get indices of row/column
    rowid = i // ncols
    colid = i % ncols
    # write row/col indices as axes' title for identification
    axi.set_title("Row:"+str(rowid)+", Col:"+str(colid))

# one can access the axes by ax[row_id][col_id]
# do additional plotting on ax[row_id][col_id] of your choice
ax[0][2].plot(xs, 3*ys, color='red', linewidth=3)
ax[4][3].plot(ys**2, xs, color='green', linewidth=3)

plt.tight_layout(True)
plt.show()

The resulting plot:

plot3

How to create id with AUTO_INCREMENT on Oracle?

Starting with Oracle 12c there is support for Identity columns in one of two ways:

  1. Sequence + Table - In this solution you still create a sequence as you normally would, then you use the following DDL:

    CREATE TABLE MyTable (ID NUMBER DEFAULT MyTable_Seq.NEXTVAL, ...)

  2. Table Only - In this solution no sequence is explicitly specified. You would use the following DDL:

    CREATE TABLE MyTable (ID NUMBER GENERATED AS IDENTITY, ...)

If you use the first way it is backward compatible with the existing way of doing things. The second is a little more straightforward and is more inline with the rest of the RDMS systems out there.

failed to push some refs to [email protected]

Make sure you’re pushing the right branch. I wasn’t on master and kept wondering why it was complaining :P

Can HTML be embedded inside PHP "if" statement?

Yes.

<?  if($my_name == 'someguy') { ?>
        HTML_GOES_HERE
<?  } ?>

Gem Command not found

try

$ /usr/bin/pd-gem

or

$ pd-gem

How to fast-forward a branch to head?

Try git merge origin/master. If you want to be sure that it only does a fast-forward, you can say git merge --ff-only origin/master.

How to load a controller from another controller in codeigniter?

There are many ways by which you can access one controller into another.

class Test1 extends CI_controller
{
    function testfunction(){
        return 1;
    }
}

Then create another class, and include first Class in it, and extend it with your class.

include 'Test1.php';

class Test extends Test1
{
    function myfunction(){
        $this->test();
        echo 1;
    }
}

What is the equivalent of bigint in C#?

That corresponds to the long (or Int64), a 64-bit integer.

Although if the number from the database happens to be small enough, and you accidentally use an Int32, etc., you'll be fine. But the Int64 will definitely hold it.

And the error you get if you use something smaller and the full size is needed? A stack overflow! Yay!

SSL received a record that exceeded the maximum permissible length. (Error code: ssl_error_rx_record_too_long)

Below Solution worked for me :

Type About:Config in the Address Bar and press Enter.

“This Might void your warranty!” warning will be displayed, click on I’ll be careful, I Promise button.

Type security.ssl.enable_ocsp_stapling in search box.

The value field is true, double click on it to make it false.

Now try to connect your website again.

How to change an Android app's name?

It depends what you want to do. I personally wanted to rename my project so it didn't say MainActivity at the top of the app and underneath the icon on my phone menu.

To do this I went into the Android Manifest.xml file and edited

<activity
        android:name=".MainActitivity"
        android:label="@string/title_activity_main" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

And edited the android:name=".Mynewname" and then edited the string title_activity_main in the strings.xml file to match the name.

Hope that helps!

How to select Multiple images from UIImagePickerController

You can't use UIImagePickerController, but you can use a custom image picker. I think ELCImagePickerController is the best option, but here are some other libraries you could use:

Objective-C
1. ELCImagePickerController
2. WSAssetPickerController
3. QBImagePickerController
4. ZCImagePickerController
5. CTAssetsPickerController
6. AGImagePickerController
7. UzysAssetsPickerController
8. MWPhotoBrowser
9. TSAssetsPickerController
10. CustomImagePicker
11. InstagramPhotoPicker
12. GMImagePicker
13. DLFPhotosPicker
14. CombinationPickerController
15. AssetPicker
16. BSImagePicker
17. SNImagePicker
18. DoImagePickerController
19. grabKit
20. IQMediaPickerController
21. HySideScrollingImagePicker
22. MultiImageSelector
23. TTImagePicker
24. SelectImages
25. ImageSelectAndSave
26. imagepicker-multi-select
27. MultiSelectImagePickerController
28. YangMingShan(Yahoo like image selector)
29. DBAttachmentPickerController
30. BRImagePicker
31. GLAssetGridViewController
32. CreolePhotoSelection

Swift
1. LimPicker (Similar to WhatsApp's image picker)
2. RMImagePicker
3. DKImagePickerController
4. BSImagePicker
5. Fusuma(Instagram like image selector)
6. YangMingShan(Yahoo like image selector)
7. NohanaImagePicker
8. ImagePicker
9. OpalImagePicker
10. TLPhotoPicker
11. AssetsPickerViewController
12. Alerts-and-pickers/Telegram Picker

Thanx to @androidbloke,
I have added some library that I know for multiple image picker in swift.
Will update list as I find new ones.
Thank You.

Do standard windows .ini files allow comments?

USE A SEMI-COLON AT BEGINING OF LINE --->> ; <<---

Ex.

; last modified 1 April 2001 by John Doe
[owner]
name=John Doe
organization=Acme Widgets Inc.

Android Studio says "cannot resolve symbol" but project compiles

When i lived to this problem(red color codes but they work correctly) in my project;

As first, i made it that (File -> Indicate Cashes) --> (Invalidate and Restart).

As last, i resync my build.gradle file in my app. After problem was resolved.

Simplest way to form a union of two lists

If it is two IEnumerable lists you can't use AddRange, but you can use Concat.

IEnumerable<int> first = new List<int>{1,1,2,3,5};
IEnumerable<int> second = new List<int>{8,13,21,34,55};

var allItems = first.Concat(second);
// 1,1,2,3,5,8,13,21,34,55

How to modify a text file?

Depends on what you want to do. To append you can open it with "a":

 with open("foo.txt", "a") as f:
     f.write("new line\n")

If you want to preprend something you have to read from the file first:

with open("foo.txt", "r+") as f:
     old = f.read() # read everything in the file
     f.seek(0) # rewind
     f.write("new line\n" + old) # write the new line before

Output data with no column headings using PowerShell

First we grab the command output, then wrap it and select one of its properties. There is only one and its "Name" which is what we want. So we select the groups property with ".name" then output it.

to text file

 (Get-ADGroupMember 'Domain Admins' |Select name).name | out-file Admins1.txt

to csv

(Get-ADGroupMember 'Domain Admins' |Select name).name | export-csv -notypeinformation "Admins1.csv"

How can I create an editable dropdownlist in HTML?

Simple HTML + Javascript approach without CSS

_x000D_
_x000D_
function editDropBox() {_x000D_
    var cSelect = document.getElementById('changingList');_x000D_
_x000D_
    var optionsSavehouse = [];_x000D_
    if(cSelect != null) {_x000D_
        var optionsArray = Array.from(cSelect.options);_x000D_
_x000D_
        var arrayLength = optionsArray.length;_x000D_
        for (var o = 0; o < arrayLength; o++) {_x000D_
            var option = optionsArray[o];_x000D_
            var oVal = option.value;_x000D_
_x000D_
            if(oVal > 0) {_x000D_
                var localParams = [];_x000D_
                localParams.push(option.text);_x000D_
                localParams.push(option.value);_x000D_
                //localParams.push(option.selected); // if needed_x000D_
                optionsSavehouse.push(localParams);_x000D_
            }_x000D_
        }_x000D_
    }_x000D_
_x000D_
    var hidden = ("<input id='hidden_select_options' type='hidden' value='" + JSON.stringify(optionsSavehouse) + "' />");_x000D_
_x000D_
    var cSpan = document.getElementById('changingSpan');_x000D_
    if(cSpan != null) {_x000D_
        cSpan.innerHTML = (hidden + "<input size='2' type='text' id='tempInput' name='fname' onchange='restoreDropBox()'>");_x000D_
    }_x000D_
}_x000D_
_x000D_
function restoreDropBox() {_x000D_
    var cSpan = document.getElementById('changingSpan');_x000D_
    var cInput = document.getElementById('tempInput');_x000D_
    var hOptions = document.getElementById('hidden_select_options');_x000D_
_x000D_
    if(cSpan != null) {_x000D_
_x000D_
        var optionsArray = [];_x000D_
_x000D_
        if(hOptions != null) {_x000D_
            optionsArray = JSON.parse(hOptions.value);_x000D_
        }_x000D_
_x000D_
        var selectList = "<select id='changingList'>\n";_x000D_
_x000D_
        var arrayLength = optionsArray.length;_x000D_
        for (var o = 0; o < arrayLength; o++) {_x000D_
            var option = optionsArray[o];_x000D_
            selectList += ("<option value='" + option[1] + "'>" + option[0] + "</option>\n");_x000D_
        }_x000D_
_x000D_
        if(cInput != null) {_x000D_
            selectList += ("<option value='-1' selected>" + cInput.value + "</option>\n");_x000D_
        }_x000D_
_x000D_
        selectList += ("<option value='-2' onclick='editDropBox()'>- Edit -</option>\n</select>");_x000D_
        cSpan.innerHTML = selectList;_x000D_
    }_x000D_
}
_x000D_
<span id="changingSpan">_x000D_
    <select id="changingList">_x000D_
        <option value="1">Apple</option>_x000D_
        <option value="2">Banana</option>_x000D_
        <option value="3">Cherry</option>_x000D_
        <option value="4">Dewberry</option>_x000D_
        <option onclick="editDropBox()" value="-2">- Edit -</option>_x000D_
    </select>_x000D_
</span>
_x000D_
_x000D_
_x000D_

Show Console in Windows Application?

Easiest way is to start a WinForms application, go to settings and change the type to a console application.

Two statements next to curly brace in an equation

You can try the cases env in amsmath.

\documentclass{article}
\usepackage{amsmath}

\begin{document}

\begin{equation}
  f(x)=\begin{cases}
    1, & \text{if $x<0$}.\\
    0, & \text{otherwise}.
  \end{cases}
\end{equation}

\end{document}

amsmath cases

Go to particular revision

Before executing this command keep in mind that it will leave you in detached head status

Use git checkout <sha1> to check out a particular commit.

Where <sha1> is the commit unique number that you can obtain with git log

Here are some options after you are in detached head status:

  • Copy the files or make the changes that you need to a folder outside your git folder, checkout the branch were you need them git checkout <existingBranch> and replace files
  • Create a new local branch git checkout -b <new_branch_name> <sha1>

How can I clear the Scanner buffer in Java?

Other people have suggested using in.nextLine() to clear the buffer, which works for single-line input. As comments point out, however, sometimes System.in input can be multi-line.

You can instead create a new Scanner object where you want to clear the buffer if you are using System.in and not some other InputStream.

in = new Scanner(System.in);

If you do this, don't call in.close() first. Doing so will close System.in, and so you will get NoSuchElementExceptions on subsequent calls to in.nextInt(); System.in probably shouldn't be closed during your program.

(The above approach is specific to System.in. It might not be appropriate for other input streams.)

If you really need to close your Scanner object before creating a new one, this StackOverflow answer suggests creating an InputStream wrapper for System.in that has its own close() method that doesn't close the wrapped System.in stream. This is overkill for simple programs, though.

Is there a way to get a collection of all the Models in your Rails app?

The Rails implements the method descendants, but models not necessarily ever inherits from ActiveRecord::Base, for example, the class that includes the module ActiveModel::Model will have the same behavior as a model, just doesn't will be linked to a table.

So complementing what says the colleagues above, the slightest effort would do this:

Monkey Patch of class Class of the Ruby:

class Class
  def extends? constant
    ancestors.include?(constant) if constant != self
  end
end

and the method models, including ancestors, as this:

The method Module.constants returns (superficially) a collection of symbols, instead of constants, so, the method Array#select can be substituted like this monkey patch of the Module:

class Module

  def demodulize
    splitted_trail = self.to_s.split("::")
    constant = splitted_trail.last

    const_get(constant) if defines?(constant)
  end
  private :demodulize

  def defines? constant, verbose=false
    splitted_trail = constant.split("::")
    trail_name = splitted_trail.first

    begin
      trail = const_get(trail_name) if Object.send(:const_defined?, trail_name)
      splitted_trail.slice(1, splitted_trail.length - 1).each do |constant_name|
        trail = trail.send(:const_defined?, constant_name) ? trail.const_get(constant_name) : nil
      end
      true if trail
    rescue Exception => e
      $stderr.puts "Exception recovered when trying to check if the constant \"#{constant}\" is defined: #{e}" if verbose
    end unless constant.empty?
  end

  def has_constants?
    true if constants.any?
  end

  def nestings counted=[], &block
    trail = self.to_s
    collected = []
    recursivityQueue = []

    constants.each do |const_name|
      const_name = const_name.to_s
      const_for_try = "#{trail}::#{const_name}"
      constant = const_for_try.constantize

      begin
        constant_sym = constant.to_s.to_sym
        if constant && !counted.include?(constant_sym)
          counted << constant_sym
          if (constant.is_a?(Module) || constant.is_a?(Class))
            value = block_given? ? block.call(constant) : constant
            collected << value if value

            recursivityQueue.push({
              constant: constant,
              counted: counted,
              block: block
            }) if constant.has_constants?
          end
        end
      rescue Exception
      end

    end

    recursivityQueue.each do |data|
      collected.concat data[:constant].nestings(data[:counted], &data[:block])
    end

    collected
  end

end

Monkey patch of String.

class String
  def constantize
    if Module.defines?(self)
      Module.const_get self
    else
      demodulized = self.split("::").last
      Module.const_get(demodulized) if Module.defines?(demodulized)
    end
  end
end

And, finally, the models method

def models
  # preload only models
  application.config.eager_load_paths = model_eager_load_paths
  application.eager_load!

  models = Module.nestings do |const|
    const if const.is_a?(Class) && const != ActiveRecord::SchemaMigration && (const.extends?(ActiveRecord::Base) || const.include?(ActiveModel::Model))
  end
end

private

  def application
    ::Rails.application
  end

  def model_eager_load_paths
    eager_load_paths = application.config.eager_load_paths.collect do |eager_load_path|
      model_paths = application.config.paths["app/models"].collect do |model_path|
        eager_load_path if Regexp.new("(#{model_path})$").match(eager_load_path)
      end
    end.flatten.compact
  end

MySQL LIMIT on DELETE statement

Use row_count - your_desired_offset

So if we had 10 rows and want to offset 3

 10 - 3 = 7

Now the query delete from table where this = that order asc limit 7 keeps the last 3, and order desc to keep the first 3:

$row_count - $offset = $limit

Delete from table where entry = criteria order by ts asc limit $limit

Swing JLabel text change on the running application

Use setText(str) method of JLabel to dynamically change text displayed. In actionPerform of button write this:

jLabel.setText("new Value");

A simple demo code will be:

    JFrame frame = new JFrame("Demo");
    frame.setLayout(new BorderLayout());
    frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    frame.setSize(250,100);

    final JLabel label = new JLabel("flag");
    JButton button = new JButton("Change flag");
    button.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent arg0) {
            label.setText("new value");
        }
    });

    frame.add(label, BorderLayout.NORTH);
    frame.add(button, BorderLayout.CENTER);
    frame.setVisible(true);

Class constants in python

You can get to SIZES by means of self.SIZES (in an instance method) or cls.SIZES (in a class method).

In any case, you will have to be explicit about where to find SIZES. An alternative is to put SIZES in the module containing the classes, but then you need to define all classes in a single module.

Excel add one hour

This may help you as well. This is a conditional statement that will fill the cell with a default date if it is empty but will subtract one hour if it is a valid date/time and put it into the cell.

=IF((Sheet1!C4)="",DATE(1999,1,1),Sheet1!C4-TIME(1,0,0))

You can also substitute TIME with DATE to add or subtract a date or time.

How can I make SQL case sensitive string comparison on MySQL?

mysql is not case sensitive by default, try changing the language collation to latin1_general_cs

CSS background-image not working

 <span class="btn-pTool">
 <a class="btn-pToolName" href="#"></a>
 </span>

That's empty. Try adding a non breaking space to give the link and span some contents:

 <span class="btn-pTool">
 <a class="btn-pToolName" href="#">&nbsp;</a>
 </span>

It's also worth noting that the CSS spec says that you can't give a span a background image because spans are not block elements. Put the background image code in the div's class style, or use <p> instead of <span>. Some browsers might let you put a background in a span, but not all will (perhaps older versions of IE).

Description Box using "onmouseover"

Assuming popup is the ID of your "description box":

HTML

<div id="parent"> <!-- This is the main container, to mouse over -->
<div id="popup" style="display: none">description text here</div>
</div>

JavaScript

var e = document.getElementById('parent');
e.onmouseover = function() {
  document.getElementById('popup').style.display = 'block';
}
e.onmouseout = function() {
  document.getElementById('popup').style.display = 'none';
}

Alternatively you can get rid of JavaScript entirely and do it just with CSS:

CSS

#parent #popup {
  display: none;
}

#parent:hover #popup {
  display: block;
}

Spring MVC Missing URI template variable

This error may happen when mapping variables you defined in REST definition do not match with @PathVariable names.

Example: Suppose you defined in the REST definition

@GetMapping(value = "/{appId}", produces = "application/json", consumes = "application/json")

Then during the definition of the function, it should be

public ResponseEntity<List> getData(@PathVariable String appId)

This error may occur when you use any other variable other than defined in the REST controller definition with @PathVariable. Like, the below code will raise the error as ID is different than appId variable name:

public ResponseEntity<List> getData(@PathVariable String ID)

How to delete a file from SD card?

File filedel = new File("/storage/sdcard0/Baahubali.mp3");
boolean deleted1 = filedel.delete();

Or, Try This:

String del="/storage/sdcard0/Baahubali.mp3";
File filedel2 = new File(del);
boolean deleted1 = filedel2.delete();

MySQL order by before group by

Your solution makes use of an extension to GROUP BY clause that permits to group by some fields (in this case, just post_author):

GROUP BY wp_posts.post_author

and select nonaggregated columns:

SELECT wp_posts.*

that are not listed in the group by clause, or that are not used in an aggregate function (MIN, MAX, COUNT, etc.).

Correct use of extension to GROUP BY clause

This is useful when all values of non-aggregated columns are equal for every row.

For example, suppose you have a table GardensFlowers (name of the garden, flower that grows in the garden):

INSERT INTO GardensFlowers VALUES
('Central Park',       'Magnolia'),
('Hyde Park',          'Tulip'),
('Gardens By The Bay', 'Peony'),
('Gardens By The Bay', 'Cherry Blossom');

and you want to extract all the flowers that grows in a garden, where multiple flowers grow. Then you have to use a subquery, for example you could use this:

SELECT GardensFlowers.*
FROM   GardensFlowers
WHERE  name IN (SELECT   name
                FROM     GardensFlowers
                GROUP BY name
                HAVING   COUNT(DISTINCT flower)>1);

If you need to extract all the flowers that are the only flowers in the garder instead, you could just change the HAVING condition to HAVING COUNT(DISTINCT flower)=1, but MySql also allows you to use this:

SELECT   GardensFlowers.*
FROM     GardensFlowers
GROUP BY name
HAVING   COUNT(DISTINCT flower)=1;

no subquery, not standard SQL, but simpler.

Incorrect use of extension to GROUP BY clause

But what happens if you SELECT non-aggregated columns that are non equal for every row? Which is the value that MySql chooses for that column?

It looks like MySql always chooses the FIRST value it encounters.

To make sure that the first value it encounters is exactly the value you want, you need to apply a GROUP BY to an ordered query, hence the need to use a subquery. You can't do it otherwise.

Given the assumption that MySql always chooses the first row it encounters, you are correcly sorting the rows before the GROUP BY. But unfortunately, if you read the documentation carefully, you'll notice that this assumption is not true.

When selecting non-aggregated columns that are not always the same, MySql is free to choose any value, so the resulting value that it actually shows is indeterminate.

I see that this trick to get the first value of a non-aggregated column is used a lot, and it usually/almost always works, I use it as well sometimes (at my own risk). But since it's not documented, you can't rely on this behaviour.

This link (thanks ypercube!) GROUP BY trick has been optimized away shows a situation in which the same query returns different results between MySql and MariaDB, probably because of a different optimization engine.

So, if this trick works, it's just a matter of luck.

The accepted answer on the other question looks wrong to me:

HAVING wp_posts.post_date = MAX(wp_posts.post_date)

wp_posts.post_date is a non-aggregated column, and its value will be officially undetermined, but it will likely be the first post_date encountered. But since the GROUP BY trick is applied to an unordered table, it is not sure which is the first post_date encountered.

It will probably returns posts that are the only posts of a single author, but even this is not always certain.

A possible solution

I think that this could be a possible solution:

SELECT wp_posts.*
FROM   wp_posts
WHERE  id IN (
  SELECT max(id)
  FROM wp_posts
  WHERE (post_author, post_date) = (
    SELECT   post_author, max(post_date)
    FROM     wp_posts
    WHERE    wp_posts.post_status='publish'
             AND wp_posts.post_type='post'
    GROUP BY post_author
  ) AND wp_posts.post_status='publish'
    AND wp_posts.post_type='post'
  GROUP BY post_author
)

On the inner query I'm returning the maximum post date for every author. I'm then taking into consideration the fact that the same author could theorically have two posts at the same time, so I'm getting only the maximum ID. And then I'm returning all rows that have those maximum IDs. It could be made faster using joins instead of IN clause.

(If you're sure that ID is only increasing, and if ID1 > ID2 also means that post_date1 > post_date2, then the query could be made much more simple, but I'm not sure if this is the case).

How to sort findAll Doctrine's method?

It's useful to look at source code sometimes.

For example findAll implementation is very simple (vendor/doctrine/orm/lib/Doctrine/ORM/EntityRepository.php):

public function findAll()
{
    return $this->findBy(array());
}

So we look at findBy and find what we need (orderBy)

public function findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)

Comparing two columns, and returning a specific adjacent cell in Excel

Here is what needs to go in D1: =VLOOKUP(C1, $A$1:$B$4, 2, FALSE)

You should then be able to copy this down to the rest of column D.

What are the differences between Mustache.js and Handlebars.js?

NOTE: This answer is outdated. It was true at the time it was posted, but no longer is.

Mustache has interpreters in many languages, while Handlebars is Javascript only.

HTTP Error 500.19 and error code : 0x80070021

In my case, there were rules for IIS URL Rewrite module but I didn't have that module installed. You should check your web.config if there are any modules included but not installed.

How to convert a List<String> into a comma separated string without iterating List explicitly

Java 8 solution if it's not a collection of strings:

{Any collection}.stream()
    .collect(StringBuilder::new, StringBuilder::append, StringBuilder::append)
    .toString()

Using Environment Variables with Vue.js

If you are using Vue cli 3, only variables that start with VUE_APP_ will be loaded.

In the root create a .env file with:

VUE_APP_ENV_VARIABLE=value

And, if it's running, you need to restart serve so that the new env vars can be loaded.

With this, you will be able to use process.env.VUE_APP_ENV_VARIABLE in your project (.js and .vue files).

Update

According to @ali6p, with Vue Cli 3, isn't necessary to install dotenv dependency.

How to change the JDK for a Jenkins job?

For those who couldn't find this option. Install JDK Parameter Plugin

List of tables, db schema, dump etc using the Python sqlite3 API

Here's a short and simple python program to print out the table names and the column names for those tables (python 2. python 3 follows).

import sqlite3

db_filename = 'database.sqlite'
newline_indent = '\n   '

db=sqlite3.connect(db_filename)
db.text_factory = str
cur = db.cursor()

result = cur.execute("SELECT name FROM sqlite_master WHERE type='table';").fetchall()
table_names = sorted(zip(*result)[0])
print "\ntables are:"+newline_indent+newline_indent.join(table_names)

for table_name in table_names:
    result = cur.execute("PRAGMA table_info('%s')" % table_name).fetchall()
    column_names = zip(*result)[1]
    print ("\ncolumn names for %s:" % table_name)+newline_indent+(newline_indent.join(column_names))

db.close()
print "\nexiting."

(EDIT: I have been getting periodic vote-ups on this, so here is the python3 version for people who are finding this answer)

import sqlite3

db_filename = 'database.sqlite'
newline_indent = '\n   '

db=sqlite3.connect(db_filename)
db.text_factory = str
cur = db.cursor()

result = cur.execute("SELECT name FROM sqlite_master WHERE type='table';").fetchall()
table_names = sorted(list(zip(*result))[0])
print ("\ntables are:"+newline_indent+newline_indent.join(table_names))

for table_name in table_names:
    result = cur.execute("PRAGMA table_info('%s')" % table_name).fetchall()
    column_names = list(zip(*result))[1]
    print (("\ncolumn names for %s:" % table_name)
           +newline_indent
           +(newline_indent.join(column_names)))

db.close()
print ("\nexiting.")

How to embed a PDF?

FlexPaper is probably still the best viewer out there to be used for this kind of stuff. It has a traditional viewer and a more turn page / flip book style viewer both in flash and html5

http://flexpaper.devaldi.com

Force Java timezone as GMT/UTC

tl;dr

String sql = "SELECT CURRENT_TIMESTAMP ;
…
OffsetDateTime odt = myResultSet.getObject( 1 , OffsetDateTime.class ) ;

Avoid depending on host OS or JVM for default time zone

I recommend you write all your code to explicitly state the desired/expected time zone. You need not depend on the JVM’s current default time zone. And be aware that the JVM’s current default time zone can change at any moment during runtime, with any code in any thread of any app calling TimeZone.setDefault. Such a call affects all apps within that JVM immediately.

java.time

Some of the other Answers were correct, but are now outmoded. The terrible date-time classes bundled with the earliest versions of Java were flawed, written by people who did not understand the complexities and subtleties of date-time handling.

The legacy date-time classes have been supplanted by the java.time classes defined in JSR 310.

To represent a time zone, use ZoneId. To represent an offset-from-UTC, use ZoneOffset. An offset is merely a number of hour-minutes-seconds ahead or behind the prime meridian. A time zone is much more. A time zone is a history of the past, present, and future changes to the offset used by the people of a particular region.

I need to force any time related operations to GMT/UTC

For an offset of zero hours-minutes-seconds, use the constant ZoneOffset.UTC.

Instant

To capture the current moment in UTC, use an Instant. This class represent a moment in UTC, always in UTC by definition.

Instant instant = Instant.now() ;  // Capture current moment in UTC.

ZonedDateTime

To see that same moment through the wall-clock time used by the people of a particular region, adjust into a time zone. Same moment, same point on the timeline, different wall-clock time.

ZoneId z = ZoneId.of( "Asia/Tokyo" ) ;
ZonedDateTime zdt = instant.atZone( z ) ;

Database

You mention a database.

To retrieve a moment from the database, your column should be of a data type akin to the SQL-standard TIMESTAMP WITH TIME ZONE. Retrieve an object rather than a string. In JDBC 4.2 and later, we can exchange java.time objects with the database. The OffsetDateTime is required by JDBC, while Instant & ZonedDateTime are optional.

OffsetDateTime odt = myResultSet.getObject( … , OffsetDateTime.class ) ;

In most databases and drivers, I would guess that you will get the moment as seen in UTC. But if not, you can adjust in either of two ways:

  • Extract a Instant: odt.toInstant()
  • Adjust from the given offset to an offset of zero: OffsetDateTime odtUtc = odt.withOffsetSameInstant( ZoneOffset.UTC ) ;`.

Table of date-time types in Java (both legacy and modern) and in standard SQL


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

Saving the PuTTY session logging

To set permanent PuTTY session parameters do:

  1. Create sessions in PuTTY. Name it as "MyskinPROD"

  2. Configure the path for this session to point to "C:\dir\&Y&M&D&T_&H_putty.log".

  3. Create a Windows "Shortcut" to C:...\Putty.exe.

  4. Open "Shortcut" Properties and append "Target" line with parameters as shown below:

    "C:\Program Files (x86)\UTL\putty.exe" -ssh -load MyskinPROD user@ServerIP -pw password
    

Now, your PuTTY shortcut will bring in the "MyskinPROD" configuration every time you open the shortcut.

Check the screenshots and details on how I did it in my environment:

http://www.evernote.com/shard/s184/sh/93ebf08f-fde2-4dad-bccf-961c98fb614b/983d2ff8f2d1e6184318825d68b0b829

C# declare empty string array

If you must create an empty array you can do this:

string[] arr = new string[0];

If you don't know about the size then You may also use List<string> as well like

var valStrings = new List<string>();

// do stuff...

string[] arrStrings = valStrings.ToArray();

Deprecation warning in Moment.js - Not in a recognized ISO format

Add the following line in your code to Suppress the warnings:

const moment = require('moment');

moment.suppressDeprecationWarnings = true;

Is `shouldOverrideUrlLoading` really deprecated? What can I use instead?

The version I'm using I think is the good one, since is the exact same as the Android Developer Docs, except for the name of the string, they used "view" and I used "webview", for the rest is the same

No, it is not.

The one that is new to the N Developer Preview has this method signature:

public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request)

The one that is supported by all Android versions, including N, has this method signature:

public boolean shouldOverrideUrlLoading(WebView view, String url)

So why should I do to make it work on all versions?

Override the deprecated one, the one that takes a String as the second parameter.

How to create an object property from a variable value in JavaScript?

Dot notation and the properties are equivalent. So you would accomplish like so:

var myObj = new Object;
var a = 'string1';
myObj[a] = 'whatever';
alert(myObj.string1)

(alerts "whatever")

Is there a way to link someone to a YouTube Video in HD 1080p quality?

Yes there is:

https://www.youtube.com/embed/kObNpTFPV5c?vq=hd1440
https://www.youtube.com/embed/kObNpTFPV5c?vq=hd1080
etc...

Options are:

Code for 1440: vq=hd1440
Code for 1080: vq=hd1080
Code for 720: vq=hd720
Code for 480p: vq=large
Code for 360p: vq=medium
Code for 240p: vq=small

UPDATE
As of 10 of April 2018, this code still works.
Some users reported "not working", if it doesn't work for you, please read below:

From what I've learned, the problem is related with network speed and or screen size.
When YT player starts, it collects the network speed, screen and player sizes, among other information, if the connection is slow or the screen/player size smaller than the quality requested(vq=), a lower quality video is displayed despite the option selected on vq=.

Also make sure you read the comments below.

Connect to Amazon EC2 file directory using Filezilla and SFTP

Just one minor note to the well explained accepted answer of Yasitha Chinthaka:

Note: FileZilla automatically figures out which key to use. You do not need to specify the key after importing it as described above.

In my case I already had other 5 ppks from other instances that I was using in the past (with the ppk of the new instance being at the bottom of that list). I added the new ppk of my new instance, and it wouldn't let me connect to it. The error message: too many tries / attempts.

After I deleted the unused ppks, I was finally able to login to the instance.

So no, Filezilla is not that smart ;-)

Ruby on Rails - Import Data from a CSV file

I know it's old question but it still in first 10 links in google.

It is not very efficient to save rows one-by-one because it cause database call in the loop and you better avoid that, especially when you need to insert huge portions of data.

It's better (and significantly faster) to use batch insert.

INSERT INTO `mouldings` (suppliers_code, name, cost)
VALUES
    ('s1', 'supplier1', 1.111), 
    ('s2', 'supplier2', '2.222')

You can build such a query manually and than do Model.connection.execute(RAW SQL STRING) (not recomended) or use gem activerecord-import (it was first released on 11 Aug 2010) in this case just put data in array rows and call Model.import rows

refer to gem docs for details

How to set bot's status

Simple way to initiate the message on startup:

bot.on('ready', () => {
    bot.user.setStatus('available')
    bot.user.setPresence({
        game: {
            name: 'with depression',
            type: "STREAMING",
            url: "https://www.twitch.tv/monstercat"
        }
    });
});

You can also just declare it elsewhere after startup, to change the message as needed:

bot.user.setPresence({ game: { name: 'with depression', type: "streaming", url: "https://www.twitch.tv/monstercat"}}); 

How to create a JQuery Clock / Timer

    var timeInterval = 5;
    var blinkTime = 1;
    var open_signal = 'signal1';
    var total_signal = 1;

    $(document).ready(function () {
        for (var i = 1; i <= total_signal; i++) {
            var timer = (i == 1) ? timeInterval : (timeInterval * (i - 1));

            var str_html = '<div id="signal' + i + '">' +
                           '<span class="float_left">Signal ' + i + ' : </span>' +
                           '<div class="red float_left"></div>' +
                           '<div class="yellow float_left"></div>' +
                           '<div class="green float_left"></div>' +
                           '<div class="timer float_left">' + timer + '</div>' +
                           '<div style="clear: both;"></div>' +
                           '</div><div class="div_separate"></div>';

            $('.div_demo').append(str_html);
        }

        $('.div_demo .green').eq(0).css('background-color', 'green');
        $('.div_demo .red').css('background-color', 'red');
        $('.div_demo .red').eq(0).css('background-color', 'white');

        setInterval(function () {
            manageSignals();
        }, 1000);
    });

    function manageSignals() {
        var obj_timer = {};

        var temp_i = parseInt(open_signal.substr(6));
        if ($('#' + open_signal + ' .timer').html() == '0')
            open_signal = (temp_i == total_signal) ? 'signal1' : 'signal' + (temp_i + 1);

        for (var i = 1; i <= total_signal; i++) {
            var next_signal = (i == total_signal) ? 'signal1' : 'signal' + (i + 1);

            obj_timer['signal' + i] = parseInt($('#signal' + i + ' .timer').html()) - 1;

            if (obj_timer['signal' + i] == -1 && open_signal == next_signal && total_signal!=1) {
                obj_timer['signal' + i] = (timeInterval * (total_signal - 1)) - 1;

                $('#signal' + i + ' .red').css('background-color', 'red');
                $('#signal' + i + ' .yellow').css('background-color', 'white');
            }
            else if (obj_timer['signal' + i] == -1 && open_signal == 'signal' + i) {
                obj_timer['signal' + i] = (timeInterval - 1);

                $('#signal' + i + ' .red').css('background-color', 'white');
                $('#signal' + i + ' .yellow').css('background-color', 'white');
                $('#signal' + i + ' .green').css('background-color', 'green');
            }
            else if (obj_timer['signal' + i] == blinkTime && open_signal == 'signal' + i) {
                $('#signal' + i + ' .yellow').css('background-color', 'yellow');
                $('#signal' + i + ' .green').css('background-color', 'white');
            }

            $('#signal' + i + ' .timer').html(obj_timer['signal' + i]);
        }
    }
</script>

How to copy data from one table to another new table in MySQL?

INSERT INTO Table1(Column1,Column2..) SELECT Column1,Column2.. FROM Table2 [WHERE <condition>]

Parse rfc3339 date strings in Python?

You can use dateutil.parser.parse (install with python -m pip install python-dateutil) to parse strings into datetime objects.

dateutil.parser.parse will attempt to guess the format of your string, if you know the exact format in advance then you can use datetime.strptime which you supply a format string to (see Brent Washburne's answer).

from dateutil.parser import parse

a = "2012-10-09T19:00:55Z"

b = parse(a)

print(b.weekday())
# 1 (equal to a Tuesday)

Is there a good reason I see VARCHAR(255) used so often (as opposed to another length)?

An unsigned 1 byte number can contain the range [0-255] inclusive. So when you see 255, it is mostly because programmers think in base 10 (get the joke?) :)

Actually, for a while, 255 was the largest size you could give a VARCHAR in MySQL, and there are advantages to using VARCHAR over TEXT with indexing and other issues.

How to select id with max date group by category in PostgreSQL?

Try this one:

SELECT t1.* FROM Table1 t1
JOIN 
(
   SELECT category, MAX(date) AS MAXDATE
   FROM Table1
   GROUP BY category
) t2
ON T1.category = t2.category
AND t1.date = t2.MAXDATE

See this SQLFiddle

Reading binary file and looping over each byte

if you are looking for something speedy, here's a method I've been using that's worked for years:

from array import array

with open( path, 'rb' ) as file:
    data = array( 'B', file.read() ) # buffer the file

# evaluate it's data
for byte in data:
    v = byte # int value
    c = chr(byte)

if you want to iterate chars instead of ints, you can simply use data = file.read(), which should be a bytes() object in py3.

Get a Div Value in JQuery

if you div looks like this:

<div id="someId">Some Value</div>

you could retrieve it with jquery like this:

$('#someId').text()

The specified child already has a parent. You must call removeView() on the child's parent first

In my case the problem was I was trying to add same view multiple times to linear layout

View childView = LayoutInflater.from(context).inflate(R.layout.lay_progressheader, parentLayout,false);

 for (int i = 1; i <= totalCount; i++) {

     parentLayout.addView(childView);

 }

just initialize view every time to fix the issue

 for (int i = 1; i <= totalCount; i++) {

     View childView = LayoutInflater.from(context).inflate(R.layout.lay_progressheader, parentLayout,false);

      parentLayout.addView(childView);

 }

Resolving ORA-4031 "unable to allocate x bytes of shared memory"

Don't forget about fragmentation. If you have a lot of traffic, your pools can be fragmented and even if you have several MB free, there could be no block larger than 4KB. Check size of largest free block with a query like:

 select
  '0 (<140)' BUCKET, KSMCHCLS, KSMCHIDX,
  10*trunc(KSMCHSIZ/10) "From",
  count(*) "Count" ,
  max(KSMCHSIZ) "Biggest",
  trunc(avg(KSMCHSIZ)) "AvgSize",
  trunc(sum(KSMCHSIZ)) "Total"
from
  x$ksmsp
where
  KSMCHSIZ<140
and
  KSMCHCLS='free'
group by
  KSMCHCLS, KSMCHIDX, 10*trunc(KSMCHSIZ/10)
UNION ALL
select
  '1 (140-267)' BUCKET,
  KSMCHCLS,
  KSMCHIDX,
  20*trunc(KSMCHSIZ/20) ,
  count(*) ,
  max(KSMCHSIZ) ,
  trunc(avg(KSMCHSIZ)) "AvgSize",
  trunc(sum(KSMCHSIZ)) "Total"
from
  x$ksmsp
where
  KSMCHSIZ between 140 and 267
and
  KSMCHCLS='free'
group by
  KSMCHCLS, KSMCHIDX, 20*trunc(KSMCHSIZ/20)
UNION ALL
select
  '2 (268-523)' BUCKET,
  KSMCHCLS,
  KSMCHIDX,
  50*trunc(KSMCHSIZ/50) ,
  count(*) ,
  max(KSMCHSIZ) ,
  trunc(avg(KSMCHSIZ)) "AvgSize",
  trunc(sum(KSMCHSIZ)) "Total"
from
  x$ksmsp
where
  KSMCHSIZ between 268 and 523
and
  KSMCHCLS='free'
group by
  KSMCHCLS, KSMCHIDX, 50*trunc(KSMCHSIZ/50)
UNION ALL
select
  '3-5 (524-4107)' BUCKET,
  KSMCHCLS,
  KSMCHIDX,
  500*trunc(KSMCHSIZ/500) ,
  count(*) ,
  max(KSMCHSIZ) ,
  trunc(avg(KSMCHSIZ)) "AvgSize",
  trunc(sum(KSMCHSIZ)) "Total"
from
  x$ksmsp
where
  KSMCHSIZ between 524 and 4107
and
  KSMCHCLS='free'
group by
  KSMCHCLS, KSMCHIDX, 500*trunc(KSMCHSIZ/500)
UNION ALL
select
  '6+ (4108+)' BUCKET,
  KSMCHCLS,
  KSMCHIDX,
  1000*trunc(KSMCHSIZ/1000) ,
  count(*) ,
  max(KSMCHSIZ) ,
  trunc(avg(KSMCHSIZ)) "AvgSize",
  trunc(sum(KSMCHSIZ)) "Total"
from
  x$ksmsp
where
  KSMCHSIZ >= 4108
and
  KSMCHCLS='free'
group by
  KSMCHCLS, KSMCHIDX, 1000*trunc(KSMCHSIZ/1000);

Code from

What does "for" attribute do in HTML <label> tag?

The for attribute associates the label with a control element, as defined in the description of label in the HTML 4.01 spec. This implies, among other things, that when the label element receives focus (e.g. by being clicked on), it passes the focus on to its associated control. The association between a label and a control may also be used by speech-based user agents, which may give the user a way to ask what the associated label is, when dealing with a control. (The association may not be as obvious as in visual rendering.)

In the first example in the question (without the for), the use of label markup has no logical or functional implication – it’s useless, unless you do something with it in CSS or JavaScript.

HTML specifications do not make it mandatory to associate labels with controls, but Web Content Accessibility Guidelines (WCAG) 2.0 do. This is described in the technical document H44: Using label elements to associate text labels with form controls, which also explains that the implicit association (by nesting e.g. input inside label) is not as widely supported as the explicit association via for and id attributes,

How do I instantiate a JAXBElement<String> object?

I don't know why you think there's no constructor. See the API.

How do I concatenate multiple C++ strings on one line?

you can also "extend" the string class and choose the operator you prefer ( <<, &, |, etc ...)

Here is the code using operator<< to show there is no conflict with streams

note: if you uncomment s1.reserve(30), there is only 3 new() operator requests (1 for s1, 1 for s2, 1 for reserve ; you can't reserve at constructor time unfortunately); without reserve, s1 has to request more memory as it grows, so it depends on your compiler implementation grow factor (mine seems to be 1.5, 5 new() calls in this example)

namespace perso {
class string:public std::string {
public:
    string(): std::string(){}

    template<typename T>
    string(const T v): std::string(v) {}

    template<typename T>
    string& operator<<(const T s){
        *this+=s;
        return *this;
    }
};
}

using namespace std;

int main()
{
    using string = perso::string;
    string s1, s2="she";
    //s1.reserve(30);
    s1 << "no " << "sunshine when " << s2 << '\'' << 's' << " gone";
    cout << "Aint't "<< s1 << " ..." <<  endl;

    return 0;
}

Dump Mongo Collection into JSON format

Mongo includes a mongoexport utility (see docs) which can dump a collection. This utility uses the native libmongoclient and is likely the fastest method.

mongoexport -d <database> -c <collection_name>

Also helpful:

-o: write the output to file, otherwise standard output is used (docs)

--jsonArray: generates a valid json document, instead of one json object per line (docs)

--pretty: outputs formatted json (docs)

What are the different types of keys in RDBMS?

Partial Key:

It is a set of attributes that can uniquely identify weak entities and that are related to same owner entity. It is sometime called as Discriminator.

Alternate Key:

All Candidate Keys excluding the Primary Key are known as Alternate Keys.

Artificial Key:

If no obvious key, either stand alone or compound is available, then the last resort is to simply create a key, by assigning a unique number to each record or occurrence. Then this is known as developing an artificial key.

Compound Key:

If no single data element uniquely identifies occurrences within a construct, then combining multiple elements to create a unique identifier for the construct is known as creating a compound key.

Natural Key:

When one of the data elements stored within a construct is utilized as the primary key, then it is called the natural key.

printf format specifiers for uint32_t and size_t

Sounds like you're expecting size_t to be the same as unsigned long (possibly 64 bits) when it's actually an unsigned int (32 bits). Try using %zu in both cases.

I'm not entirely certain though.

What is the difference between "px", "dip", "dp" and "sp"?

Difference between dp and sp units mentioned as "user's font size preference" by the answers copied from official documentation can be seen at run time by changing Settings->Accessibility->Large Text option.

Large Text option forces text to become 1.3 times bigger.

private static final float LARGE_FONT_SCALE = 1.3f;

This might be well of course vendor dependent since it lies in packages/apps/Settings.

Strange Characters in database text: Ã, Ã, ¢, â‚ €,

I encountered today quite a similar problem : mysqldump dumped my utf-8 base encoding utf-8 diacritic characters as two latin1 characters, although the file itself is regular utf8.

For example : "é" was encoded as two characters "é". These two characters correspond to the utf8 two bytes encoding of the letter but it should be interpreted as a single character.

To solve the problem and correctly import the database on another server, I had to convert the file using the ftfy (stands for "Fixes Text For You). (https://github.com/LuminosoInsight/python-ftfy) python library. The library does exactly what I expect : transform bad encoded utf-8 to correctly encoded utf-8.

For example : This latin1 combination "é" is turned into an "é".

ftfy comes with a command line script but it transforms the file so it can not be imported back into mysql.

I wrote a python3 script to do the trick :

#!/usr/bin/python3
# coding: utf-8

import ftfy

# Set input_file
input_file = open('mysql.utf8.bad.dump', 'r', encoding="utf-8")
# Set output file
output_file = open ('mysql.utf8.good.dump', 'w')

# Create fixed output stream
stream = ftfy.fix_file(
    input_file,
    encoding=None,
    fix_entities='auto', 
    remove_terminal_escapes=False, 
    fix_encoding=True, 
    fix_latin_ligatures=False, 
    fix_character_width=False, 
    uncurl_quotes=False, 
    fix_line_breaks=False, 
    fix_surrogates=False, 
    remove_control_chars=False, 
    remove_bom=False, 
    normalization='NFC'
)

# Save stream to output file
stream_iterator = iter(stream)
while stream_iterator:
    try:
        line = next(stream_iterator)
        output_file.write(line)
    except StopIteration:
        break

How to convert Set<String> to String[]?

Use the Set#toArray(IntFunction<T[]>) method taking an IntFunction as generator.

String[] GPXFILES1 = myset.toArray(String[]::new);

If you're not on Java 11 yet, then use the Set#toArray(T[]) method taking a typed array argument of the same size.

String[] GPXFILES1 = myset.toArray(new String[myset.size()]);

While still not on Java 11, and you can't guarantee that myset is unmodifiable at the moment of conversion to array, then better specify an empty typed array.

String[] GPXFILES1 = myset.toArray(new String[0]);

PostgreSQL INSERT ON CONFLICT UPDATE (upsert) use all excluded values

Postgres hasn't implemented an equivalent to INSERT OR REPLACE. From the ON CONFLICT docs (emphasis mine):

It can be either DO NOTHING, or a DO UPDATE clause specifying the exact details of the UPDATE action to be performed in case of a conflict.

Though it doesn't give you shorthand for replacement, ON CONFLICT DO UPDATE applies more generally, since it lets you set new values based on preexisting data. For example:

INSERT INTO users (id, level)
VALUES (1, 0)
ON CONFLICT (id) DO UPDATE
SET level = users.level + 1;

How would you count occurrences of a string (actually a char) within a string?

private int CountWords(string text, string word) {
    int count = (text.Length - text.Replace(word, "").Length) / word.Length;
    return count;
}

Because the original solution, was the fastest for chars, I suppose it will also be for strings. So here is my contribution.

For the context: I was looking for words like 'failed' and 'succeeded' in a log file.

Gr, Ben

What are the most widely used C++ vector/matrix math/linear algebra libraries, and their cost and benefit tradeoffs?

What about GLM?

It's based on the OpenGL Shading Language (GLSL) specification and released under the MIT license. Clearly aimed at graphics programmers

Getting number of days in a month

  int month = Convert.ToInt32(ddlMonth.SelectedValue);/*Store month Value From page*/
  int year = Convert.ToInt32(txtYear.Value);/*Store Year Value From page*/
  int days = System.DateTime.DaysInMonth(year, month); /*this will store no. of days for month, year that we store*/

declaring a priority_queue in c++ with a custom comparator

The third template parameter must be a class who has operator()(Node,Node) overloaded. So you will have to create a class this way:

class ComparisonClass {
    bool operator() (Node, Node) {
        //comparison code here
    }
};

And then you will use this class as the third template parameter like this:

priority_queue<Node, vector<Node>, ComparisonClass> q;

PHP simple foreach loop with HTML

This will work although when embedding PHP in HTML it is better practice to use the following form:

<table>
    <?php foreach($array as $key=>$value): ?>
    <tr>
        <td><?= $key; ?></td>
    </tr>
    <?php endforeach; ?>
</table>

You can find the doc for the alternative syntax on PHP.net

Python match a string with regex

You do not need regular expressions to check if a substring exists in a string.

line = 'This,is,a,sample,string'
result = bool('sample' in line) # returns True

If you want to know if a string contains a pattern then you should use re.search

line = 'This,is,a,sample,string'
result = re.search(r'sample', line) # finds 'sample'

This is best used with pattern matching, for example:

line = 'my name is bob'
result = re.search(r'my name is (\S+)', line) # finds 'bob'

Alternative to Intersect in MySQL

Microsoft SQL Server's INTERSECT "returns any distinct values that are returned by both the query on the left and right sides of the INTERSECT operand" This is different from a standard INNER JOIN or WHERE EXISTS query.

SQL Server

CREATE TABLE table_a (
    id INT PRIMARY KEY,
    value VARCHAR(255)
);

CREATE TABLE table_b (
    id INT PRIMARY KEY,
    value VARCHAR(255)
);

INSERT INTO table_a VALUES (1, 'A'), (2, 'B'), (3, 'B');
INSERT INTO table_b VALUES (1, 'B');

SELECT value FROM table_a
INTERSECT
SELECT value FROM table_b

value
-----
B

(1 rows affected)

MySQL

CREATE TABLE `table_a` (
  `id` INT NOT NULL AUTO_INCREMENT,
  `value` varchar(255),
  PRIMARY KEY (`id`)
) ENGINE=InnoDB;

CREATE TABLE `table_b` LIKE `table_a`;

INSERT INTO table_a VALUES (1, 'A'), (2, 'B'), (3, 'B');
INSERT INTO table_b VALUES (1, 'B');

SELECT value FROM table_a
INNER JOIN table_b
USING (value);

+-------+
| value |
+-------+
| B     |
| B     |
+-------+
2 rows in set (0.00 sec)

SELECT value FROM table_a
WHERE (value) IN
(SELECT value FROM table_b);

+-------+
| value |
+-------+
| B     |
| B     |
+-------+

With this particular question, the id column is involved, so duplicate values will not be returned, but for the sake of completeness, here's a MySQL alternative using INNER JOIN and DISTINCT:

SELECT DISTINCT value FROM table_a
INNER JOIN table_b
USING (value);

+-------+
| value |
+-------+
| B     |
+-------+

And another example using WHERE ... IN and DISTINCT:

SELECT DISTINCT value FROM table_a
WHERE (value) IN
(SELECT value FROM table_b);

+-------+
| value |
+-------+
| B     |
+-------+

How do I set default values for functions parameters in Matlab?

This is more or less lifted from the Matlab manual; I've only got passing experience...

function my_output = wave ( a, b, n, k, T, f, flag, varargin )
  optargin = numel(varargin);
  fTrue = inline('0');
  if optargin > 0
    fTrue = varargin{1};
  end
  % code ...
end

Change location of log4j.properties

Yes, define log4j.configuration property

java -Dlog4j.configuration=file:/path/to/log4j.properties myApp

Note, that property value must be a URL.

For more read section 'Default Initialization Procedure' in Log4j manual.

Font Awesome & Unicode

I got a simillary problem using unicode and fontawesome. when i wrote :

font-family: 'Font Awesome\ 5 Free';
content: "\f061"; /* FontAwesome Unicode */

On google chrome, a square appear instead of the icon. The new version of Font Awesome also requires

font-weight: 900;

That's work for me.

From : https://github.com/FortAwesome/Font-Awesome/issues/11946

Hope that's will help.

Check whether there is an Internet connection available on Flutter app

I made a base class for widget state

Usage instead of State<LoginPage> use BaseState<LoginPage> then just use the boolean variable isOnline

Text(isOnline ? 'is Online' : 'is Offline')

First, add connectivity plugin:

dependencies:
  connectivity: ^0.4.3+2

Then add the BaseState class

import 'dart:async';
import 'dart:io';
import 'package:flutter/services.dart';

import 'package:connectivity/connectivity.dart';
import 'package:flutter/widgets.dart';

/// a base class for any statful widget for checking internet connectivity
abstract class BaseState<T extends StatefulWidget> extends State {

  void castStatefulWidget();

  final Connectivity _connectivity = Connectivity();

  StreamSubscription<ConnectivityResult> _connectivitySubscription;

  /// the internet connectivity status
  bool isOnline = true;

  /// initialize connectivity checking
  /// Platform messages are asynchronous, so we initialize in an async method.
  Future<void> initConnectivity() async {
    // Platform messages may fail, so we use a try/catch PlatformException.
    try {
      await _connectivity.checkConnectivity();
    } on PlatformException catch (e) {
      print(e.toString());
    }

    // If the widget was removed from the tree while the asynchronous platform
    // message was in flight, we want to discard the reply rather than calling
    // setState to update our non-existent appearance.
    if (!mounted) {
      return;
    }

    await _updateConnectionStatus().then((bool isConnected) => setState(() {
          isOnline = isConnected;
        }));
  }

  @override
  void initState() {
    super.initState();
    initConnectivity();
    _connectivitySubscription = Connectivity()
        .onConnectivityChanged
        .listen((ConnectivityResult result) async {
      await _updateConnectionStatus().then((bool isConnected) => setState(() {
            isOnline = isConnected;
          }));
    });
  }

  @override
  void dispose() {
    _connectivitySubscription.cancel();
    super.dispose();
  }

  Future<bool> _updateConnectionStatus() async {
    bool isConnected;
    try {
      final List<InternetAddress> result =
          await InternetAddress.lookup('google.com');
      if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) {
        isConnected = true;
      }
    } on SocketException catch (_) {
      isConnected = false;
      return false;
    }
    return isConnected;
  }
}

And you need to cast the widget in your state like this

@override
  void castStatefulWidget() {
    // ignore: unnecessary_statements
    widget is StudentBoardingPage;
  }

How to convert a byte array to Stream

Easy, simply wrap a MemoryStream around it:

Stream stream = new MemoryStream(buffer);

Can't perform a React state update on an unmounted component

To remove - Can't perform a React state update on an unmounted component warning, use componentDidMount method under a condition and make false that condition on componentWillUnmount method. For example : -

class Home extends Component {
  _isMounted = false;

  constructor(props) {
    super(props);

    this.state = {
      news: [],
    };
  }

  componentDidMount() {
    this._isMounted = true;

    ajaxVar
      .get('https://domain')
      .then(result => {
        if (this._isMounted) {
          this.setState({
            news: result.data.hits,
          });
        }
      });
  }

  componentWillUnmount() {
    this._isMounted = false;
  }

  render() {
    ...
  }
}

Table Height 100% inside Div element

This is how you can do it-

HTML-

<div style="overflow:hidden; height:100%">
     <div style="float:left">a<br>b</div>
     <table cellpadding="0" cellspacing="0" style="height:100%;">     
          <tr><td>This is the content of a table that takes 100% height</td></tr>  
      </table>
 </div>

CSS-

html,body
{
    height:100%;
    background-color:grey;
}
table
{
    background-color:yellow;
}

See the DEMO

Update: Well, if you are not looking for applying 100% height to your parent containers, then here is a jQuery solution that should help you-

Demo-using jQuery

Script-

 $(document).ready(function(){
    var b= $(window).height(); //gets the window's height, change the selector if you are looking for height relative to some other element
    $("#tab").css("height",b);
});

Can't find @Nullable inside javax.annotation.*

I am using Guava which has annotation included:

(Gradle code )

compile 'com.google.guava:guava:23.4-jre'

npx command not found

Updating node helped me, whether that be from the command line or just re-downloading it from the web

How to select specific columns in laravel eloquent

You can use Table::select ('name', 'surname')->where ('id', 1)->get ().

Keep in mind that when selecting for only certain fields, you will have to make another query if you end up accessing those other fields later in the request (that may be obvious, just wanted to include that caveat). Including the id field is usually a good idea so laravel knows how to write back any updates you do to the model instance.

Creating a fixed sidebar alongside a centered Bootstrap 3 grid

As drew_w said, you can find a good example here.

HTML

<div id="wrapper">
    <div id="sidebar-wrapper">
        <ul class="sidebar-nav">
            <li class="sidebar-brand"><a href="#">Home</a></li>
            <li><a href="#">Another link</a></li>
            <li><a href="#">Next link</a></li>
            <li><a href="#">Last link</a></li>
        </ul>
    </div>
    <div id="page-content-wrapper">
        <div class="page-content">
            <div class="container">
                <div class="row">
                    <div class="col-md-12">
                        <!-- content of page -->
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

CSS

#wrapper {
  padding-left: 250px;
  transition: all 0.4s ease 0s;
}

#sidebar-wrapper {
  margin-left: -250px;
  left: 250px;
  width: 250px;
  background: #CCC;
  position: fixed;
  height: 100%;
  overflow-y: auto;
  z-index: 1000;
  transition: all 0.4s ease 0s;
}

#page-content-wrapper {
  width: 100%;
}

.sidebar-nav {
  position: absolute;
  top: 0;
  width: 250px;
  list-style: none;
  margin: 0;
  padding: 0;
}

@media (max-width:767px) {

    #wrapper {
      padding-left: 0;
    }

    #sidebar-wrapper {
      left: 0;
    }

    #wrapper.active {
      position: relative;
      left: 250px;
    }

    #wrapper.active #sidebar-wrapper {
      left: 250px;
      width: 250px;
      transition: all 0.4s ease 0s;
    }

}

JSFIDDLE

How to insert a text at the beginning of a file?

Hi with carriage return:

sed -i '1s/^/your text\n/' file

Assembly Language - How to do Modulo?

If you compute modulo a power of two, using bitwise AND is simpler and generally faster than performing division. If b is a power of two, a % b == a & (b - 1).

For example, let's take a value in register EAX, modulo 64.
The simplest way would be AND EAX, 63, because 63 is 111111 in binary.

The masked, higher digits are not of interest to us. Try it out!

Analogically, instead of using MUL or DIV with powers of two, bit-shifting is the way to go. Beware signed integers, though!

Android fade in and fade out with ImageView

This is probably the best solution you'll get. Simple and Easy. I learned it on udemy. Suppose you have two images having image id's id1 and id2 respectively and currently the image view is set as id1 and you want to change it to the other image everytime someone clicks in. So this is the basic code in MainActivity.java File

int clickNum=0;
public void click(View view){
clickNum++;
ImageView a=(ImageView)findViewById(R.id.id1);
ImageView b=(ImageView)findViewById(R.id.id2);
if(clickNum%2==1){
  a.animate().alpha(0f).setDuration(2000); //alpha controls the transpiracy
}
else if(clickNum%2==0){
  b.animate().alpha(0f).setDuration(2000); //alpha controls the transpiracy
}

}

I hope this will surely help

Find duplicate records in MongoDB

Use aggregation on name and get name with count > 1:

db.collection.aggregate([
    {"$group" : { "_id": "$name", "count": { "$sum": 1 } } },
    {"$match": {"_id" :{ "$ne" : null } , "count" : {"$gt": 1} } }, 
    {"$project": {"name" : "$_id", "_id" : 0} }
]);

To sort the results by most to least duplicates:

db.collection.aggregate([
    {"$group" : { "_id": "$name", "count": { "$sum": 1 } } },
    {"$match": {"_id" :{ "$ne" : null } , "count" : {"$gt": 1} } }, 
    {"$sort": {"count" : -1} },
    {"$project": {"name" : "$_id", "_id" : 0} }     
]);

To use with another column name than "name", change "$name" to "$column_name"

Converting JavaScript object with numeric keys into array

_x000D_
_x000D_
var JsonObj = {_x000D_
  "0": "1",_x000D_
  "1": "2",_x000D_
  "2": "3",_x000D_
  "3": "4"_x000D_
};_x000D_
_x000D_
var array = [];_x000D_
for (var i in JsonObj) {_x000D_
  if (JsonObj.hasOwnProperty(i) && !isNaN(+i)) {_x000D_
    array[+i] = JsonObj[i];_x000D_
  }_x000D_
}_x000D_
_x000D_
console.log(array)
_x000D_
_x000D_
_x000D_

DEMO

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'MyController':

I have been getting similar error, and just want to share with you. maybe it will help someone.

If you want to use EntityManagerFactory to get an EntityManager, make sure that you will use:

<persistence-unit name="name" transaction-type="RESOURCE_LOCAL">

and not:

<persistence-unit name="name" transaction-type="JPA">

in persistance.xml

clean and rebuild project, it should help.

android: how to change layout on button click?

The logcat shows the error, you should call super.onCreate(savedInstanceState) :

@Override
public void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    //... your code
}

Error: Module not specified (IntelliJ IDEA)

For IntelliJ IDEA 2019.3.4 (Ultimate Edition), the following worked for me:

  1. Find the Environment variables for your project.
  2. Specify, from the dropdowns, the values of "Use class path of module:" and "JRE" as in the attached screenshot.

enter image description here

What is the difference between HTML tags and elements?

HTML tag is just opening or closing entity. For example:

<p> and </p> are called HTML tags

HTML element encompasses opening tag, closing tag, content (optional for content-less tags) Eg:

<p>This is the content</p> : This complete thing is called a HTML element

How to display UTF-8 characters in phpMyAdmin?

Easier solution for wamp is: go to phpMyAdmin, click localhost, select latin1_bin for Server connection collation, then start to create database and table

Destroy or remove a view in Backbone.js

This is what I've been using. Haven't seen any issues.

destroy: function(){
  this.remove();
  this.unbind();
}

How to study design patterns?

The notion that read design patterns, practice coding them is not really going to help IMO. When you read these books 1. Look for the basic problem that a particular design pattern solves,starting with Creational Patterns is your best bet. 2. I am sure you have written code in past, analyze if you faced the same problems that design patterns aim at providing a solution. 3. Try to redesign/re factor code or perhaps start off fresh.

About resources you can check these

  1. www.dofactory.com
  2. Design Patterns: Elements of Reusable Object-Oriented Software (Addison-Wesley Professional Computing Series) by Erich Gamma, Richard Helm, Ralph Johnson, and John M. Vlissides
  3. Patterns of Enterprise Application Architecture by Martin Fowler

1 is quick start, 2 will be in depth study..3 will explain or should make you think what you learnt in 2 fits in enterprise software.

My 2 cents...

Java - Using Accessor and Mutator methods

Let's go over the basics: "Accessor" and "Mutator" are just fancy names fot a getter and a setter. A getter, "Accessor", returns a class's variable or its value. A setter, "Mutator", sets a class variable pointer or its value.

So first you need to set up a class with some variables to get/set:

public class IDCard
{
    private String mName;
    private String mFileName;
    private int mID;

}

But oh no! If you instantiate this class the default values for these variables will be meaningless. B.T.W. "instantiate" is a fancy word for doing:

IDCard test = new IDCard();

So - let's set up a default constructor, this is the method being called when you "instantiate" a class.

public IDCard()
{
    mName = "";
    mFileName = "";
    mID = -1;
}

But what if we do know the values we wanna give our variables? So let's make another constructor, one that takes parameters:

public IDCard(String name, int ID, String filename)
{
    mName = name;
    mID = ID;
    mFileName = filename;
}

Wow - this is nice. But stupid. Because we have no way of accessing (=reading) the values of our variables. So let's add a getter, and while we're at it, add a setter as well:

public String getName()
{
    return mName;
}

public void setName( String name )
{
    mName = name;
}

Nice. Now we can access mName. Add the rest of the accessors and mutators and you're now a certified Java newbie. Good luck.

Javascript Object push() function

Do :


var data = new Array();
var tempData = new Array();

How can I select random files from a directory in bash?

This is an even later response to @gniourf_gniourf's late answer, which I just upvoted because it's by far the best answer, twice over. (Once for avoiding eval and once for safe filename handling.)

But it took me a few minutes to untangle the "not very well documented" feature(s) this answer uses. If your Bash skills are solid enough that you saw immediately how it works, then skip this comment. But I didn't, and having untangled it I think it's worth explaining.

Feature #1 is the shell's own file globbing. a=(*) creates an array, $a, whose members are the files in the current directory. Bash understands all the weirdnesses of filenames, so that list is guaranteed correct, guaranteed escaped, etc. No need to worry about properly parsing textual file names returned by ls.

Feature #2 is Bash parameter expansions for arrays, one nested within another. This starts with ${#ARRAY[@]}, which expands to the length of $ARRAY.

That expansion is then used to subscript the array. The standard way to find a random number between 1 and N is to take the value of random number modulo N. We want a random number between 0 and the length of our array. Here's the approach, broken into two lines for clarity's sake:

LENGTH=${#ARRAY[@]}
RANDOM=${a[RANDOM%$LENGTH]}

But this solution does it in a single line, removing the unnecessary variable assignment.

Feature #3 is Bash brace expansion, although I have to confess I don't entirely understand it. Brace expansion is used, for instance, to generate a list of 25 files named filename1.txt, filename2.txt, etc: echo "filename"{1..25}".txt".

The expression inside the subshell above, "${a[RANDOM%${#a[@]}]"{1..42}"}", uses that trick to produce 42 separate expansions. The brace expansion places a single digit in between the ] and the }, which at first I thought was subscripting the array, but if so it would be preceded by a colon. (It would also have returned 42 consecutive items from a random spot in the array, which is not at all the same thing as returning 42 random items from the array.) I think it's just making the shell run the expansion 42 times, thereby returning 42 random items from the array. (But if someone can explain it more fully, I'd love to hear it.)

The reason N has to be hardcoded (to 42) is that brace expansion happens before variable expansion.

Finally, here's Feature #4, if you want to do this recursively for a directory hierarchy:

shopt -s globstar
a=( ** )

This turns on a shell option that causes ** to match recursively. Now your $a array contains every file in the entire hierarchy.

Regular expression for not allowing spaces in the input field

If you're using some plugin which takes string and use construct Regex to create Regex Object i:e new RegExp()

Than Below string will work

'^\\S*$'

It's same regex @Bergi mentioned just the string version for new RegExp constructor

Connect to mysql on Amazon EC2 from a remote server

Though this question seems to be answered, another common issue that you can get is the DB user has been mis-configured. This is a mysql administration and permissions issue:

  1. EC2_DB launched with IP 10.55.142.100
  2. EC2_web launched with IP 10.55.142.144
  3. EC2_DB and EC2_WEBare in the same security group with access across your DB port (3306)
  4. EC2_DB has a mysql DB that can be reached locally by the DB root user ('root'@'localhost')
  5. EC2_DB mysql DB has a remote user 'my_user'@'%' IDENTIFIED BY PASSWORD 'password'
  6. A bash call to mysql from EC2_WEB fails: mysql -umy_user -p -h ip-10-55-142-100.ec2.internal as does host references to the explicit IP, public DNS, etc.

Step 6 fails because the mysql DB has the wrong user permisions. It needs this:

GRANT ALL PRIVILEGES ON *.* TO 'my_user'@'ip-10-55-142-144.ec2.internal' IDENTIFIED BY PASSWORD 'password'

I would like to think that % would work for any remote server, but I did not find this to be the case.

Please let me know if this helps you.

Why is __dirname not defined in node REPL?

I was running a script from batch file as SYSTEM user and all variables like process.cwd() , path.resolve() and all other methods would give me path to C:\Windows\System32 folder instead of actual path. During experiments I noticed that when an error is thrown the stack contains a true path to the node file.

Here's a very hacky way to get true path by triggering an error and extracting path from e.stack. Do not use.

// this should be the name of currently executed file
const currentFilename = 'index.js';

function veryHackyGetFolder() {
  try {
    throw new Error();
  } catch(e) {
    const fullMsg = e.stack.toString();
    const beginning = fullMsg.indexOf('file:///') + 8;
    const end = fullMsg.indexOf('\/' + currentFilename);
    const dir = fullMsg.substr(beginning, end - beginning).replace(/\//g, '\\');
    return dir;
  }
}

Usage

const dir = veryHackyGetFolder();

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)

Calling a Function defined inside another function in Javascript

you can also just use return:

   function outer() { 
    function inner() {
        alert("hi");
    }
return inner();

}
outer();

VMWare Player vs VMWare Workstation

VMWare Player can be seen as a free, closed-source competitor to Virtualbox.

Initially VMWare Player (up to version 2.5) was intended to operate on fixed virtual operating systems (e.g. play back pre-created virtual disks).

Many advanced features such as vsphere are probably not required by most users, and VMWare Player will provide the same core technologies and 3D acceleration as the ESX Workstation solution.

From my experience VMWare Player 5 is faster than Virtualbox 4.2 RC3 and has better SMP performance. Both are great however, each with its own unique advantages. Both are somewhat lacking in 2D rendering performance.

See the official FAQ, and a feature comparison table.

MATLAB - multiple return values from a function?

Matlab allows you to return multiple values as well as receive them inline.

When you call it, receive individual variables inline:

[array, listp, freep] = initialize(size)

Excel - Sum column if condition is met by checking other column in same table

Actually a more refined solution is use the build-in function sumif, this function does exactly what you need, will only sum those expenses of a specified month.

example

=SUMIF(A2:A100,"=January",B2:B100)

Best way to get child nodes

firstElementChild might not be available in IE<9 (only firstChild)

on IE<9 firstChild is the firstElementChild because MS DOM (IE<9) is not storing empty text nodes. But if you do so on other browsers they will return empty text nodes...

my solution

child=(elem.firstElementChild||elem.firstChild)

this will give the firstchild even on IE<9

Aggregate multiple columns at once

You could try:

agg <- aggregate(list(x$val1, x$val2, x$val3, x$val4), by = list(x$id1, x$id2), mean)

How can I initialize an ArrayList with all zeroes in Java?

It's not like that. ArrayList just uses array as internal respentation. If you add more then 60 elements then underlaying array will be exapanded. How ever you can add as much elements to this array as much RAM you have.

How does Facebook disable the browser's integrated Developer Tools?

Besides redefining console._commandLineAPI, there are some other ways to break into InjectedScriptHost on WebKit browsers, to prevent or alter the evaluation of expressions entered into the developer's console.

Edit:

Chrome has fixed this in a past release. - which must have been before February 2015, as I created the gist at that time

So here's another possibility. This time we hook in, a level above, directly into InjectedScript rather than InjectedScriptHost as opposed to the prior version.

Which is kind of nice, as you can directly monkey patch InjectedScript._evaluateAndWrap instead of having to rely on InjectedScriptHost.evaluate as that gives you more fine-grained control over what should happen.

Another pretty interesting thing is, that we can intercept the internal result when an expression is evaluated and return that to the user instead of the normal behavior.

Here is the code, that does exactly that, return the internal result when a user evaluates something in the console.

var is;
Object.defineProperty(Object.prototype,"_lastResult",{
   get:function(){
       return this._lR;
   },
   set:function(v){
       if (typeof this._commandLineAPIImpl=="object") is=this;
       this._lR=v;
   }
});
setTimeout(function(){
   var ev=is._evaluateAndWrap;
   is._evaluateAndWrap=function(){
       var res=ev.apply(is,arguments);
       console.log();
       if (arguments[2]==="completion") {
           //This is the path you end up when a user types in the console and autocompletion get's evaluated

           //Chrome expects a wrapped result to be returned from evaluateAndWrap.
           //You can use `ev` to generate an object yourself.
           //In case of the autocompletion chrome exptects an wrapped object with the properties that can be autocompleted. e.g.;
           //{iGetAutoCompleted: true}
           //You would then go and return that object wrapped, like
           //return ev.call (is, '', '({test:true})', 'completion', true, false, true);
           //Would make `test` pop up for every autocompletion.
           //Note that syntax as well as every Object.prototype property get's added to that list later,
           //so you won't be able to exclude things like `while` from the autocompletion list,
           //unless you wou'd find a way to rewrite the getCompletions function.
           //
           return res; //Return the autocompletion result. If you want to break that, return nothing or an empty object
       } else {
           //This is the path where you end up when a user actually presses enter to evaluate an expression.
           //In order to return anything as normal evaluation output, you have to return a wrapped object.

           //In this case, we want to return the generated remote object. 
           //Since this is already a wrapped object it would be converted if we directly return it. Hence,
           //`return result` would actually replicate the very normal behaviour as the result is converted.
           //to output what's actually in the remote object, we have to stringify it and `evaluateAndWrap` that object again.`
           //This is quite interesting;
           return ev.call (is, null, '(' + JSON.stringify (res) + ')', "console", true, false, true)
       }
   };
},0);

It's a bit verbose, but I thought I put some comments into it

So normally, if a user, for example, evaluates [1,2,3,4] you'd expect the following output:

enter image description here

After monkeypatching InjectedScript._evaluateAndWrap evaluating the very same expression, gives the following output:

enter image description here

As you see the little-left arrow, indicating output, is still there, but this time we get an object. Where the result of the expression, the array [1,2,3,4] is represented as an object with all its properties described.

I recommend trying to evaluate this and that expression, including those that generate errors. It's quite interesting.

Additionally, take a look at the is - InjectedScriptHost - object. It provides some methods to play with and get a bit of insight into the internals of the inspector.

Of course, you could intercept all that information and still return the original result to the user.

Just replace the return statement in the else path by a console.log (res) following a return res. Then you'd end up with the following.

enter image description here

End of Edit


This is the prior version which was fixed by Google. Hence not a possible way anymore.

One of it is hooking into Function.prototype.call

Chrome evaluates the entered expression by calling its eval function with InjectedScriptHost as thisArg

var result = evalFunction.call(object, expression);

Given this, you can listen for the thisArg of call being evaluate and get a reference to the first argument (InjectedScriptHost)

if (window.URL) {
    var ish, _call = Function.prototype.call;
    Function.prototype.call = function () { //Could be wrapped in a setter for _commandLineAPI, to redefine only when the user started typing.
        if (arguments.length > 0 && this.name === "evaluate" && arguments [0].constructor.name === "InjectedScriptHost") { //If thisArg is the evaluate function and the arg0 is the ISH
            ish = arguments[0];
            ish.evaluate = function (e) { //Redefine the evaluation behaviour
                throw new Error ('Rejected evaluation of: \n\'' + e.split ('\n').slice(1,-1).join ("\n") + '\'');
            };
            Function.prototype.call = _call; //Reset the Function.prototype.call
            return _call.apply(this, arguments);  
        }
    };
}

You could e.g. throw an error, that the evaluation was rejected.

enter image description here

Here is an example where the entered expression gets passed to a CoffeeScript compiler before passing it to the evaluate function.

How to make (link)button function as hyperlink?

You can use OnClientClick event to call a JavaScript function:

<asp:Button ID="Button1" runat="server" Text="Button" onclientclick='redirect()' />

JavaScript code:

function redirect() {
  location.href = 'page.aspx';
}

But i think the best would be to style a hyperlink with css.

Example :

.button {
  display: block;
  height: 25px;
  background: #f1f1f1;
  padding: 10px;
  text-align: center;
  border-radius: 5px;
  border: 1px solid #e1e1e2;
  color: #000;
  font-weight: bold;
}