Programs & Examples On #Qgraphicsview

A QGraphicsView is a class from the Qt toolkit which provides a widget for displaying the contents of a QGraphicsScene.

Adding a simple spacer to twitter bootstrap

In Bootstrap 4 you can use classes like mt-5, mb-5, my-5, mx-5 (y for both top and bottom, x for both left and right).

According to their site:

The classes are named using the format {property}{sides}-{size} for xs and {property}{sides}-{breakpoint}-{size} for sm, md, lg, and xl.

Link: https://getbootstrap.com/docs/4.0/utilities/spacing/

How to convert date into this 'yyyy-MM-dd' format in angular 2

You can also try this.

consider today's date '28 Dec 2018'(for example)

 this.date = new Date().toISOString().slice(0,10); 

new Date() we get as: Fri Dec 28 2018 11:44:33 GMT+0530 (India Standard Time)

toISOString will convert to : 2018-12-28T06:15:27.479Z

slice(0,10) we get only first 10 characters as date which contains yyyy-mm-dd : 2018-12-28.

Programmatically open new pages on Tabs

You can't directly control this, because it's an option controlled by Internet Explorer users.

Opening pages using Window.open with a different window name will open in a new browser window like a popup, OR open in a new tab, if the user configured the browser to do so.

Image overlay on responsive sized images bootstrap

Add a class to the containing div, then set the following css on it:

.img-overlay {
    position: relative;
    max-width: 500px; //whatever your max-width should be 
}

position: relative is required on a parent element of children with position: absolute for the children to be positioned in relation to that parent.

DEMO

Abstract variables in Java?

Why do you want all subclasses to define the variable? If every subclass is supposed to have it, just define it in the superclass. BTW, given that it's good OOP practice not to expose fields anyway, your question makes even less sense.

How to delete mysql database through shell command

Another suitable way:

$ mysql -u you -p
<enter password>

>>> DROP DATABASE foo;

c#: getter/setter

These are called auto properties.

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

Functionally (and in terms of the compiled IL), they are the same as properties with backing fields.

How to increase icons size on Android Home Screen?

If you want to change settings in the launcher, change icon size, or grid size just hold down on an empty part of your home screen. Tap the three Dots and there you go.

From https://forums.oneplus.net/threads/how-to-change-icon-and-grid-size-trebuchet-settings.84820/

When configuring the phone for first time I saw something about a grid somewhere, but couldn't find it again. Luckily I found the answer on the link above.

Is it possible to run .php files on my local computer?

Sure you just need to setup a local web server. Check out XAMPP: http://www.apachefriends.org/en/xampp.html

That will get you up and running in about 10 minutes.

There is now a way to run php locally without installing a server: https://stackoverflow.com/a/21872484/672229


Yes but the files need to be processed. For example you can install test servers like mamp / lamp / wamp depending on your plateform.

Basically you need apache / php running.

git command to move a folder inside another

 git mv common include

should work.

From the git mv man page:

git mv [-f] [-n] [-k] <source> ... <destination directory>

In the second form, the last argument has to be an existing directory; the given sources will be moved into this directory.
The index is updated after successful completion, but the change must still be committed.

No "git add" should be done before the move.


Note: "git mv A B/", when B does not exist as a directory, should error out, but it didn't.

See commit c57f628 by Matthieu Moy (moy) for Git 1.9/2.0 (Q1 2014):

Git used to trim the trailing slash, and make the command equivalent to 'git mv file no-such-dir', which created the file no-such-dir (while the trailing slash explicitly stated that it could only be a directory).

This patch skips the trailing slash removal for the destination path.
The path with its trailing slash is passed to rename(2), which errors out with the appropriate message:

$ git mv file no-such-dir/
fatal: renaming 'file' failed: Not a directory

How to call a stored procedure (with parameters) from another stored procedure without temp table

You can call a stored procedure from another stored procedure by using the EXECUTE command.

Say your procedure is X. Then in X you can use

EXECUTE PROCEDURE Y () RETURNING_VALUES RESULT;"

Where can I get a list of Ansible pre-defined variables?

There are 3 sources of variables in Ansible:

  1. Variables gathered from facts. You can get them by running command: ansible -m setup hostname

  2. Built-in (pre-defined) Ansible variables (AKA 'magic' variables). They are documented in Ansible documentation: http://docs.ansible.com/playbooks_variables.html#magic-variables-and-how-to-access-information-about-other-hosts
    Here is the list extracted from Ansible 1.9 documentation:

    • group_names
    • groups
    • inventory_hostname
    • ansible_hostname
    • inventory_hostname_short
    • play_hosts
    • delegate_to
    • inventory_dir
    • inventory_file
  3. Variables passed to ansible via command line. But obviously you know what they are

Java String import

Java compiler imports 3 packages by default. 1. The package without name 2. The java.lang package(That's why you can declare String, Integer, System classes without import) 3. The current package (current file's package)

That's why you don't need to declare import statement for the java.lang package.

How to create an AVD for Android 4.0

If you installed the system image and still get this error, it might be that the Android SDK manager did not put the files in the right folder for the AVD manager. See an answer to Stack Overflow question How to create an AVD for Android 4.0.3? (Unable to find a 'userdata.img').

Why doesn't os.path.join() work in this case?

Do not use forward slashes at the beginning of path components, except when refering to the root directory:

os.path.join('/home/build/test/sandboxes', todaystr, 'new_sandbox')

see also: http://docs.python.org/library/os.path.html#os.path.join

How to timeout a thread

I had the same problem. So i came up with a simple solution like this.

public class TimeoutBlock {

 private final long timeoutMilliSeconds;
    private long timeoutInteval=100;

    public TimeoutBlock(long timeoutMilliSeconds){
        this.timeoutMilliSeconds=timeoutMilliSeconds;
    }

    public void addBlock(Runnable runnable) throws Throwable{
        long collectIntervals=0;
        Thread timeoutWorker=new Thread(runnable);
        timeoutWorker.start();
        do{ 
            if(collectIntervals>=this.timeoutMilliSeconds){
                timeoutWorker.stop();
                throw new Exception("<<<<<<<<<<****>>>>>>>>>>> Timeout Block Execution Time Exceeded In "+timeoutMilliSeconds+" Milli Seconds. Thread Block Terminated.");
            }
            collectIntervals+=timeoutInteval;           
            Thread.sleep(timeoutInteval);

        }while(timeoutWorker.isAlive());
        System.out.println("<<<<<<<<<<####>>>>>>>>>>> Timeout Block Executed Within "+collectIntervals+" Milli Seconds.");
    }

    /**
     * @return the timeoutInteval
     */
    public long getTimeoutInteval() {
        return timeoutInteval;
    }

    /**
     * @param timeoutInteval the timeoutInteval to set
     */
    public void setTimeoutInteval(long timeoutInteval) {
        this.timeoutInteval = timeoutInteval;
    }
}

Guarantees that if block didn't execute within the time limit. the process will terminate and throws an exception.

example :

try {
        TimeoutBlock timeoutBlock = new TimeoutBlock(10 * 60 * 1000);//set timeout in milliseconds
        Runnable block=new Runnable() {

            @Override
            public void run() {
                //TO DO write block of code 
            }
        };

        timeoutBlock.addBlock(block);// execute the runnable block 

    } catch (Throwable e) {
        //catch the exception here . Which is block didn't execute within the time limit
    }

Carriage return and Line feed... Are both required in C#?

I know this is a little old, but for anyone stumbling across this page should know there is a difference between \n and \r\n.

The \r\n gives a CRLF end of line and the \n gives an LF end of line character. There is very little difference to the eye in general.

Create a .txt from the string and then try and open in notepad (normal not notepad++) and you will notice the difference

SHA,PCT,PRACTICE,BNF CODE,BNF NAME,ITEMS,NIC,ACT COST,QUANTITY,PERIOD
Q44,01C,N81002,0101021B0AAALAL,Sod Algin/Pot Bicarb_Susp S/F,3,20.48,19.05,2000,201901
Q44,01C,N81002,0101021B0AAAPAP,Sod Alginate/Pot Bicarb_Tab Chble 500mg,1,3.07,2.86,60,201901

The above is using 'CRLF' and the below is what 'LF only' would look like (There is a character that cant be seen where the LF shows).

SHA,PCT,PRACTICE,BNF CODE,BNF NAME,ITEMS,NIC,ACT COST,QUANTITY,PERIODQ44,01C,N81002,0101021B0AAALAL,Sod Algin/Pot Bicarb_Susp S/F,3,20.48,19.05,2000,201901Q44,01C,N81002,0101021B0AAAPAP,Sod Alginate/Pot Bicarb_Tab Chble 500mg,1,3.07,2.86,60,201901

If the Line Ends need to be corrected and the file is small enough in size, you can change the line endings in NotePad++ (or paste into word then back into Notepad - although this will make CRLF only).

This may cause some functions that read these files to potenitially no longer function (The example lines given are from GP Prescribing data - England. The file has changed from a CRLF Line end to an LF line end). This stopped an SSIS job from running and failed as couldn't read the LF line endings.

Source of Line Ending Information: https://en.wikipedia.org/wiki/Newline#Representations_in_different_character_encoding_specifications

Hope this helps someone in future :) CRLF = Windows based, LF or CF are from Unix based systems (Linux, MacOS etc.)

How to delete or change directory of a cloned git repository on a local computer

Just move it :)

command line :

move "C:\Documents and Setings\$USER\project" C:\project

or just drag the folder in explorer.

Git won't care where it is - all the metadata for the repository is inside a folder called .git inside your project folder.

Android "hello world" pushnotification example

Firebase: https://firebase.google.com/docs/cloud-messaging/

GCM(Deprecated): http://developer.android.com/google/gcm/index.html

I don't have much knowledge about C2DM. Use GCM, it's very easy to implement and configure.

Facebook how to check if user has liked page and show content?

There are some changes required to JavaScript code to handle rendering based on user liking or not liking the page mandated by Facebook moving to Auth2.0 authorization.

Change is fairly simple:-

sessions has to be replaced by authResponse and uid by userID

Moreover given the requirement of the code and some issues faced by people(including me) in general with FB.login, use of FB.getLoginStatus is a better alternative. It saves query to FB in case user is logged in and has authenticated your app.

Refer to Response and Sessions Object section for info on how this might save query to FB server. http://developers.facebook.com/docs/reference/javascript/FB.getLoginStatus/

Issues with FB.login and its fixes using FB.getLoginStatus. http://forum.developers.facebook.net/viewtopic.php?id=70634

Here is the code posted above with changes which worked for me.

$(document).ready(function(){
    FB.getLoginStatus(function(response) {
        if (response.status == 'connected') {
            var user_id = response.authResponse.userID;
            var page_id = "40796308305"; //coca cola
            var fql_query = "SELECT uid FROM page_fan WHERE page_id =" + page_id + " and uid=" + user_id;
            var the_query = FB.Data.query(fql_query);

            the_query.wait(function(rows) {

                if (rows.length == 1 && rows[0].uid == user_id) {
                    $("#container_like").show();

                    //here you could also do some ajax and get the content for a "liker" instead of simply showing a hidden div in the page.

                } else {
                    $("#container_notlike").show();
                    //and here you could get the content for a non liker in ajax...
                }
            });
        } else {
            // user is not logged in
        }
    });

});

How to include the reference of DocumentFormat.OpenXml.dll on Mono2.10?

After viewing and changed the properties to DocumentFormat.OpenXml, I also had to change the Specific Version to false.

ADB not responding. You can wait more,or kill "adb.exe" process manually and click 'Restart'

If you need to kill all adb processes on windows with one command, you can do it as follows:

taskkill /F /IM adb*

ENOENT, no such file or directory

For those running Laravel Mix with npm run watch, just terminate the script and run the command again.

Signed to unsigned conversion in C - is it always safe?

When one unsigned and one signed variable are added (or any binary operation) both are implicitly converted to unsigned, which would in this case result in a huge result.

So it is safe in the sense of that the result might be huge and wrong, but it will never crash.

Copying text outside of Vim with set mouse=a enabled

Another OSX-Mac option is to uncheck View->Allow Mouse Reporting (or press ?-R to toggle it.) This allows you to toggle between mouse interaction and mouse selecting, which might be useful when selecting and copy/pasting a few bits because you don't have to hold a modifier key to do it.

Note for Multiline with line numbers:

I usually have line numbers enabled so this will also copy the line numbers if you select multiple lines. If you want to copy multiple lines without the line numbers disable the numbers with :set nonu and then you can :set nu to re-enable them after you're done copying.

Making TextView scrollable on Android

whenever you need to use the ScrollView as parent, And you also use the scroll movement method with TextView.

And When you portrait to landscape your device that time occur some issue. (like) entire page is scrollable but scroll movement method can't work.

if you still need to use ScrollView as parent or scroll movement method then you also use below desc.

If you do not have any problems then you use EditText instead of TextView

see below :

<EditText
     android:id="@+id/description_text_question"
     android:layout_width="match_parent"
     android:layout_height="wrap_content"
     android:background="@null"
     android:editable="false"
     android:cursorVisible="false"
     android:maxLines="6"/>

Here, the EditText behaves like TextView

And your issue will be resolved

How to get the path of a running JAR file?

Try this:

String path = new File("").getAbsolutePath();

How do I remove objects from an array in Java?

You can always do:

int i, j;
for (i = j = 0; j < foo.length; ++j)
  if (!"a".equals(foo[j])) foo[i++] = foo[j];
foo = Arrays.copyOf(foo, i);

How can I hide or encrypt JavaScript code?

JavaScript is a scripting language and therefore stays in human readable form until it is time for it to be interpreted and executed by the JavaScript runtime.

The only way to partially hide it, at least from the less technical minds, is to obfuscate.

Obfuscation makes it harder for humans to read it, but not impossible for the technically savvy.

Relative imports for the billionth time

Relative imports use a module's name attribute to determine that module's position in the package hierarchy. If the module's name does not contain any package information (e.g. it is set to 'main') then relative imports are resolved as if the module were a top level module, regardless of where the module is actually located on the file system.

Wrote a little python package to PyPi that might help viewers of this question. The package acts as workaround if one wishes to be able to run python files containing imports containing upper level packages from within a package / project without being directly in the importing file's directory. https://pypi.org/project/import-anywhere/

How do I use su to execute the rest of the bash script as that user?

Here is yet another approach, which was more convenient in my case (I just wanted to drop root privileges and do the rest of my script from restricted user): you can make the script restart itself from correct user. Let's suppose it is run as root initially. Then it will look like this:

#!/bin/bash
if [ $UID -eq 0 ]; then
  user=$1
  dir=$2
  shift 2     # if you need some other parameters
  cd "$dir"
  exec su "$user" "$0" -- "$@"
  # nothing will be executed beyond that line,
  # because exec replaces running process with the new one
fi

echo "This will be run from user $UID"
...

convert php date to mysql format

There is several options.

Either convert it to timestamp and use as instructed in other posts with strtotime() or use MySQL’s date parsing option

How to customize a Spinner in Android

Try this

i was facing lot of issues when i was trying other solution...... After lot of R&D now i got solution

  1. create custom_spinner.xml in layout folder and paste this code

     <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/colorGray">
    <TextView
    android:id="@+id/tv_spinnervalue"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:textColor="@color/colorWhite"
    android:gravity="center"
    android:layout_alignParentLeft="true"
    android:textSize="@dimen/_18dp"
    android:layout_marginTop="@dimen/_3dp"/>
    <ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentRight="true"
    android:background="@drawable/men_icon"/>
    </RelativeLayout>
    
  2. in your activity

    Spinner spinner =(Spinner)view.findViewById(R.id.sp_colorpalates);
    String[] years = {"1996","1997","1998","1998"};
    spinner.setAdapter(new SpinnerAdapter(this, R.layout.custom_spinner, years));
    
  3. create a new class of adapter

    public class SpinnerAdapter extends ArrayAdapter<String> {
    private String[] objects;
    
    public SpinnerAdapter(Context context, int textViewResourceId, String[] objects) {
        super(context, textViewResourceId, objects);
        this.objects=objects;
    }
    
    @Override
    public View getDropDownView(int position, View convertView, @NonNull ViewGroup parent) {
        return getCustomView(position, convertView, parent);
    }
    
    @NonNull
    @Override
    public View getView(int position, View convertView, @NonNull ViewGroup parent) {
        return getCustomView(position, convertView, parent);
    }
    
    private View getCustomView(final int position, View convertView, ViewGroup parent) {
        View row = LayoutInflater.from(parent.getContext()).inflate(R.layout.custom_spinner, parent, false);
        final TextView label=(TextView)row.findViewById(R.id.tv_spinnervalue);
        label.setText(objects[position]);
        return row;
    }
    }
    

How to find/identify large commits in git history?

A blazingly fast shell one-liner

This shell script displays all blob objects in the repository, sorted from smallest to largest.

For my sample repo, it ran about 100 times faster than the other ones found here.
On my trusty Athlon II X4 system, it handles the Linux Kernel repository with its 5.6 million objects in just over a minute.

The Base Script

git rev-list --objects --all |
  git cat-file --batch-check='%(objecttype) %(objectname) %(objectsize) %(rest)' |
  sed -n 's/^blob //p' |
  sort --numeric-sort --key=2 |
  cut -c 1-12,41- |
  $(command -v gnumfmt || echo numfmt) --field=2 --to=iec-i --suffix=B --padding=7 --round=nearest

When you run above code, you will get nice human-readable output like this:

...
0d99bb931299  530KiB path/to/some-image.jpg
2ba44098e28f   12MiB path/to/hires-image.png
bd1741ddce0d   63MiB path/to/some-video-1080p.mp4

macOS users: Since numfmt is not available on macOS, you can either omit the last line and deal with raw byte sizes or brew install coreutils.

Filtering

To achieve further filtering, insert any of the following lines before the sort line.

To exclude files that are present in HEAD, insert the following line:

grep -vF --file=<(git ls-tree -r HEAD | awk '{print $3}') |

To show only files exceeding given size (e.g. 1 MiB = 220 B), insert the following line:

awk '$2 >= 2^20' |

Output for Computers

To generate output that's more suitable for further processing by computers, omit the last two lines of the base script. They do all the formatting. This will leave you with something like this:

...
0d99bb93129939b72069df14af0d0dbda7eb6dba 542455 path/to/some-image.jpg
2ba44098e28f8f66bac5e21210c2774085d2319b 12446815 path/to/hires-image.png
bd1741ddce0d07b72ccf69ed281e09bf8a2d0b2f 65183843 path/to/some-video-1080p.mp4

File Removal

For the actual file removal, check out this SO question on the topic.

Setting PATH environment variable in OSX permanently

You could also add this

if [ -f ~/.bashrc ]; then
    . ~/.bashrc
fi

to ~/.bash_profile, then create ~/.bashrc where you can just add more paths to PATH. An example with .

export PATH=$PATH:.

Run cURL commands from Windows console

If you are not into Cygwin, you can use native Windows builds. Some are here: curl Download Wizard.

Calculate the date yesterday in JavaScript

Surprisingly no answer point to the easiest cross browser solution

To find exactly the same time yesterday*:

var yesterday = new Date(Date.now() - 86400000); // that is: 24 * 60 * 60 * 1000

*: This works well if your use-case doesn't mind potential imprecision with calendar weirdness (like daylight savings), otherwise I'd recommend using https://moment.github.io/luxon/

Regex to test if string begins with http:// or https://

Making this case insensitive wasn't working in asp.net so I just specified each of the letters.

Here's what I had to do to get it working in an asp.net RegularExpressionValidator:

[Hh][Tt][Tt][Pp][Ss]?://(.*)

Notes:

  • (?i) and using /whatever/i didn't work probably because javascript hasn't brought in all case sensitive functionality
  • Originally had ^ at beginning but it didn't matter, but the (.*) did (Expression didn't work without (.*) but did work without ^)
  • Didn't need to escape the // though might be a good idea.

Here's the full RegularExpressionValidator if you need it:

<asp:RegularExpressionValidator ID="revURLHeaderEdit" runat="server" 
    ControlToValidate="txtURLHeaderEdit" 
    ValidationExpression="[Hh][Tt][Tt][Pp][Ss]?://(.*)"
    ErrorMessage="URL should begin with http:// or https://" >
</asp:RegularExpressionValidator>

Testing two JSON objects for equality ignoring child order in Java

I know it is usually considered only for testing but you could use the Hamcrest JSON comparitorSameJSONAs in Hamcrest JSON.

Hamcrest JSON SameJSONAs

How do I get the current absolute URL in Ruby on Rails?

you can use any one for rails 3.2:

request.original_url
or
request.env["HTTP_REFERER"]
or
request.env['REQUEST_URI']

I think it will work every where

"#{request.protocol}#{request.host}:#{request.port}#{request.fullpath}"

asp:TextBox ReadOnly=true or Enabled=false?

Readonly will not "grayout" the textbox and will still submit the value on a postback.

Override devise registrations controller

A better and more organized way of overriding Devise controllers and views using namespaces:

Create the following folders:

app/controllers/my_devise
app/views/my_devise

Put all controllers that you want to override into app/controllers/my_devise and add MyDevise namespace to controller class names. Registrations example:

# app/controllers/my_devise/registrations_controller.rb
class MyDevise::RegistrationsController < Devise::RegistrationsController

  ...

  def create
    # add custom create logic here
  end

  ...    

end 

Change your routes accordingly:

devise_for :users,
           :controllers  => {
             :registrations => 'my_devise/registrations',
             # ...
           }

Copy all required views into app/views/my_devise from Devise gem folder or use rails generate devise:views, delete the views you are not overriding and rename devise folder to my_devise.

This way you will have everything neatly organized in two folders.

Does Visual Studio Code have box select/multi-line edit?

For multiple select in Visual Studio Code, hold down the Alt key and starting clicking wherever you want to edit.

Visual Studio Code supports multiple line edit.

How to filter WooCommerce products by custom attribute

You can use the WooCommerce Layered Nav widget, which allows you to use different sets of attributes as filters for products. Here's the "official" description:

Shows a custom attribute in a widget which lets you narrow down the list of products when viewing product categories.

If you look into plugins/woocommerce/widgets/widget-layered_nav.php, you can see the way it operates with the attributes in order to set filters. The URL then looks like this:

http://yoursite.com/shop/?filtering=1&filter_min-kvadratura=181&filter_max-kvadratura=108&filter_obem-ohlajdane=111

... and the digits are actually the id-s of the different attribute values, that you want to set.

Removing padding gutter from grid columns in Bootstrap 4

You can use this css code to get gutterless grid in bootstrap.

.no-gutter.row,
.no-gutter.container,
.no-gutter.container-fluid{
  margin-left: 0;
  margin-right: 0;
}

.no-gutter>[class^="col-"]{
  padding-left: 0;
  padding-right: 0;
}

"Proxy server connection failed" in google chrome

Internet explorer has a reset to factory button and luckily so does chrome! try the link below and let us know. the other option is to stop chrome and delete the c:\users\%username%\appdata\local\google folder entirely then reinstall chrome but this will loose all you local settings and data.

Google doc on how to factory reset: https://support.google.com/chrome/answer/3296214?hl=en

How to get memory usage at runtime using C++?

I am using other way to do that and it sounds realistic. What I do is i got the PID of the process by getpid() function and then I use /proc/pid/stat file. I believe the 23rd column of the stat file is the vmsize (look at the Don post). You may read the vmsize from the file wherever you need in the code. In case you wonder how much a snippet of a code may use memory, you may read that file once before that snippet and once after and you can subtract them from each other.

How do I use a custom Serializer with Jackson?

In my case (Spring 3.2.4 and Jackson 2.3.1), XML configuration for custom serializer:

<mvc:annotation-driven>
    <mvc:message-converters register-defaults="false">
        <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
            <property name="objectMapper">
                <bean class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean">
                    <property name="serializers">
                        <array>
                            <bean class="com.example.business.serializer.json.CustomObjectSerializer"/>
                        </array>
                    </property>
                </bean>
            </property>
        </bean>
    </mvc:message-converters>
</mvc:annotation-driven>

was in unexplained way overwritten back to default by something.

This worked for me:

CustomObject.java

@JsonSerialize(using = CustomObjectSerializer.class)
public class CustomObject {

    private Long value;

    public Long getValue() {
        return value;
    }

    public void setValue(Long value) {
        this.value = value;
    }
}

CustomObjectSerializer.java

public class CustomObjectSerializer extends JsonSerializer<CustomObject> {

    @Override
    public void serialize(CustomObject value, JsonGenerator jgen,
        SerializerProvider provider) throws IOException,JsonProcessingException {
        jgen.writeStartObject();
        jgen.writeNumberField("y", value.getValue());
        jgen.writeEndObject();
    }

    @Override
    public Class<CustomObject> handledType() {
        return CustomObject.class;
    }
}

No XML configuration (<mvc:message-converters>(...)</mvc:message-converters>) is needed in my solution.

Javascript - check array for value

This should do it:

for (var i = 0; i < bank_holidays.length; i++) {
    if (bank_holidays[i] === '06/04/2012') {
        alert('LOL');
    }
}

jsFiddle

Spring security CORS Filter

In my case, I just added this class and use @EnableAutConfiguration:

@Component
public class SimpleCORSFilter extends GenericFilterBean {
    /**
     * The Logger for this class.
     */
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp,
                         FilterChain chain) throws IOException, ServletException {
        logger.info("> doFilter");

        HttpServletResponse response = (HttpServletResponse) resp;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, PUT, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "Authorization, Content-Type");
        //response.setHeader("Access-Control-Allow-Credentials", "true");
        chain.doFilter(req, resp);

        logger.info("< doFilter");
    }
}

How to split a number into individual digits in c#?

Substring and Join methods are usable for this statement.

string no = "12345";
string [] numberArray = new string[no.Length];
int counter = 0;

   for (int i = 0; i < no.Length; i++)
   {
     numberArray[i] = no.Substring(counter, 1); // 1 is split length
     counter++;
   }

Console.WriteLine(string.Join(" ", numberArray)); //output >>> 0 1 2 3 4 5

How to execute IN() SQL queries with Spring's JDBCTemplate effectively?

Refer to here

write query with named parameter, use simple ListPreparedStatementSetter with all parameters in sequence. Just add below snippet to convert the query in traditional form based to available parameters,

ParsedSql parsedSql = NamedParameterUtils.parseSqlStatement(namedSql);

List<Integer> parameters = new ArrayList<Integer>();
for (A a : paramBeans)
    parameters.add(a.getId());

MapSqlParameterSource parameterSource = new MapSqlParameterSource();
parameterSource.addValue("placeholder1", parameters);
// create SQL with ?'s
String sql = NamedParameterUtils.substituteNamedParameters(parsedSql, parameterSource);     
return sql;

Use curly braces to initialize a Set in Python

You need to do empty_set = set() to initialize an empty set. {} is an empty dict.

Check whether a path is valid

I haven't had any problems with the code below. (Relative paths must start with '/' or '\').

private bool IsValidPath(string path, bool allowRelativePaths = false)
{
    bool isValid = true;

    try
    {
        string fullPath = Path.GetFullPath(path);

        if (allowRelativePaths)
        {
            isValid = Path.IsPathRooted(path);
        }
        else
        {
            string root = Path.GetPathRoot(path);
            isValid = string.IsNullOrEmpty(root.Trim(new char[] { '\\', '/' })) == false;
        }
    }
    catch(Exception ex)
    {
        isValid = false;
    }

    return isValid;
}

For example these would return false:

IsValidPath("C:/abc*d");
IsValidPath("C:/abc?d");
IsValidPath("C:/abc\"d");
IsValidPath("C:/abc<d");
IsValidPath("C:/abc>d");
IsValidPath("C:/abc|d");
IsValidPath("C:/abc:d");
IsValidPath("");
IsValidPath("./abc");
IsValidPath("./abc", true);
IsValidPath("/abc");
IsValidPath("abc");
IsValidPath("abc", true);

And these would return true:

IsValidPath(@"C:\\abc");
IsValidPath(@"F:\FILES\");
IsValidPath(@"C:\\abc.docx\\defg.docx");
IsValidPath(@"C:/abc/defg");
IsValidPath(@"C:\\\//\/\\/\\\/abc/\/\/\/\///\\\//\defg");
IsValidPath(@"C:/abc/def~`!@#$%^&()_-+={[}];',.g");
IsValidPath(@"C:\\\\\abc////////defg");
IsValidPath(@"/abc", true);
IsValidPath(@"\abc", true);

How do I deal with special characters like \^$.?*|+()[{ in my regex?

I think the easiest way to match the characters like

\^$.?*|+()[

are using character classes from within R. Consider the following to clean column headers from a data file, which could contain spaces, and punctuation characters:

> library(stringr)
> colnames(order_table) <- str_replace_all(colnames(order_table),"[:punct:]|[:space:]","")

This approach allows us to string character classes to match punctation characters, in addition to whitespace characters, something you would normally have to escape with \\ to detect. You can learn more about the character classes at this cheatsheet below, and you can also type in ?regexp to see more info about this.

https://www.rstudio.com/wp-content/uploads/2016/09/RegExCheatsheet.pdf

Importing JSON into an Eclipse project

Download java-json.jar from here, which contains org.json.JSONArray

http://www.java2s.com/Code/JarDownload/java/java-json.jar.zip

nzip and add to your project's library: Project > Build Path > Configure build path> Select Library tab > Add External Libraries > Select the java-json.jar file.

how to auto select an input field and the text in it on page load

I found a very simple method that works well:

<input type="text" onclick="this.focus();this.select()">

findViewByID returns null

In my experience, it seems that this can also happen when your code is called after OnDestroyView (when the fragment is on the back stack.) If you are updating the UI on input from a BroadCastReceiver, you ought to check if this is the case.

Where are shared preferences stored?

Just to save some of you time...

On my Galaxy S v.2.3.3 Shared Preferences are not stored in:/data/data/YOUR_PACKAGE_NAME/shared_prefs/YOUR_PREFS_NAME.xml

but are now located in: /dbdata/databases/YOUR_PACKAGE_NAME/shared_prefs/YOUR_PREFS_NAME.xml

I believe they changed this in 2.3

Excel VBA - read cell value from code

I think you need this ..

Dim n as Integer   

For n = 5 to 17
  msgbox cells(n,3) '--> sched waste
  msgbox cells(n,4) '--> type of treatm
  msgbox format(cells(n,5),"dd/MM/yyyy") '--> Lic exp
  msgbox cells(n,6) '--> email col
Next

VBA - how to conditionally skip a for loop iteration

VBA does not have a Continue or any other equivalent keyword to immediately jump to the next loop iteration. I would suggest a judicious use of Goto as a workaround, especially if this is just a contrived example and your real code is more complicated:

For i = LBound(Schedule, 1) To UBound(Schedule, 1)
    If (Schedule(i, 1) < ReferenceDate) Then
        PrevCouponIndex = i
        Goto NextIteration
    End If
    DF = Application.Run("SomeFunction"....)
    PV = PV + (DF * Coupon / CouponFrequency)
    '....'
    'a whole bunch of other code you are not showing us'
    '....'
    NextIteration:
Next

If that is really all of your code, though, @Brian is absolutely correct. Just put an Else clause in your If statement and be done with it.

Find the server name for an Oracle database

SELECT  host_name
FROM    v$instance

How to split a string with angularJS

You can try something like this:

$scope.test = "test1,test2";
{{test.split(',')[0]}}

now you will get "test1" while you try {{test.split(',')[0]}}

and you will get "test2" while you try {{test.split(',')[1]}}

here is my plnkr:

http://plnkr.co/edit/jaXOrZX9UO9kmdRMImdN?p=preview

Creating a simple configuration file and parser in C++

Here is a simple work around for white space between the '=' sign and the data, in the config file. Assign to the istringstream from the location after the '=' sign and when reading from it, any leading white space is ignored.

Note: while using an istringstream in a loop, make sure you call clear() before assigning a new string to it.

//config.txt
//Input name = image1.png
//Num. of rows = 100
//Num. of cols = 150

std::string ipName;
int nR, nC;

std::ifstream fin("config.txt");
std::string line;
std::istringstream sin;

while (std::getline(fin, line)) {
 sin.str(line.substr(line.find("=")+1));
 if (line.find("Input name") != std::string::npos) {
  std::cout<<"Input name "<<sin.str()<<std::endl;
  sin >> ipName;
 }
 else if (line.find("Num. of rows") != std::string::npos) {
  sin >> nR;
 }
 else if (line.find("Num. of cols") != std::string::npos) {
  sin >> nC;
 }
 sin.clear();
}

Merging arrays with the same keys

I just wrote this function, it should do the trick for you, but it does left join

public function mergePerKey($array1,$array2)
    {
        $mergedArray = [];

        foreach ($array1 as $key => $value) 
        {
            if(isset($array2[$key]))
             {
               $mergedArray[$value] = null;

               continue;
             }
            $mergedArray[$value] = $array2[$key];
        }

        return $mergedArray;
    }

How do you use MySQL's source command to import large files in windows

C:\xampp\mysql\bin\mysql -u root -p testdatabase < C:\Users\Juan\Desktop\databasebackup.sql

That worked for me to import 400MB file into my database.

How to get Spinner value?

Yes, you can register a listener via setOnItemSelectedListener(), as is demonstrated here.

Difference between null and empty ("") Java String

You may also understand the difference between null and an empty string this way:

Difference between null and 0/empty string

Original image by R. Sato (@raysato)

Finding current executable's path without /proc/self/exe

Making this work reliably across platforms requires using #ifdef statements.

The below code finds the executable's path in Windows, Linux, MacOS, Solaris or FreeBSD (although FreeBSD is untested). It uses Boost 1.55.0 (or later) to simplify the code, but it's easy enough to remove if you want. Just use defines like _MSC_VER and __linux as the OS and compiler require.

#include <string>
#include <boost/predef/os.h>

#if (BOOST_OS_WINDOWS)
#  include <stdlib.h>
#elif (BOOST_OS_SOLARIS)
#  include <stdlib.h>
#  include <limits.h>
#elif (BOOST_OS_LINUX)
#  include <unistd.h>
#  include <limits.h>
#elif (BOOST_OS_MACOS)
#  include <mach-o/dyld.h>
#elif (BOOST_OS_BSD_FREE)
#  include <sys/types.h>
#  include <sys/sysctl.h>
#endif

/*
 * Returns the full path to the currently running executable,
 * or an empty string in case of failure.
 */
std::string getExecutablePath() {
    #if (BOOST_OS_WINDOWS)
        char *exePath;
        if (_get_pgmptr(&exePath) != 0)
            exePath = "";
    #elif (BOOST_OS_SOLARIS)
        char exePath[PATH_MAX];
        if (realpath(getexecname(), exePath) == NULL)
            exePath[0] = '\0';
    #elif (BOOST_OS_LINUX)
        char exePath[PATH_MAX];
        ssize_t len = ::readlink("/proc/self/exe", exePath, sizeof(exePath));
        if (len == -1 || len == sizeof(exePath))
            len = 0;
        exePath[len] = '\0';
    #elif (BOOST_OS_MACOS)
        char exePath[PATH_MAX];
        uint32_t len = sizeof(exePath);
        if (_NSGetExecutablePath(exePath, &len) != 0) {
            exePath[0] = '\0'; // buffer too small (!)
        } else {
            // resolve symlinks, ., .. if possible
            char *canonicalPath = realpath(exePath, NULL);
            if (canonicalPath != NULL) {
                strncpy(exePath,canonicalPath,len);
                free(canonicalPath);
            }
        }
    #elif (BOOST_OS_BSD_FREE)
        char exePath[2048];
        int mib[4];  mib[0] = CTL_KERN;  mib[1] = KERN_PROC;  mib[2] = KERN_PROC_PATHNAME;  mib[3] = -1;
        size_t len = sizeof(exePath);
        if (sysctl(mib, 4, exePath, &len, NULL, 0) != 0)
            exePath[0] = '\0';
    #endif
        return std::string(exePath);
}

The above version returns full paths including the executable name. If instead you want the path without the executable name, #include boost/filesystem.hpp> and change the return statement to:

return strlen(exePath)>0 ? boost::filesystem::path(exePath).remove_filename().make_preferred().string() : std::string();

How to copy folders to docker image from Dockerfile?

COPY . <destination>

Which would be in your case:

COPY . /

Can Powershell Run Commands in Parallel?

In Powershell 7 you can use ForEach-Object -Parallel

$Message = "Output:"
Get-ChildItem $dir | ForEach-Object -Parallel {
    "$using:Message $_"
} -ThrottleLimit 4

Compare two files in Visual Studio

To compare any two files and merge it to one file Here are the following steps you can follow if you have visual studio(Any version) installed.

Step 1: Open Visual studio command prompt. If you do not find visual studio command prompt then choose visual studio tools

Start -> Visual studio command prompt

enter image description here

enter image description here

Step 2: Enter the command vsdiffmerge.exe

Ignore the switch /m if you need just comparison.

Syntax 1:
vsdiffmerge <file1> <file2> <file1> <outputfile> /t /m

Syntax 2:
vsdiffmerge <basefilename> <CompareFilename> <basefilename> <OutputFilename> /t /m

Example 1:
vsdiffmerge test1.js test2.js test1.js output.js /t /m
Example 2:
vsdiffmerge.exe "C:\Users\livingston\Downloads\wa\wa\Files\pre\Test.js" "C:\Users\livingston\Downloads\wa\wa\Files\Prod\Test.js" "C:\Users\livingston\Downloads\wa\wa\Files\pre\Test.js" "C:\Users\livingston\Downloads\wa\wa\Files\output\samp.js" /t /m

enter image description here


Step 3: Merge the files

enter image description here Please note that if file name does not exists in the location, it will not open the comparer.

Also you can beautify the file before you do the comparison. In visual studio Ctrl + K + D.

There are lot of beautifier sites available online.

Hashmap does not work with int, char

Generics only support object types, not primitives. Unlike C++ templates, generics don't involve code generatation and there is only one HashMap code regardless of the number of generic types of it you use.

Trove4J gets around this by pre-generating selected collections to use primitives and supports TCharIntHashMap which to can wrap to support the Map<Character, Integer> if you need to.

TCharIntHashMap: An open addressed Map implementation for char keys and int values.

How can I get the status code from an http error in Axios?

You can put the error into an object and log the object, like this:

axios.get('foo.com')
    .then((response) => {})
    .catch((error) => {
        console.log({error}) // this will log an empty object with an error property
    });

Hope this help someone out there.

How to remove all white spaces in java

Try:

  string output = YourString.replaceAll("\\s","")

s - indicates space character (tab characters etc)

Provide schema while reading csv file as a dataframe

In pyspark 2.4 onwards, you can simply use header parameter to set the correct header:

data = spark.read.csv('data.csv', header=True)

Similarly, if using scala you can use header parameter as well.

CSS3 equivalent to jQuery slideUp and slideDown?

    try this for slide up slide down with animation 
give your **height

        @keyframes slide_up{
            from{
                min-height: 0;
                height: 0px;
                opacity: 0;
            }
            to{
                height: 560px;
                opacity: 1;
            }
        }

        @keyframes slide_down{
            from{
                height: 560px;
                opacity: 1;
            }
            to{
                min-height: 0;
                height: 0px;
                opacity: 0;
            } 
        }

how to fix stream_socket_enable_crypto(): SSL operation failed with code 1

How to fix on Laravel 7:

Download the latest cacert.pem file from cURL website.

wget https://curl.haxx.se/ca/cacert.pem

Edit php.ini (you can do php --ini to find it), update (or create if they don't exist already) those two lines:

curl.cainfo="/path/to/downloaded/cacert.pem"
...
openssl.cafile="/path/to/downloaded/cacert.pem"

Those lines should already exist but commented out, so uncomment them and edit both values with the path to the downloaded cacert.pem

Restart PHP and Nginx/Apache.

Edit: You may need to chown/chmod the downloaded certificate file so PHP (and its user) can read it.

source

Python: Get the first character of the first string in a list?

Indexing in python starting from 0. You wrote [1:] this would not return you a first char in any case - this will return you a rest(except first char) of string.

If you have the following structure:

mylist = ['base', 'sample', 'test']

And want to get fist char for the first one string(item):

myList[0][0]
>>> b

If all first chars:

[x[0] for x in myList]
>>> ['b', 's', 't']    

If you have a text:

text = 'base sample test'
text.split()[0][0]
>>> b

iPhone system font

Swift

You should always use the system defaults and not hard coding the font name because the default font could be changed by Apple at any time.

There are a couple of system default fonts(normal, bold, italic) with different sizes(label, button, others):

let font = UIFont.systemFont(ofSize: UIFont.systemFontSize)
let font2 = UIFont.boldSystemFont(ofSize: UIFont.systemFontSize)
let font3 = UIFont.italicSystemFont(ofSize: UIFont.systemFontSize)

beaware that the default font size depends on the target view (label, button, others)

Examples:

let labelFont = UIFont.systemFont(ofSize: UIFont.labelFontSize)
let buttonFont = UIFont.systemFont(ofSize: UIFont.buttonFontSize)
let textFieldFont = UIFont.systemFont(ofSize: UIFont.systemFontSize)

SQL server stored procedure return a table

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

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

select * from @t
end
go

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

select * from @t

Only variables should be passed by reference

PHP offical Manual : end()

Parameters

array

The array. This array is passed by reference because it is modified by the function. This means you must pass it a real variable and not a function returning an array because only actual variables may be passed by reference.

Check if cookie exists else set cookie to Expire in 10 days

You need to read and write document.cookie

if (document.cookie.indexOf("visited=") >= 0) {
  // They've been here before.
  alert("hello again");
}
else {
  // set a new cookie
  expiry = new Date();
  expiry.setTime(expiry.getTime()+(10*60*1000)); // Ten minutes

  // Date()'s toGMTSting() method will format the date correctly for a cookie
  document.cookie = "visited=yes; expires=" + expiry.toGMTString();
  alert("this is your first time");
}

Docker-compose: node_modules not present in a volume after npm install succeeds

I tried the most popular answers on this page but ran into an issue: the node_modules directory in my Docker instance would get cached in the the named or unnamed mount point, and later would overwrite the node_modules directory that was built as part of the Docker build process. Thus, new modules I added to package.json would not show up in the Docker instance.

Fortunately I found this excellent page which explains what was going on and gives at least 3 ways to work around it: https://burnedikt.com/dockerized-node-development-and-mounting-node-volumes/

PHPExcel - set cell type before writing a value in it

try this

$currencyFormat = '_($* #,##0.00_);_($* (#,##0.00);_($* "-"??_);_(@_)';
$textFormat='@';//'General','0.00','@'
$excel->getActiveSheet()->getStyle('B1')->getNumberFormat()->setFormatCode($currencyFormat);
$excel->getActiveSheet()->getStyle('C1')->getNumberFormat()->setFormatCode($textFormat);`

How can I run PowerShell with the .NET 4 runtime?

Please be VERY careful with using the registry key approach. These are machine-wide keys and forcibily migrate ALL applications to .NET 4.0.

Many products do not work if forcibily migrated and this is a testing aid and not a production quality mechanism. Visual Studio 2008 and 2010, MSBuild, turbotax, and a host of websites, SharePoint and so on should not be automigrated.

If you need to use PowerShell with 4.0, this should be done on a per-application basis with a configuration file, you should check with the PowerShell team on the precise recommendation. This is likely to break some existing PowerShell commands.

Rails 4: before_filter vs. before_action

It is just syntax difference, in rails app there is CRUD, and seven actions basically by name index, new, create, show, update, edit, destroy.

Rails 4 make it developer friendly to change syntax before filter to before action.

before_action call method before the actions which we declare, like

before_action :set_event, only: [:show, :update, :destroy, :edit]

set_event is a method which will call always before show, update, edit and destroy.

Check if an image is loaded (no errors) with jQuery

As I understand the .complete property is non-standard. It may not be universal... I notice it seem to work differently in Firefox verses IE. I am loading a number of images in javascript then checking if complete. In Firefox, this seems to work great. In IE, it doesn't because the images appear to be loading on another thread. It works only if I put a delay between my assignment to image.src and when I check the image.complete property.

Using image.onload and image.onerror isn't working for me, either, because I need to pass a parameter to know which image I am talking about when the function is called. Any way of doing that seems to fail because it actually seems to pass the same function, not different instances of the same function. So the value I pass into it to identify the image always ends up being the last value in the loop. I cannot think of any way around this problem.

On Safari and Chrome, I am seeing the image.complete true and the naturalWidth set even when the error console shows a 404 for that image... and I intentionally removed that image to test this. But the above works well for Firefox and IE.

Return list of items in list greater than some value

You can use a list comprehension:

[x for x in j if x >= 5]

Best way to alphanumeric check in JavaScript

The asker's original inclination to use str.charCodeAt(i) appears to be faster than the regular expression alternative. In my test on jsPerf the RegExp option performs 66% slower in Chrome 36 (and slightly slower in Firefox 31).

Here's a cleaned-up version of the original validation code that receives a string and returns true or false:

function isAlphaNumeric(str) {
  var code, i, len;

  for (i = 0, len = str.length; i < len; i++) {
    code = str.charCodeAt(i);
    if (!(code > 47 && code < 58) && // numeric (0-9)
        !(code > 64 && code < 91) && // upper alpha (A-Z)
        !(code > 96 && code < 123)) { // lower alpha (a-z)
      return false;
    }
  }
  return true;
};

Of course, there may be other considerations, such as readability. A one-line regular expression is definitely prettier to look at. But if you're strictly concerned with speed, you may want to consider this alternative.

String contains another string

You can use .indexOf():

if(str.indexOf(substr) > -1) {

}

Exit codes in Python

The exit codes only have meaning as assigned by the script author. The Unix tradition is that exit code 0 means 'success', anything else is failure. The only way to be sure what the exit codes for a given script mean is to examine the script itself.

How can I have grep not print out 'No such file or directory' errors?

You can use the -s or --no-messages flag to suppress errors.

-s, --no-messages suppress error messages

grep pattern * -s -R -n

What is the cause for "angular is not defined"

You have not placed the script tags for angular js

you can do so by using cdn or downloading the angularjs for your project and then referencing it

after this you have to add your own java script in your case main.js

that should do

Google OAuth 2 authorization - Error: redirect_uri_mismatch

for me it was because in the 'Authorized redirect URIs' list I've incorrectly put https://developers.google.com/oauthplayground/ instead of https://developers.google.com/oauthplayground (without / at the end).

Constructing pandas DataFrame from values in variables gives "ValueError: If using all scalar values, you must pass an index"

I had the same problem with numpy arrays and the solution is to flatten them:

data = {
    'b': array1.flatten(),
    'a': array2.flatten(),
}

df = pd.DataFrame(data)

Get Android API level of phone currently running my application

Check android.os.Build.VERSION, which is a static class that holds various pieces of information about the Android OS a system is running.

If you care about all versions possible (back to original Android version), as in minSdkVersion is set to anything less than 4, then you will have to use android.os.Build.VERSION.SDK, which is a String that can be converted to the integer of the release.

If you are on at least API version 4 (Android 1.6 Donut), the current suggested way of getting the API level would be to check the value of android.os.Build.VERSION.SDK_INT, which is an integer.

In either case, the integer you get maps to an enum value from all those defined in android.os.Build.VERSION_CODES:

SDK_INT value        Build.VERSION_CODES        Human Version Name       
    1                  BASE                      Android 1.0 (no codename)
    2                  BASE_1_1                  Android 1.1 Petit Four
    3                  CUPCAKE                   Android 1.5 Cupcake
    4                  DONUT                     Android 1.6 Donut
    5                  ECLAIR                    Android 2.0 Eclair
    6                  ECLAIR_0_1                Android 2.0.1 Eclair                  
    7                  ECLAIR_MR1                Android 2.1 Eclair
    8                  FROYO                     Android 2.2 Froyo
    9                  GINGERBREAD               Android 2.3 Gingerbread
   10                  GINGERBREAD_MR1           Android 2.3.3 Gingerbread
   11                  HONEYCOMB                 Android 3.0 Honeycomb
   12                  HONEYCOMB_MR1             Android 3.1 Honeycomb
   13                  HONEYCOMB_MR2             Android 3.2 Honeycomb
   14                  ICE_CREAM_SANDWICH        Android 4.0 Ice Cream Sandwich
   15                  ICE_CREAM_SANDWICH_MR1    Android 4.0.3 Ice Cream Sandwich
   16                  JELLY_BEAN                Android 4.1 Jellybean
   17                  JELLY_BEAN_MR1            Android 4.2 Jellybean
   18                  JELLY_BEAN_MR2            Android 4.3 Jellybean
   19                  KITKAT                    Android 4.4 KitKat
   20                  KITKAT_WATCH              Android 4.4 KitKat Watch
   21                  LOLLIPOP                  Android 5.0 Lollipop
   22                  LOLLIPOP_MR1              Android 5.1 Lollipop
   23                  M                         Android 6.0 Marshmallow
   24                  N                         Android 7.0 Nougat
   25                  N_MR1                     Android 7.1.1 Nougat
   26                  O                         Android 8.0 Oreo
   27                  O_MR1                     Android 8 Oreo MR1
   28                  P                         Android 9 Pie
   29                  Q                         Android 10
  10000                CUR_DEVELOPMENT           Current Development Version

Note that some time between Android N and O, the Android SDK began aliasing CUR_DEVELOPMENT and the developer preview of the next major Android version to be the same SDK_INT value (10000).

Download file from web in Python 3

If you want to obtain the contents of a web page into a variable, just read the response of urllib.request.urlopen:

import urllib.request
...
url = 'http://example.com/'
response = urllib.request.urlopen(url)
data = response.read()      # a `bytes` object
text = data.decode('utf-8') # a `str`; this step can't be used if data is binary

The easiest way to download and save a file is to use the urllib.request.urlretrieve function:

import urllib.request
...
# Download the file from `url` and save it locally under `file_name`:
urllib.request.urlretrieve(url, file_name)
import urllib.request
...
# Download the file from `url`, save it in a temporary directory and get the
# path to it (e.g. '/tmp/tmpb48zma.txt') in the `file_name` variable:
file_name, headers = urllib.request.urlretrieve(url)

But keep in mind that urlretrieve is considered legacy and might become deprecated (not sure why, though).

So the most correct way to do this would be to use the urllib.request.urlopen function to return a file-like object that represents an HTTP response and copy it to a real file using shutil.copyfileobj.

import urllib.request
import shutil
...
# Download the file from `url` and save it locally under `file_name`:
with urllib.request.urlopen(url) as response, open(file_name, 'wb') as out_file:
    shutil.copyfileobj(response, out_file)

If this seems too complicated, you may want to go simpler and store the whole download in a bytes object and then write it to a file. But this works well only for small files.

import urllib.request
...
# Download the file from `url` and save it locally under `file_name`:
with urllib.request.urlopen(url) as response, open(file_name, 'wb') as out_file:
    data = response.read() # a `bytes` object
    out_file.write(data)

It is possible to extract .gz (and maybe other formats) compressed data on the fly, but such an operation probably requires the HTTP server to support random access to the file.

import urllib.request
import gzip
...
# Read the first 64 bytes of the file inside the .gz archive located at `url`
url = 'http://example.com/something.gz'
with urllib.request.urlopen(url) as response:
    with gzip.GzipFile(fileobj=response) as uncompressed:
        file_header = uncompressed.read(64) # a `bytes` object
        # Or do anything shown above using `uncompressed` instead of `response`.

Using new line(\n) in string and rendering the same in HTML

I had the following problem where I was fetching data from a database and wanted to display a string containing \n. None of the solutions above worked for me and I finally came up with a solution: https://stackoverflow.com/a/61484190/7251208

SQL Server reports 'Invalid column name', but the column is present and the query works through management studio

In my case I restart Microsoft SQL Sever Management Studio and this works well for me.

How do I URL encode a string

For individual www form-encoded query parameters, I made a category on NSString:

- (NSString*)WWWFormEncoded{
     NSMutableCharacterSet *chars = NSCharacterSet.alphanumericCharacterSet.mutableCopy;
     [chars addCharactersInString:@" "];
     NSString* encodedString = [self stringByAddingPercentEncodingWithAllowedCharacters:chars];
     encodedString = [encodedString stringByReplacingOccurrencesOfString:@" " withString:@"+"];
     return encodedString;
}

How can I read a text file from the SD card in Android?

You should have READ_EXTERNAL_STORAGE permission for reading sdcard. Add permission in manifest.xml

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

From android 6.0 or higher, your app must ask user to grant the dangerous permissions at runtime. Please refer this link Permissions overview

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
    if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 0);
    }
}

How to get all key in JSON object (javascript)

var input = {"document":
  {"people":[
    {"name":["Harry Potter"],"age":["18"],"gender":["Male"]},
    {"name":["hermione granger"],"age":["18"],"gender":["Female"]},
  ]}
}

var keys = [];
for(var i = 0;i<input.document.people.length;i++)
{
    Object.keys(input.document.people[i]).forEach(function(key){
        if(keys.indexOf(key) == -1)
        {
            keys.push(key);
        }
    });
}
console.log(keys);

Submit form using AJAX and jQuery

First give your form an id attribute, then use code like this:

$(document).ready( function() {
  var form = $('#my_awesome_form');

  form.find('select:first').change( function() {
    $.ajax( {
      type: "POST",
      url: form.attr( 'action' ),
      data: form.serialize(),
      success: function( response ) {
        console.log( response );
      }
    } );
  } );

} );

So this code uses .serialize() to pull out the relevant data from the form. It also assumes the select you care about is the first one in the form.

For future reference, the jQuery docs are very, very good.

Error handling in AngularJS http get then construct

If you want to handle server errors globally, you may want to register an interceptor service for $httpProvider:

$httpProvider.interceptors.push(function ($q) {
    return {
        'responseError': function (rejection) {
            // do something on error
            if (canRecover(rejection)) {
                return responseOrNewPromise
            }
            return $q.reject(rejection);
        }
    };
});

Docs: http://docs.angularjs.org/api/ng.$http

Android - Back button in the title bar

It can also be done without code by specifying a parent activity in app manifest If you want a back button in Activity B which will goto Activity A, just add Activity A as the parent of Activity B in the manifest.

How to use ScrollView in Android?

Put your TableLayout inside a ScrollView Layout.That will solve your problem.

Display Parameter(Multi-value) in Report

You can use the "Join" function to create a single string out of the array of labels, like this:

=Join(Parameters!Product.Label, ",")

Laravel 5 route not defined, while it is?

In my case the solution was simple:

I have defined the route at the very start of the route.php file.

After moving the named route to the bottom, my app finally saw it. It means that somehow the route was defined too early.

Can we have multiple <tbody> in same <table>?

Yes you can use them, for example I use them to more easily style groups of data, like this:

_x000D_
_x000D_
thead th { width: 100px; border-bottom: solid 1px #ddd; font-weight: bold; }_x000D_
tbody:nth-child(odd) { background: #f5f5f5;  border: solid 1px #ddd; }_x000D_
tbody:nth-child(even) { background: #e5e5e5;  border: solid 1px #ddd; }
_x000D_
<table>_x000D_
    <thead>_x000D_
        <tr><th>Customer</th><th>Order</th><th>Month</th></tr>_x000D_
    </thead>_x000D_
    <tbody>_x000D_
        <tr><td>Customer 1</td><td>#1</td><td>January</td></tr>_x000D_
        <tr><td>Customer 1</td><td>#2</td><td>April</td></tr>_x000D_
        <tr><td>Customer 1</td><td>#3</td><td>March</td></tr>_x000D_
    </tbody>_x000D_
    <tbody>_x000D_
        <tr><td>Customer 2</td><td>#1</td><td>January</td></tr>_x000D_
        <tr><td>Customer 2</td><td>#2</td><td>April</td></tr>_x000D_
        <tr><td>Customer 2</td><td>#3</td><td>March</td></tr>_x000D_
    </tbody>_x000D_
    <tbody>_x000D_
        <tr><td>Customer 3</td><td>#1</td><td>January</td></tr>_x000D_
        <tr><td>Customer 3</td><td>#2</td><td>April</td></tr>_x000D_
        <tr><td>Customer 3</td><td>#3</td><td>March</td></tr>_x000D_
    </tbody>_x000D_
</table>
_x000D_
_x000D_
_x000D_

You can view an example here. It'll only work in newer browsers, but that's what I'm supporting in my current application, you can use the grouping for JavaScript etc. The main thing is it's a convenient way to visually group the rows to make the data much more readable. There are other uses of course, but as far as applicable examples, this one is the most common one for me.

How to display two digits after decimal point in SQL Server

select cast(your_float_column as decimal(10,2))
from your_table

decimal(10,2) means you can have a decimal number with a maximal total precision of 10 digits. 2 of them after the decimal point and 8 before.
The biggest possible number would be 99999999.99

Parsing time string in Python

It has discussed many times in SO. In short, "%z" is not supported because platform not support it. My solution is a new one, just skip the time zone.:

    datetime.datetime.strptime(re.sub(r"[+-]([0-9])+", "", "Tue May 08 15:14:45 +0800 2012"),"%a %b %d %H:%M:%S %Y")

Basic HTTP authentication with Node and Express 4

Express has removed this functionality and now recommends you use the basic-auth library.

Here's an example of how to use:

var http = require('http')
var auth = require('basic-auth')

// Create server
var server = http.createServer(function (req, res) {
  var credentials = auth(req)

  if (!credentials || credentials.name !== 'aladdin' || credentials.pass !== 'opensesame') {
    res.statusCode = 401
    res.setHeader('WWW-Authenticate', 'Basic realm="example"')
    res.end('Access denied')
  } else {
    res.end('Access granted')
  }
})

// Listen
server.listen(3000)

To send a request to this route you need to include an Authorization header formatted for basic auth.

Sending a curl request first you must take the base64 encoding of name:pass or in this case aladdin:opensesame which is equal to YWxhZGRpbjpvcGVuc2VzYW1l

Your curl request will then look like:

 curl -H "Authorization: Basic YWxhZGRpbjpvcGVuc2VzYW1l" http://localhost:3000/

Hosting ASP.NET in IIS7 gives Access is denied?

For me, nothing worked except the following, which solved the problem: open IIS, select the site, open Authentication (in the IIS section), right click Anonymous Authentication and select Edit, select Application Pool Identity.

implements Closeable or implements AutoCloseable

Here is the small example

public class TryWithResource {

    public static void main(String[] args) {
        try (TestMe r = new TestMe()) {
            r.generalTest();
        } catch(Exception e) {
            System.out.println("From Exception Block");
        } finally {
            System.out.println("From Final Block");
        }
    }
}



public class TestMe implements AutoCloseable {

    @Override
    public void close() throws Exception {
        System.out.println(" From Close -  AutoCloseable  ");
    }

    public void generalTest() {
        System.out.println(" GeneralTest ");
    }
}

Here is the output:

GeneralTest 
From Close -  AutoCloseable  
From Final Block

PHP XML how to output nice format

With a SimpleXml object, you can simply

$domxml = new DOMDocument('1.0');
$domxml->preserveWhiteSpace = false;
$domxml->formatOutput = true;
/* @var $xml SimpleXMLElement */
$domxml->loadXML($xml->asXML());
$domxml->save($newfile);

$xml is your simplexml object

So then you simpleXml can be saved as a new file specified by $newfile

Git fatal: protocol 'https' is not supported

Simple Answer is Just remove the https

Your Repo. : (git clone https://........)

just Like That (git clone ://.......)

and again type (git clone https://........)

Problem Solve 100%...

How can I use/create dynamic template to compile dynamic Component with Angular 2.0?

I decided to compact everything I learned into one file. There's a lot to take in here especially compared to before RC5. Note that this source file includes the AppModule and AppComponent.

import {
  Component, Input, ReflectiveInjector, ViewContainerRef, Compiler, NgModule, ModuleWithComponentFactories,
  OnInit, ViewChild
} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';

@Component({
  selector: 'app-dynamic',
  template: '<h4>Dynamic Components</h4><br>'
})
export class DynamicComponentRenderer implements OnInit {

  factory: ModuleWithComponentFactories<DynamicModule>;

  constructor(private vcRef: ViewContainerRef, private compiler: Compiler) { }

  ngOnInit() {
    if (!this.factory) {
      const dynamicComponents = {
        sayName1: {comp: SayNameComponent, inputs: {name: 'Andrew Wiles'}},
        sayAge1: {comp: SayAgeComponent, inputs: {age: 30}},
        sayName2: {comp: SayNameComponent, inputs: {name: 'Richard Taylor'}},
        sayAge2: {comp: SayAgeComponent, inputs: {age: 25}}};
      this.compiler.compileModuleAndAllComponentsAsync(DynamicModule)
        .then((moduleWithComponentFactories: ModuleWithComponentFactories<DynamicModule>) => {
          this.factory = moduleWithComponentFactories;
          Object.keys(dynamicComponents).forEach(k => {
            this.add(dynamicComponents[k]);
          })
        });
    }
  }

  addNewName(value: string) {
    this.add({comp: SayNameComponent, inputs: {name: value}})
  }

  addNewAge(value: number) {
    this.add({comp: SayAgeComponent, inputs: {age: value}})
  }

  add(comp: any) {
    const compFactory = this.factory.componentFactories.find(x => x.componentType === comp.comp);
    // If we don't want to hold a reference to the component type, we can also say: const compFactory = this.factory.componentFactories.find(x => x.selector === 'my-component-selector');
    const injector = ReflectiveInjector.fromResolvedProviders([], this.vcRef.parentInjector);
    const cmpRef = this.vcRef.createComponent(compFactory, this.vcRef.length, injector, []);
    Object.keys(comp.inputs).forEach(i => cmpRef.instance[i] = comp.inputs[i]);
  }
}

@Component({
  selector: 'app-age',
  template: '<div>My age is {{age}}!</div>'
})
class SayAgeComponent {
  @Input() public age: number;
};

@Component({
  selector: 'app-name',
  template: '<div>My name is {{name}}!</div>'
})
class SayNameComponent {
  @Input() public name: string;
};

@NgModule({
  imports: [BrowserModule],
  declarations: [SayAgeComponent, SayNameComponent]
})
class DynamicModule {}

@Component({
  selector: 'app-root',
  template: `
        <h3>{{message}}</h3>
        <app-dynamic #ad></app-dynamic>
        <br>
        <input #name type="text" placeholder="name">
        <button (click)="ad.addNewName(name.value)">Add Name</button>
        <br>
        <input #age type="number" placeholder="age">
        <button (click)="ad.addNewAge(age.value)">Add Age</button>
    `,
})
export class AppComponent {
  message = 'this is app component';
  @ViewChild(DynamicComponentRenderer) dcr;

}

@NgModule({
  imports: [BrowserModule],
  declarations: [AppComponent, DynamicComponentRenderer],
  bootstrap: [AppComponent]
})
export class AppModule {}`

Angular 4 img src is not found

Copy your images into the assets folder. Angular can only access static files like images and config files from assets folder.

Try like this: <img src="assets/img/myimage.png">

Change the background color of a pop-up dialog

For any dialog called myDialog, after calling myDialog.show(); you can call:

myDialog.getWindow().getDecorView().getBackground().setColorFilter(new LightingColorFilter(0xFF000000, CUSTOM_COLOR));

where CUSTOM_COLOR is in 8-digit hex format, ex. 0xFF303030. Here, FF is the alpha value and the rest is the color value in hex.

angularjs make a simple countdown

I updated Mr. ganaraj answer to show stop and resume functionality and added angular js filter to format countdown timer

it is here on jsFiddle

controller code

'use strict';
var myApp = angular.module('myApp', []);
myApp.controller('AlbumCtrl', function($scope,$timeout) {
    $scope.counter = 0;
    $scope.stopped = false;
    $scope.buttonText='Stop';
    $scope.onTimeout = function(){
        $scope.counter++;
        mytimeout = $timeout($scope.onTimeout,1000);
    }
    var mytimeout = $timeout($scope.onTimeout,1000);
    $scope.takeAction = function(){
        if(!$scope.stopped){
            $timeout.cancel(mytimeout);
            $scope.buttonText='Resume';
        }
        else
        {
            mytimeout = $timeout($scope.onTimeout,1000);
            $scope.buttonText='Stop';
        }
            $scope.stopped=!$scope.stopped;
    }   
});

filter-code adapted from RobG from stackoverflow

myApp.filter('formatTimer', function() {
  return function(input)
    {
        function z(n) {return (n<10? '0' : '') + n;}
        var seconds = input % 60;
        var minutes = Math.floor(input / 60);
        var hours = Math.floor(minutes / 60);
        return (z(hours) +':'+z(minutes)+':'+z(seconds));
    };
});

How does the Java 'for each' loop work?

As so many good answers said, an object must implement the Iterable interface if it wants to use a for-each loop.

I'll post a simple example and try to explain in a different way how a for-each loop works.

The for-each loop example:

public class ForEachTest {

    public static void main(String[] args) {

        List<String> list = new ArrayList<String>();
        list.add("111");
        list.add("222");

        for (String str : list) {
            System.out.println(str);
        }
    }
}

Then, if we use javap to decompile this class, we will get this bytecode sample:

public static void main(java.lang.String[]);
    flags: ACC_PUBLIC, ACC_STATIC
    Code:
      stack=2, locals=4, args_size=1
         0: new           #16                 // class java/util/ArrayList
         3: dup
         4: invokespecial #18                 // Method java/util/ArrayList."<init>":()V
         7: astore_1
         8: aload_1
         9: ldc           #19                 // String 111
        11: invokeinterface #21,  2           // InterfaceMethod java/util/List.add:(Ljava/lang/Object;)Z
        16: pop
        17: aload_1
        18: ldc           #27                 // String 222
        20: invokeinterface #21,  2           // InterfaceMethod java/util/List.add:(Ljava/lang/Object;)Z
        25: pop
        26: aload_1
        27: invokeinterface #29,  1           // InterfaceMethod java/util/List.iterator:()Ljava/util/Iterator;

As we can see from the last line of the sample, the compiler will automatically convert the use of for-each keyword to the use of an Iterator at compile time. That may explain why object, which doesn't implement the Iterable interface, will throw an Exception when it tries to use the for-each loop.

Python equivalent of a given wget command

easy as py:

class Downloder():
    def download_manager(self, url, destination='Files/DownloderApp/', try_number="10", time_out="60"):
        #threading.Thread(target=self._wget_dl, args=(url, destination, try_number, time_out, log_file)).start()
        if self._wget_dl(url, destination, try_number, time_out, log_file) == 0:
            return True
        else:
            return False


    def _wget_dl(self,url, destination, try_number, time_out):
        import subprocess
        command=["wget", "-c", "-P", destination, "-t", try_number, "-T", time_out , url]
        try:
            download_state=subprocess.call(command)
        except Exception as e:
            print(e)
        #if download_state==0 => successfull download
        return download_state

Javascript Array.sort implementation?

If you look at this bug 224128, it appears that MergeSort is being used by Mozilla.

Make HTML5 video poster be same size as video itself

You can use poster to show image instead of video on mobile device(or devices which doesn't support the video autoplay functionality). Because mobile devices not support video autoplay functionality.

<div id="wrap_video">
<video preload="preload" id="Video" autoplay="autoplay" loop="loop" poster="default.jpg">
<source src="Videos.mp4" type="video/mp4">
Your browser does not support the <code>video</code> tag.
</video>
</div>

Now you can just style the poster attribute which is inside the video tag for mobile device via media-query.

#wrap_video
{
width:480px;
height:360px;
position: relative;
} 
@media (min-width:360px) and (max-width:780px)
{
video[poster]
{
top:0 !important;
left:0 !important;
width:480px !important;
height:360px !important;
position: absolute !important;
}
}

Reference - What does this error mean in PHP?

Notice: Undefined variable

Happens when you try to use a variable that wasn't previously defined.

A typical example would be

foreach ($items as $item) {
    // do something with item
    $counter++;
}

If you didn't define $counter before, the code above will trigger the notice.

The correct way would be to set the variable before using it, even if it's just an empty string like

$counter = 0;
foreach ($items as $item) {
    // do something with item
    $counter++;
}

Similarly, a variable is not accessible outside its scope, for example when using anonymous functions.

$prefix = "Blueberry";
$food = ["cake", "cheese", "pie"];
$prefixedFood = array_map(function ($food) {
  // Prefix is undefined
  return "${prefix} ${food}";
}, $food);

This should instead be passed using use

$prefix = "Blueberry";
$food = ["cake", "cheese", "pie"];
$prefixedFood = array_map(function ($food) use ($prefix) {
  return "${prefix} ${food}";
}, $food);

Notice: Undefined property

This error means much the same thing, but refers to a property of an object. Reusing the example above, this code would trigger the error because the counter property hasn't been set.

$obj = new stdclass;
$obj->property = 2342;
foreach ($items as $item) {
    // do something with item
    $obj->counter++;
}

Related Questions:

ASP.NET Web API - PUT & DELETE Verbs Not Allowed - IIS 8

Remove the WebDAV works perfectly for my case:

<modules>
  <remove name="WebDAVModule"/>
</modules>
<handlers>
  <remove name="WebDAV" />
  <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
  <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" 
       type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>

it always better to solve the problem through the web.config instead of going to fix it through the iis or machine.config to grantee it wouldn't happen if the app hosted at another machine

how to set select element as readonly ('disabled' doesnt pass select value on server)

To be able to pass the select, I just set it back to :

  $('#selectID').prop('disabled',false);

or

  $('#selectID').attr('disabled',false);

when passing the request.

Counting the number of elements in array

Just use the length filter on the whole array. It works on more than just strings:

{{ notcount|length }}

Format XML string to print friendly XML string

The simple solution that is working for me:

        XmlDocument xmlDoc = new XmlDocument();
        StringWriter sw = new StringWriter();
        xmlDoc.LoadXml(rawStringXML);
        xmlDoc.Save(sw);
        String formattedXml = sw.ToString();

How can I use Guzzle to send a POST request in JSON?

The answer from @user3379466 can be made to work by setting $data as follows:

$data = "{'some_key' : 'some_value'}";

What our project needed was to insert a variable into an array inside the json string, which I did as follows (in case this helps anyone):

$data = "{\"collection\" : [$existing_variable]}";

So with $existing_variable being, say, 90210, you get:

echo $data;
//{"collection" : [90210]}

Also worth noting is that you might want to also set the 'Accept' => 'application/json' as well in case the endpoint you're hitting cares about that kind of thing.

How to position a div scrollbar on the left hand side?

Here is what I have done to make the right scroll bar work. The only thing needed to be considered is when using 'direction: rtl' and whole table also need to be changed. Hopefully this gives you an idea how to do it.

Example:

<table dir='rtl'><tr><td>Display Last</td><td>Display Second</td><td>Display First</td></table>

Check this: JSFiddle

HTML -- two tables side by side

You can place your tables in a div and add style to your table "float: left"

<div>
  <table style="float: left">
    <tr>
      <td>..</td>
    </tr>
  </table>
  <table style="float: left">
    <tr>
      <td>..</td>
    </tr>
  </table>
</div>

or simply use css:

div>table {
  float: left
}

What does this error mean: "error: expected specifier-qualifier-list before 'type_name'"?

You have to name your struct like that:

typedef struct car_t {

   char

   wheel_t

} car_t;

How do I get the function name inside a function in PHP?

<?php

  class Test {
     function MethodA(){
         echo __FUNCTION__ ;
     }
 }
 $test = new Test;
 echo $test->MethodA();
?>

Result: "MethodA";

how to show confirmation alert with three buttons 'Yes' 'No' and 'Cancel' as it shows in MS Word

If you don't want to use a separate JS library to create a custom control for that, you could use two confirm dialogs to do the checks:

if (confirm("Are you sure you want to quit?") ) {
    if (confirm("Save your work before leaving?") ) {
        // code here for save then leave (Yes)
    } else {
        //code here for no save but leave (No)
    }
} else {
    //code here for don't leave (Cancel)
}

How to create a signed APK file using Cordova command line interface?

For Windows, I've created a build.cmd file:

(replace the keystore path and alias)

For Cordova:

@echo off 
set /P spassw="Store Password: " && set /P kpassw="Key Password: " && cordova build android --release -- --keystore=../../local/my.keystore --storePassword=%spassw% --alias=tmpalias --password=%kpassw%

And for Ionic:

@echo off 
set /P spassw="Store Password: " && set /P kpassw="Key Password: " && ionic build --prod && cordova build android --release -- --keystore=../../local/my.keystore --storePassword=%spassw% --alias=tmpalias --password=%kpassw%

Save it in the ptoject's directory, you can double click or open it with cmd.

LINQ order by null column where order is ascending and nulls should be last

my decision:

Array = _context.Products.OrderByDescending(p => p.Val ?? float.MinValue)

Python - Create list with numbers between 2 values?

The most elegant way to do this is by using the range function however if you want to re-create this logic you can do something like this :

def custom_range(*args):
    s = slice(*args)
    start, stop, step = s.start, s.stop, s.step
    if 0 == step:
        raise ValueError("range() arg 3 must not be zero")
    i = start
    while i < stop if step > 0 else i > stop:
        yield i
        i += step

>>> [x for x in custom_range(10, 3, -1)]

This produces the output:

[10, 9, 8, 7, 6, 5, 4]

As expressed before by @Jared, the best way is to use the range or numpy.arrange however I find the code interesting to be shared.

Find object by id in an array of JavaScript objects

As you are already using jQuery, you can use the grep function which is intended for searching an array:

var result = $.grep(myArray, function(e){ return e.id == id; });

The result is an array with the items found. If you know that the object is always there and that it only occurs once, you can just use result[0].foo to get the value. Otherwise you should check the length of the resulting array. Example:

if (result.length === 0) {
  // no result found
} else if (result.length === 1) {
  // property found, access the foo property using result[0].foo
} else {
  // multiple items found
}

Python Selenium Chrome Webdriver

You need to specify the path where your chromedriver is located.

  1. Download chromedriver for your desired platform from here.

  2. Place chromedriver on your system path, or where your code is.

  3. If not using a system path, link your chromedriver.exe (For non-Windows users, it's just called chromedriver):

    browser = webdriver.Chrome(executable_path=r"C:\path\to\chromedriver.exe")
    

    (Set executable_path to the location where your chromedriver is located.)

    If you've placed chromedriver on your System Path, you can shortcut by just doing the following:

    browser = webdriver.Chrome()

  4. If you're running on a Unix-based operating system, you may need to update the permissions of chromedriver after downloading it in order to make it executable:

    chmod +x chromedriver

  5. That's all. If you're still experiencing issues, more info can be found on this other StackOverflow article: Can't use chrome driver for Selenium

Is it possible to change javascript variable values while debugging in Google Chrome?

To modify a value every time a block of code runs without having to break execution flow:

The "Logpoints" feature in the debugger is designed to let you log arbitrary values to the console without breaking. It evaluates code inside the flow of execution, which means you can actually use it to change values on the fly without stopping.

Right-click a line number and choose "Logpoint," then enter the assignment expression. It looks something like this:

enter image description here

I find it super useful for setting values to a state not otherwise easy to reproduce, without having to rebuild my project with debug lines in it. REMEMBER to delete the breakpoint when you're done!

How to restart adb from root to user mode?

I would like to add a little more explanation to @user837048's answer. on my OSX Yosemite and Galaxy S3 which is rooted and using firmware CyanogenMod 11 and KitKat I have done the below proceedings to Enable and Disable root prompt.

Please make ensure below

  • On your system

    • Make sure you have installed Android SDK and you have set paths to binary files. type which adb on your shell. It must give you somewhat result. $ which adb /Applications/Android Studio.app/sdk/platform-tools/adb
  • On your Mobile

    • Settings > Developer Options> Android Debugging = ON
    • Settings > Developer Options> Root Access = Apps and ADB

If you don't see Developer Options in your settings, Goto Settings > About Phone. Scroll down to Build number and tap there 7 times. I know its crazy. But believe me it works :D

Connect your phone via USB Cable. type on your computer's terminal

$ adb shell

you will see a prompt similiar, If any prompt has been shown on your mobile, to trust the connection, tap 'Always Trust' and 'OK'

shell@m0:/ $

now type

shell@m0:/ $ id
uid=2000(shell) gid=2000(shell) groups=1004(input),1007(log),1011(adb),1015(sdcard_rw),1028(sdcard_r),3001(net_bt_admin),3002(net_bt),3003(inet),3006(net_bw_stats) context=u:r:shell:s0

See you are not root

Now exit from shell, which will fall back to computer's prompt

shell@m0:/ $ exit

Now activate root

$adb shell
* daemon not running. starting it now on port 5037 *
* daemon started successfully *
root@m0:/ #

Wow.. you are root

root@m0:/ # id
uid=0(root) gid=0(root) context=u:r:shell:s0

I tried many solutions to go back to normal non root prompt. But didn't worked except @user837048's solution.

root@m0:/ # stop adbd && setprop service.adb.root 0 && start adbd &
[1] 32137
root@m0:/ #
$

This might exit you from Adb prompt to normal prompt. Now connect again.

$ adb shell
shell@m0:/ $

Well.. You are Non root

jquery $(window).width() and $(window).height() return different values when viewport has not been resized

I think what you're seeing is the hiding and showing of scrollbars. Here's a quick demo showing the width change.

As an aside: do you need to poll constantly? You might be able to optimize your code to run on the resize event, like this:

$(window).resize(function() {
  //update stuff
});

Node.js/Express routing with get params

Your route isn't ok, it should be like this (with ':')

app.get('/documents/:format/:type', function (req, res) {
   var format = req.params.format,
       type = req.params.type;
});

Also you cannot interchange parameter order unfortunately. For more information on req.params (and req.query) check out the api reference here.

How does DateTime.Now.Ticks exactly work?

You can get the milliseconds since 1/1/1970 using such code:

private static DateTime JanFirst1970 = new DateTime(1970, 1, 1);
public static long getTime()
{
    return (long)((DateTime.Now.ToUniversalTime() - JanFirst1970).TotalMilliseconds + 0.5);
}

Why do I need an IoC container as opposed to straightforward DI code?

I'm with you, Vadim. IoC containers take a simple, elegant, and useful concept, and make it something you have to study for two days with a 200-page manual.

I personally am perplexed at how the IoC community took a beautiful, elegant article by Martin Fowler and turned it into a bunch of complex frameworks typically with 200-300 page manuals.

I try not to be judgemental (HAHA!), but I think that people who use IoC containers are (A) very smart and (B) lacking in empathy for people who aren't as smart as they are. Everything makes perfect sense to them, so they have trouble understanding that many ordinary programmers will find the concepts confusing. It's the curse of knowledge. The people who understand IoC containers have trouble believing that there are people who don't understand it.

The most valuable benefit of using an IoC container is that you can have a configuration switch in one place which lets you change between, say, test mode and production mode. For example, suppose you have two versions of your database access classes... one version which logged aggressively and did a lot of validation, which you used during development, and another version without logging or validation that was screamingly fast for production. It is nice to be able to switch between them in one place. On the other hand, this is a fairly trivial problem easily handled in a simpler way without the complexity of IoC containers.

I believe that if you use IoC containers, your code becomes, frankly, a lot harder to read. The number of places you have to look at to figure out what the code is trying to do goes up by at least one. And somewhere in heaven an angel cries out.

Javascript close alert box

The only real alternative here is to use some sort of custom widget with a modal option. Have a look at jQuery UI for an example of a dialog with these features. Similar things exist in just about every JS framework you can mention.

Automatically deleting related rows in Laravel (Eloquent ORM)

I believe this is a perfect use-case for Eloquent events (http://laravel.com/docs/eloquent#model-events). You can use the "deleting" event to do the cleanup:

class User extends Eloquent
{
    public function photos()
    {
        return $this->has_many('Photo');
    }

    // this is a recommended way to declare event handlers
    public static function boot() {
        parent::boot();

        static::deleting(function($user) { // before delete() method call this
             $user->photos()->delete();
             // do the rest of the cleanup...
        });
    }
}

You should probably also put the whole thing inside a transaction, to ensure the referential integrity..

using stored procedure in entity framework

After importing stored procedure, you can create object of stored procedure pass the parameter like function

using (var entity = new FunctionsContext())
{
   var DBdata = entity.GetFunctionByID(5).ToList<Functions>();
}

or you can also use SqlQuery

using (var entity = new FunctionsContext())
{
    var Parameter = new SqlParameter {
                     ParameterName = "FunctionId",
                     Value = 5
            };

    var DBdata = entity.Database.SqlQuery<Course>("exec GetFunctionByID @FunctionId ", Parameter).ToList<Functions>();
}

Postgresql : Connection refused. Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections

The error you quote has nothing to do with pg_hba.conf; it's failing to connect, not failing to authorize the connection.

Do what the error message says:

Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections

You haven't shown the command that produces the error. Assuming you're connecting on localhost port 5432 (the defaults for a standard PostgreSQL install), then either:

  • PostgreSQL isn't running

  • PostgreSQL isn't listening for TCP/IP connections (listen_addresses in postgresql.conf)

  • PostgreSQL is only listening on IPv4 (0.0.0.0 or 127.0.0.1) and you're connecting on IPv6 (::1) or vice versa. This seems to be an issue on some older Mac OS X versions that have weird IPv6 socket behaviour, and on some older Windows versions.

  • PostgreSQL is listening on a different port to the one you're connecting on

  • (unlikely) there's an iptables rule blocking loopback connections

(If you are not connecting on localhost, it may also be a network firewall that's blocking TCP/IP connections, but I'm guessing you're using the defaults since you didn't say).

So ... check those:

  • ps -f -u postgres should list postgres processes

  • sudo lsof -n -u postgres |grep LISTEN or sudo netstat -ltnp | grep postgres should show the TCP/IP addresses and ports PostgreSQL is listening on

BTW, I think you must be on an old version. On my 9.3 install, the error is rather more detailed:

$ psql -h localhost -p 12345
psql: could not connect to server: Connection refused
        Is the server running on host "localhost" (::1) and accepting
        TCP/IP connections on port 12345?

Best way to update data with a RecyclerView adapter

Found following solution working for my similar problem:

private ExtendedHashMap mData = new ExtendedHashMap();
private  String[] mKeys;

public void setNewData(ExtendedHashMap data) {
    mData.putAll(data);
    mKeys = data.keySet().toArray(new String[data.size()]);
    notifyDataSetChanged();
}

Using the clear-command

mData.clear()

is not nessescary

How to edit CSS style of a div using C# in .NET

Add the runat="server" attribute to the tag, then you can reference it from the codebehind.

Directing print output to a .txt file

One can directly store the returned output of a function in a file.

print(output statement, file=open("filename", "a"))

Conversion failed when converting the nvarchar value ... to data type int

You got this Error because you tried to convert column DataType from String to int which is

leagal if and only if

you dont have row in that table with string content inside that column

so just make sure your previously inserted Rows is compatible with the new changes

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

// CHANGE name="select2" TO name="select2[]" THEN
<?php
  $mySelection = $_GET['select2'];

  $nSelection = count($MySelection);

  for($i=0; $i < $nSelection; $i++)
   {
      $numberVal = $MySelection[$i];

        if ($numberVal == "11"){
         echo("Eleven"); 
         }
        else if ($numberVal == "12"){
         echo("Twelve"); 
         } 
         ...

         ...
    }
?>

OpenCV - DLL missing, but it's not?

just open the bin folder and copy and paste the .dll files to the folder you are working in..it should fix the problem

Matplotlib - global legend and title aside subplots

suptitle seems the way to go, but for what it's worth, the figure has a transFigure property that you can use:

fig=figure(1)
text(0.5, 0.95, 'test', transform=fig.transFigure, horizontalalignment='center')

Correct way to write loops for promise.

I'd make something like this:

var request = []
while(count<10){
   request.push(db.getUser(email).then(function(res) { return res; }));
   count++
};

Promise.all(request).then((dataAll)=>{
  for (var i = 0; i < dataAll.length; i++) {

      logger.log(dataAll[i]); 
  }  
});

in this way, dataAll is an ordered array of all element to log. And log operation will perform when all promises are done.

onchange event for html.dropdownlist

You can try this if you are passing a value to the action method.

@Html.DropDownList("Sortby", new SelectListItem[] { new SelectListItem() { Text = "Newest to Oldest", Value = "0" }, new SelectListItem() { Text = "Oldest to Newest", Value = "1" }},new { onchange = "document.location.href = '/ControllerName/ActionName?id=' + this.options[this.selectedIndex].value;" })

Remove the query string in case of no parameter passing.

How do I resolve `The following packages have unmet dependencies`

Installing nodejs will install npm ... so just remove nodejs then reinstall it: $ sudo apt-get remove nodejs

$ sudo apt-get --purge remove nodejs node npm
$ sudo apt-get clean
$ sudo apt-get autoclean
$ sudo apt-get -f install
$ sudo apt-get autoremove

How to hide image broken Icon using only CSS/HTML?

Using CSS only is tough, but you could use CSS's background-image instead of <img> tags...

Something like this:

HTML

<div id="image"></div>

CSS

#image {
    background-image: url(Error.src);
    width: //width of image;
    height: //height of image;

}

Here is a working fiddle.

Note: I added the border in the CSS on the fiddle just to demonstrate where the image would be.

Debugging with Android Studio stuck at "Waiting For Debugger" forever

Got it fixed according this solution: https://youtrack.jetbrains.com/issue/IDEA-166153
I opened <project dir>/.idea/workspace.xml replaced all the
<option name="DEBUGGER_TYPE" value="Auto" /> occurrences to
<option name="DEBUGGER_TYPE" value="Java" />
and restarted Android Studio

Find Java classes implementing an interface

The code you are talking about sounds like ServiceLoader, which was introduced in Java 6 to support a feature that has been defined since Java 1.3 or earlier. For performance reasons, this is the recommended approach to find interface implementations at runtime; if you need support for this in an older version of Java, I hope that you'll find my implementation helpful.

There are a couple of implementations of this in earlier versions of Java, but in the Sun packages, not in the core API (I think there are some classes internal to ImageIO that do this). As the code is simple, I'd recommend providing your own implementation rather than relying on non-standard Sun code which is subject to change.

Conditionally ignoring tests in JUnit 4

You should checkout Junit-ext project. They have RunIf annotation that performs conditional tests, like:

@Test
@RunIf(DatabaseIsConnected.class)
public void calculateTotalSalary() {
    //your code there
}

class DatabaseIsConnected implements Checker {
   public boolean satisify() {
        return Database.connect() != null;
   }
}

[Code sample taken from their tutorial]

onclick="location.href='link.html'" does not load page in Safari

Give this a go:

<option onclick="parent.location='#5.2'">Bookmark 2</option>

Change the color of a checked menu item in a navigation drawer

Step 1: Build a checked/unchecked selector:

selector.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:color="@color/yellow" android:state_checked="true" />
    <item android:color="@color/white" android:state_checked="false" />
</selector>

Step 2: use the xml attribute app:itemTextColor within NavigationView widget for selecting the text color.

<android.support.design.widget.NavigationView
    android:id="@+id/nav_view"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    app:headerLayout="@layout/navigation_header_layout"
    app:itemTextColor="@drawable/selector"
    app:menu="@menu/navigation_menu" />

Step 3:
For some reason when you hit an item from the NavigationView menu, it doesn't consider this as a button check. So you need to manually get the selected item checked and clear the previously selected item. Use below listener to do that

@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {

    int id = item.getItemId();

    // remove all colors of the items to the `unchecked` state of the selector
    removeColor(mNavigationView);

    // check the selected item to change its color set by the `checked` state of the selector
    item.setChecked(true);

    switch (item.getItemId()) {
      case R.id.dashboard:
          ...
    }

    drawerLayout.closeDrawer(GravityCompat.START);
    return true;
}

private void removeColor(NavigationView view) {
    for (int i = 0; i < view.getMenu().size(); i++) {
        MenuItem item = view.getMenu().getItem(i);
        item.setChecked(false);
    }
}

Step 4:
To change icon color, use the app:iconTint attribute in the NavigationView menu items, and set to the same selector.

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <item
        android:id="@+id/nav_account"
        android:checked="true"
        android:icon="@drawable/ic_person_black_24dp"
        android:title="My Account"
        app:iconTint="@drawable/selector" />
    <item
        android:id="@+id/nav_settings"
        android:icon="@drawable/ic_settings_black_24dp"
        android:title="Settings"
        app:iconTint="@drawable/selector" />

    <item
        android:id="@+id/nav_logout"
        android:icon="@drawable/logout"
        android:title="Log Out"
        app:iconTint="@drawable/selector" />
</menu>

Result:

How do I execute a command and get the output of the command within C++ using POSIX?

Assuming POSIX, simple code to capture stdout:

#include <sys/wait.h>
#include <unistd.h>
#include <string>
#include <vector>

std::string qx(const std::vector<std::string>& args) {
  int stdout_fds[2];
  pipe(stdout_fds);

  int stderr_fds[2];
  pipe(stderr_fds);

  const pid_t pid = fork();
  if (!pid) {
    close(stdout_fds[0]);
    dup2(stdout_fds[1], 1);
    close(stdout_fds[1]);

    close(stderr_fds[0]);
    dup2(stderr_fds[1], 2);
    close(stderr_fds[1]);

    std::vector<char*> vc(args.size() + 1, 0);
    for (size_t i = 0; i < args.size(); ++i) {
      vc[i] = const_cast<char*>(args[i].c_str());
    }

    execvp(vc[0], &vc[0]);
    exit(0);
  }

  close(stdout_fds[1]);

  std::string out;
  const int buf_size = 4096;
  char buffer[buf_size];
  do {
    const ssize_t r = read(stdout_fds[0], buffer, buf_size);
    if (r > 0) {
      out.append(buffer, r);
    }
  } while (errno == EAGAIN || errno == EINTR);

  close(stdout_fds[0]);

  close(stderr_fds[1]);
  close(stderr_fds[0]);

  int r, status;
  do {
    r = waitpid(pid, &status, 0);
  } while (r == -1 && errno == EINTR);

  return out;
}

Code contributions are welcome for more functionality:

https://github.com/ericcurtin/execxx

"Could not get any response" response when using postman with subdomain

I had the same issue.

Turned out my timeout was set too low. I changed it to 30ms thinking it was 30sec. I set it back to 0 and it started working again.

How do you dynamically add elements to a ListView on Android?

Create an XML layout first in your project's res/layout/main.xml folder:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >
    <Button
        android:id="@+id/addBtn"
        android:text="Add New Item"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:onClick="addItems"/>
    <ListView
        android:id="@android:id/list"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:drawSelectorOnTop="false"
    />
</LinearLayout>

This is a simple layout with a button on the top and a list view on the bottom. Note that the ListView has the id @android:id/list which defines the default ListView a ListActivity can use.

public class ListViewDemo extends ListActivity {
    //LIST OF ARRAY STRINGS WHICH WILL SERVE AS LIST ITEMS
    ArrayList<String> listItems=new ArrayList<String>();

    //DEFINING A STRING ADAPTER WHICH WILL HANDLE THE DATA OF THE LISTVIEW
    ArrayAdapter<String> adapter;

    //RECORDING HOW MANY TIMES THE BUTTON HAS BEEN CLICKED
    int clickCounter=0;

    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setContentView(R.layout.main);
        adapter=new ArrayAdapter<String>(this,
            android.R.layout.simple_list_item_1,
            listItems);
        setListAdapter(adapter);
    }

    //METHOD WHICH WILL HANDLE DYNAMIC INSERTION
    public void addItems(View v) {
        listItems.add("Clicked : "+clickCounter++);
        adapter.notifyDataSetChanged();
    }
}

android.R.layout.simple_list_item_1 is the default list item layout supplied by Android, and you can use this stock layout for non-complex things.

listItems is a List which holds the data shown in the ListView. All the insertion and removal should be done on listItems; the changes in listItems should be reflected in the view. That's handled by ArrayAdapter<String> adapter, which should be notified using:

adapter.notifyDataSetChanged();

An Adapter is instantiated with 3 parameters: the context, which could be your activity/listactivity; the layout of your individual list item; and lastly, the list, which is the actual data to be displayed in the list.

Remove Select arrow on IE

In case you want to use the class and pseudo-class:

.simple-control is your css class

:disabled is pseudo class

select.simple-control:disabled{
         /*For FireFox*/
        -webkit-appearance: none;
        /*For Chrome*/
        -moz-appearance: none;
}

/*For IE10+*/
select:disabled.simple-control::-ms-expand {
        display: none;
}

How can I use a DLL file from Python?

For ease of use, ctypes is the way to go.

The following example of ctypes is from actual code I've written (in Python 2.5). This has been, by far, the easiest way I've found for doing what you ask.

import ctypes

# Load DLL into memory.

hllDll = ctypes.WinDLL ("c:\\PComm\\ehlapi32.dll")

# Set up prototype and parameters for the desired function call.
# HLLAPI

hllApiProto = ctypes.WINFUNCTYPE (
    ctypes.c_int,      # Return type.
    ctypes.c_void_p,   # Parameters 1 ...
    ctypes.c_void_p,
    ctypes.c_void_p,
    ctypes.c_void_p)   # ... thru 4.
hllApiParams = (1, "p1", 0), (1, "p2", 0), (1, "p3",0), (1, "p4",0),

# Actually map the call ("HLLAPI(...)") to a Python name.

hllApi = hllApiProto (("HLLAPI", hllDll), hllApiParams)

# This is how you can actually call the DLL function.
# Set up the variables and call the Python name with them.

p1 = ctypes.c_int (1)
p2 = ctypes.c_char_p (sessionVar)
p3 = ctypes.c_int (1)
p4 = ctypes.c_int (0)
hllApi (ctypes.byref (p1), p2, ctypes.byref (p3), ctypes.byref (p4))

The ctypes stuff has all the C-type data types (int, char, short, void*, and so on) and can pass by value or reference. It can also return specific data types although my example doesn't do that (the HLL API returns values by modifying a variable passed by reference).


In terms of the specific example shown above, IBM's EHLLAPI is a fairly consistent interface.

All calls pass four void pointers (EHLLAPI sends the return code back through the fourth parameter, a pointer to an int so, while I specify int as the return type, I can safely ignore it) as per IBM's documentation here. In other words, the C variant of the function would be:

int hllApi (void *p1, void *p2, void *p3, void *p4)

This makes for a single, simple ctypes function able to do anything the EHLLAPI library provides, but it's likely that other libraries will need a separate ctypes function set up per library function.

The return value from WINFUNCTYPE is a function prototype but you still have to set up more parameter information (over and above the types). Each tuple in hllApiParams has a parameter "direction" (1 = input, 2 = output and so on), a parameter name and a default value - see the ctypes doco for details

Once you have the prototype and parameter information, you can create a Python "callable" hllApi with which to call the function. You simply create the needed variable (p1 through p4 in my case) and call the function with them.

Determining type of an object in ruby

Oftentimes in Ruby, you don't actually care what the object's class is, per se, you just care that it responds to a certain method. This is known as Duck Typing and you'll see it in all sorts of Ruby codebases.

So in many (if not most) cases, its best to use Duck Typing using #respond_to?(method):

object.respond_to?(:to_i)

How do I enumerate through a JObject?

The answer did not work for me. I dont know how it got so many votes. Though it helped in pointing me in a direction.

This is the answer that worked for me:

foreach (var x in jobj)
{
    var key = ((JProperty) (x)).Name;
    var jvalue = ((JProperty)(x)).Value ;
}

How can I take an UIImage and give it a black border?

If you know the dimensions of your image, then adding a border to the UIImageView's layer is the best solution AFAIK. Infact, you can simply setFrame your imageView to x,y,image.size.width,image.size.height

In case you have an ImageView of a fixed size with dynamically loaded images which are getting resized (or scaled to AspectFit), then your aim is to resize the imageview to the new resized image.

The shortest way to do this:

// containerView is my UIImageView
containerView.layer.borderWidth = 7;
containerView.layer.borderColor = [UIColor colorWithRed:0.22 green:0.22 blue:0.22 alpha:1.0].CGColor;

// this is the key command
[containerView setFrame:AVMakeRectWithAspectRatioInsideRect(image.size, containerView.frame)];

But to use the AVMakeRectWithAspectRatioInsideRect, you need to add this

#import <AVFoundation/AVFoundation.h>

import statement to your file and also include the AVFoundation framework in your project (comes bundled with the SDK).

Python list directory, subdirectory, and files

Here is a one-liner:

import os

[val for sublist in [[os.path.join(i[0], j) for j in i[2]] for i in os.walk('./')] for val in sublist]
# Meta comment to ease selecting text

The outer most val for sublist in ... loop flattens the list to be one dimensional. The j loop collects a list of every file basename and joins it to the current path. Finally, the i loop iterates over all directories and sub directories.

This example uses the hard-coded path ./ in the os.walk(...) call, you can supplement any path string you like.

Note: os.path.expanduser and/or os.path.expandvars can be used for paths strings like ~/

Extending this example:

Its easy to add in file basename tests and directoryname tests.

For Example, testing for *.jpg files:

... for j in i[2] if j.endswith('.jpg')] ...

Additionally, excluding the .git directory:

... for i in os.walk('./') if '.git' not in i[0].split('/')]

Attribute 'nowrap' is considered outdated. A newer construct is recommended. What is it?

There are several ways to try to prevent line breaks, and the phrase “a newer construct” might refer to more than one way—that’s actually the most reasonable interpretation. They probably mostly think of the CSS declaration white-space:nowrap and possibly the no-break space character. The different ways are not equivalent, far from that, both in theory and especially in practice, though in some given case, different ways might produce the same result.

There is probably nothing real to be gained by switching from the HTML attribute to the somewhat clumsier CSS way, and you would surely lose when style sheets are disabled. But even the nowrap attribute does no work in all situations. In general, what works most widely is the nobr markup, which has never made its way to any specifications but is alive and kicking: <td><nobr>...</nobr></td>.

What is an MDF file?

SQL Server databases use two files - an MDF file, known as the primary database file, which contains the schema and data, and a LDF file, which contains the logs. See wikipedia. A database may also use secondary database file, which normally uses a .ndf extension.

As John S. indicates, these file extensions are purely convention - you can use whatever you want, although I can't think of a good reason to do that.

More info on MSDN here and in Beginning SQL Server 2005 Administation (Google Books) here.

How does one use the onerror attribute of an img element

very simple

  <img onload="loaded(this, 'success')" onerror="error(this, 
 'error')"  src="someurl"  alt="" />

 function loaded(_this, status){
   console.log(_this, status)
  // do your work in load
 }
 function error(_this, status){
  console.log(_this, status)
  // do your work in error
  }

Difference between a theta join, equijoin and natural join

@outis's answer is good: concise and correct as regards relations.

However, the situation is slightly more complicated as regards SQL.

Consider the usual suppliers and parts database but implemented in SQL:

SELECT * FROM S NATURAL JOIN SP;

would return a resultset** with columns

SNO, SNAME, STATUS, CITY, PNO, QTY

The join is performed on the column with the same name in both tables, SNO. Note that the resultset has six columns and only contains one column for SNO.

Now consider a theta eqijoin, where the column names for the join must be explicitly specified (plus range variables S and SP are required):

SELECT * FROM S JOIN SP ON S.SNO = SP.SNO;

The resultset will have seven columns, including two columns for SNO. The names of the resultset are what the SQL Standard refers to as "implementation dependent" but could look like this:

SNO, SNAME, STATUS, CITY, SNO, PNO, QTY

or perhaps this

S.SNO, SNAME, STATUS, CITY, SP.SNO, PNO, QTY

In other words, NATURAL JOIN in SQL can be considered to remove columns with duplicated names from the resultset (but alas will not remove duplicate rows - you must remember to change SELECT to SELECT DISTINCT yourself).


** I don't quite know what the result of SELECT * FROM table_expression; is. I know it is not a relation because, among other reasons, it can have columns with duplicate names or a column with no name. I know it is not a set because, among other reasons, the column order is significant. It's not even a SQL table or SQL table expression. I call it a resultset.

How to add SHA-1 to android application

Alternatively you can use command line to get your SHA-1 fingerprint:

for your debug certificate you should use:

keytool -list -v -keystore C:\Users\user\.android\debug.keystore -alias androiddebugkey -storepass android -keypass android

you should change "c:\Users\user" with the path to your windows user directory

if you want to get the production SHA-1 for your own certificate, replace "C:\Users\user\.android\debug.keystore" with your custom KeyStore path and use your KeystorePass and Keypass instead of android/android.

Than declare the SHA-1 fingerprints you get to your firebase console as Damini said

What is the best way to implement constants in Java?

FWIW, a timeout in seconds value should probably be a configuration setting (read in from a properties file or through injection as in Spring) and not a constant.

Word-wrap in an HTML table

Check out this demo

_x000D_
_x000D_
   <table style="width: 100%;">_x000D_
    <tr>_x000D_
        <td><div style="word-break:break-all;">LongWordLongWordLongWordLongWordLongWordLongWordLongWordLongWordLongWordLongWordLongWordLongWordLongWordLongWordLongWordLongWordLongWordLongWordLongWordLongWordLongWordLongWordLongWordLongWordLongWordLongWordLongWordLongWordLongWordLongWordLongWordLongWordLongWordLongWordLongWordLongWordLongWordLongWordLongWordLongWord</div>_x000D_
        </td>_x000D_
        <td>_x000D_
            <span style="display: inline;">Foo</span>_x000D_
        </td>_x000D_
    </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

Here is the link to read

Prevent Caching in ASP.NET MVC for specific actions using an attribute

To ensure that JQuery isn't caching the results, on your ajax methods, put the following:

$.ajax({
    cache: false
    //rest of your ajax setup
});

Or to prevent caching in MVC, we created our own attribute, you could do the same. Here's our code:

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public sealed class NoCacheAttribute : ActionFilterAttribute
{
    public override void OnResultExecuting(ResultExecutingContext filterContext)
    {
        filterContext.HttpContext.Response.Cache.SetExpires(DateTime.UtcNow.AddDays(-1));
        filterContext.HttpContext.Response.Cache.SetValidUntilExpires(false);
        filterContext.HttpContext.Response.Cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
        filterContext.HttpContext.Response.Cache.SetCacheability(HttpCacheability.NoCache);
        filterContext.HttpContext.Response.Cache.SetNoStore();

        base.OnResultExecuting(filterContext);
    }
}

Then just decorate your controller with [NoCache]. OR to do it for all you could just put the attribute on the class of the base class that you inherit your controllers from (if you have one) like we have here:

[NoCache]
public class ControllerBase : Controller, IControllerBase

You can also decorate some of the actions with this attribute if you need them to be non-cacheable, instead of decorating the whole controller.

If your class or action didn't have NoCache when it was rendered in your browser and you want to check it's working, remember that after compiling the changes you need to do a "hard refresh" (Ctrl+F5) in your browser. Until you do so, your browser will keep the old cached version, and won't refresh it with a "normal refresh" (F5).

Default values for Vue component props & how to check if a user did not set the prop?

Also something important to add here, in order to set default values for arrays and objects we must use the default function for props:

propE: {
      type: Object,
      // Object or array defaults must be returned from
      // a factory function
      default: function () {
        return { message: 'hello' }
      }
    },

Good examples of python-memcache (memcached) being used in Python?

I would advise you to use pylibmc instead.

It can act as a drop-in replacement of python-memcache, but a lot faster(as it's written in C). And you can find handy documentation for it here.

And to the question, as pylibmc just acts as a drop-in replacement, you can still refer to documentations of pylibmc for your python-memcache programming.

How to set a Header field on POST a form?

If you are using JQuery with Form plugin, you can use:

$('#myForm').ajaxSubmit({
    headers: {
        "foo": "bar"
    }
});

Source: https://stackoverflow.com/a/31955515/9469069

Add CSS box shadow around the whole DIV

You're offsetting the shadow, so to get it to uniformly surround the box, don't offset it:

-moz-box-shadow: 0 0 3px #ccc;
-webkit-box-shadow: 0 0 3px #ccc;
box-shadow: 0 0 3px #ccc;

How to create an Array with AngularJS's ng-model

This should work.

app = angular.module('plunker', [])

app.controller 'MainCtrl', ($scope) ->
  $scope.users = ['bob', 'sean', 'rocky', 'john']
  $scope.test = ->
    console.log $scope.users

HTML:

<input ng-repeat="user in users" ng-model="user" type="text"/>
<input type="button" value="test" ng-click="test()" />

Example plunk here

How can I find the last element in a List<>?

Why not just use the Count property on the List?

for(int cnt3 = 0; cnt3 < integerList.Count; cnt3++)

Python coding standards/best practices

I follow it extremely rigorously. The only god before PEP-8 is existing code bases.

TensorFlow not found using pip

The only thing that worked for me was to use Ananconda and create a new conda env with conda create -n tensorflow python=3.5 then activate using activate tensorflow and finally conda install -c conda-forge tensorflow.

This works around every issue I had including ssl certs, proxy settings, and does not need admin access. It should be noted that this is not directly supported by the tensorflow team.

Source

How to call an async method from a getter or setter?

When I ran into this problem, trying to run an async method synchronicity from either a setter or a constructor got me into a deadlock on the UI thread, and using an event handler required too many changes in the general design.
The solution was, as often is, to just write explicitly what I wanted to happen implicitly, which was to have another thread handle the operation and to get the main thread to wait for it to finish:

string someValue=null;
var t = new Thread(() =>someValue = SomeAsyncMethod().Result);
t.Start();
t.Join();

You could argue that I abuse the framework, but it works.

How to clear all <div>s’ contents inside a parent <div>?

try them if it help.

$('.div_parent .div_child').empty();

$('#div_parent #div_child').empty();

How to delete a stash created with git stash create?

git stash           // create stash,
git stash push -m "message" // create stash with msg,
git stash apply         // to apply stash,
git stash apply indexno // to apply  specific stash, 
git stash list          //list stash,
git stash drop indexno      //to delete stash,
git stash pop indexno,
git stash pop = stash drop + stash apply
git stash clear         //clear all your local stashed code

Send data through routing paths in Angular

There is a lot of confusion on this topic because there are so many different ways to do it.

Here are the appropriate types used in the following screen shots:

private route: ActivatedRoute
private router: Router

1) Required Routing Parameters:

enter image description here

2) Route Optional Parameters:

enter image description here

3) Route Query Parameters:

enter image description here

4) You can use a service to pass data from one component to another without using route parameters at all.

For an example see: https://blogs.msmvps.com/deborahk/build-a-simple-angular-service-to-share-data/

I have a plunker of this here: https://plnkr.co/edit/KT4JLmpcwGBM2xdZQeI9?p=preview