Programs & Examples On #Popupmenu

Pop-up menus open to display a list of choices when triggered by the user.

Android custom dropdown/popup menu

The Kotlin Way

fun showPopupMenu(view: View) {
    PopupMenu(view.context, view).apply {
                menuInflater.inflate(R.menu.popup_men, menu)
                setOnMenuItemClickListener { item ->
                    Toast.makeText(view.context, "You Clicked : " + item.title, Toast.LENGTH_SHORT).show()
                    true
                }
            }.show()
}

UPDATE: In the above code, the apply function returns this which is not required, so we can use run which don't return anything and to make it even simpler we can also remove the curly braces of showPopupMenu method.

Even Simpler:

fun showPopupMenu(view: View) = PopupMenu(view.context, view).run {
            menuInflater.inflate(R.menu.popup_men, menu)
            setOnMenuItemClickListener { item ->
                Toast.makeText(view.context, "You Clicked : ${item.title}", Toast.LENGTH_SHORT).show()
                true
            }
            show()
        }

What is the best way to modify a list in a 'foreach' loop?

Make a copy of the enumeration, using an IEnumerable extension method in this case, and enumerate over it. This would add a copy of every element in every inner enumerable to that enumeration.

foreach(var item in Enumerable)
{
    foreach(var item2 in item.Enumerable.ToList())
    {
        item.Add(item2)
    }
}

How to call a parent method from child class in javascript?

While you can call the parent method by the prototype of the parent, you will need to pass the current child instance for using call, apply, or bind method. The bind method will create a new function so I doesn't recommend that if you care for performance except it only called once.

As an alternative you can replace the child method and put the parent method on the instance while calling the original child method.

_x000D_
_x000D_
function proxy(context, parent){
  var proto = parent.prototype;
  var list = Object.getOwnPropertyNames(proto);
  
  for(var i=0; i < list.length; i++){
    var key = list[i];

    // Create only when child have similar method name
    if(context[key] !== proto[key]){
      let currentMethod = context[key];
      let parentMethod = proto[key];
      
      context[key] = function(){
        context.super = parentMethod;
        return currentMethod.apply(context, arguments);
      }
    }
  }
}

// ========= The usage would be like this ==========

class Parent {
  first = "Home";

  constructor(){
    console.log('Parent created');
  }

  add(arg){
    return this.first + ", Parent "+arg;
  }
}

class Child extends Parent{
  constructor(b){
    super();
    proxy(this, Parent);
    console.log('Child created');
  }

  // Comment this to call method from parent only
  add(arg){
    return super.add(arg) + ", Child "+arg;
  }
}

var family = new Child();
console.log(family.add('B'));
_x000D_
_x000D_
_x000D_

What is the closest thing Windows has to fork()?

Well, windows doesn't really have anything quite like it. Especially since fork can be used to conceptually create a thread or a process in *nix.

So, I'd have to say:

CreateProcess()/CreateProcessEx()

and

CreateThread() (I've heard that for C applications, _beginthreadex() is better).

Using multiple IF statements in a batch file

IF EXIST "somefile.txt" (
  IF EXIST "someotherfile.txt" (
    SET var="somefile.txt","someotherfile.txt"
  )
) ELSE (
  CALL :SUB
)
:SUB
ECHO Sorry... nothin' there.
GOTO:EOF

Is this feasible?

SETLOCAL ENABLEDELAYEDEXPANSION
IF EXIST "somefile.txt" (
  SET var="somefile.txt"
  IF EXIST "someotherfile.txt" (
    SET var=!var!,"someotherfile.txt"
  )
) ELSE (
  IF EXIST "someotherfile.txt" (
    SET var="someotherfile.txt"
  ) ELSE (
  GOTO:EOF
  )
)

Checking for duplicate strings in JavaScript array

Use object keys for good performance when you work with a big array (in that case, loop for each element and loop again to check duplicate will be very slowly).

var strArray = ["q", "w", "w", "e", "i", "u", "r"];

var counting = {};
strArray.forEach(function (str) {
    counting[str] = (counting[str] || 0) + 1;
});

if (Object.keys(counting).length !== strArray.length) {
    console.log("Has duplicates");

    var str;
    for (str in counting) {
        if (counting.hasOwnProperty(str)) {
            if (counting[str] > 1) {
                console.log(str + " appears " + counting[str] + " times");
            }
        }
    }
}

Overflow Scroll css is not working in the div

If you set a static height for your header, you can use that in a calculation for the size of your wrapper.

http://jsfiddle.net/ske5Lqyv/5/

Using your example code, you can add this CSS:

html, body {
  margin: 0px;
  padding: 0px;
  height: 100%;
}

#container {
  height: 100%;
}

.header {
  height: 64px;
  background-color: lightblue;
}

.wrapper {
  height: calc(100% - 64px);
  overflow-y: auto;
}

Or, you can use flexbox for a more dynamic approach http://jsfiddle.net/19zbs7je/3/

<div id="container">
  <div class="section">
    <div class="header">Heading</div>
    <div class="wrapper">
      <p>Large Text</p>
    </div>
  </div>
</div>

html, body {
  margin: 0px;
  padding: 0px;
  height: 100%;
}

#container {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.section {
  flex-grow: 1;
  display: flex;
  flex-direction: column;
  min-height: 0;
}

.header {
  height: 64px;
  background-color: lightblue;
  flex-shrink: 0;
}

.wrapper {
  flex-grow: 1;
  overflow: auto;
  min-height: 100%; 
}

And if you'd like to get even fancier, take a look at my response to this question https://stackoverflow.com/a/52416148/1513083

Make Bootstrap's Carousel both center AND responsive?

Was having a very similar issue to this while using a CMS but it was not resolving with the above solution. What I did to solve it is put the following in the applicable css:

background-size: cover

and for placement purposes in case you are using bootstrap, I used:

background-position: center center /* or whatever position you wanted */

Newline in markdown table?

When you're exporting to HTML, using <br> works. However, if you're using pandoc to export to LaTeX/PDF as well, you should use grid tables:

+---------------+---------------+--------------------+
| Fruit         | Price         | Advantages         |
+===============+===============+====================+
| Bananas       | first line\   | first line\        |
|               | next line     | next line          |
+---------------+---------------+--------------------+
| Bananas       | first line\   | first line\        |
|               | next line     | next line          |
+---------------+---------------+--------------------+

How to delete empty folders using windows command prompt?

Install any UNIX interpreter for windows (Cygwin or Git Bash) and run the cmd:

find /path/to/directory -empty -type d

To find them

find /path/to/directory -empty -type d -delete

To delete them

(not really using the windows cmd prompt but it's easy and took few seconds to run)

java.security.InvalidAlgorithmParameterException: the trustAnchors parameter must be non-empty on Linux, or why is the default truststore empty

I have avoided this error (Java 1.6.0 on OSX 10.5.8) by putting a dummy cert in the keystore, such as

keytool -genkey -alias foo -keystore cacerts -dname cn=test -storepass changeit -keypass changeit

Surely the question should be "Why can't java handle an empty trustStore?"

How can I disable the bootstrap hover color for links?

If you like an ugly hacks which you should never do in real worlds systems; you could strip all :hover style rules from document.styleSheets.

Just go through all CSS styles with JavaScript and remove all rules, which contain ":hover" in their selector. I use this method when I need to remove :hover styles from bootstrap 2.

_.each(document.styleSheets, function (sheet) { 
    var rulesToLoose = []; 
    _.each(sheet.cssRules, function (rule, index) { 
        if (rule.selectorText && rule.selectorText.indexOf(':hover') > 0) { 
            rulesToLoose.push(index);
        }
    });

    _.each(rulesToLoose.reverse(), function (index) {
        if (sheet.deleteRule) {
            sheet.deleteRule(index);
        } else if (sheet.removeRule) {
            sheet.removeRule(index);
        }
    });
});

I did use underscore for iterating arrays, but one could write those with pure js loop as well:

for (var i = 0; i < document.styleSheets.length; i++) {}

JSON Java 8 LocalDateTime format in Spring Boot

I found another solution which you can convert it to whatever format you want and apply to all LocalDateTime datatype and you do not have to specify @JsonFormat above every LocalDateTime datatype. first add the dependency :

<dependency>
    <groupId>com.fasterxml.jackson.datatype</groupId>
    <artifactId>jackson-datatype-jsr310</artifactId>
</dependency>

Add the following bean :

@Configuration
public class Java8DateTimeConfiguration {
    /**
     * Customizing
     * http://docs.spring.io/spring-boot/docs/current/reference/html/howto-spring-mvc.html
     *
     * Defining a @Bean of type Jackson2ObjectMapperBuilder will allow you to customize both default ObjectMapper and XmlMapper (used in MappingJackson2HttpMessageConverter and MappingJackson2XmlHttpMessageConverter respectively).
     */
    @Bean
    public Module jsonMapperJava8DateTimeModule() {
        val bean = new SimpleModule();

        bean.addDeserializer (ZonedDateTime.class, new JsonDeserializer<ZonedDateTime>() {
            @Override
            public ZonedDateTime deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
                return ZonedDateTime.parse(jsonParser.getValueAsString(), DateTimeFormatter.ISO_ZONED_DATE_TIME);
            }
        });

        bean.addDeserializer(LocalDateTime.class, new JsonDeserializer<LocalDateTime>() {
            @Override
            public LocalDateTime deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
                return LocalDateTime.parse(jsonParser.getValueAsString(), DateTimeFormatter.ISO_LOCAL_DATE_TIME);
            }
        });

        bean.addSerializer(ZonedDateTime.class, new JsonSerializer<ZonedDateTime>() {
            @Override
            public void serialize(
                    ZonedDateTime zonedDateTime, JsonGenerator jsonGenerator, SerializerProvider serializerProvider)
                    throws IOException {
                jsonGenerator.writeString(DateTimeFormatter.ISO_ZONED_DATE_TIME.format(zonedDateTime));
            }
        });

        bean.addSerializer(LocalDateTime.class, new JsonSerializer<LocalDateTime>() {
            @Override
            public void serialize(
                    LocalDateTime localDateTime, JsonGenerator jsonGenerator, SerializerProvider serializerProvider)
                    throws IOException {
                jsonGenerator.writeString(DateTimeFormatter.ISO_LOCAL_DATE_TIME.format(localDateTime));
            }
        });

        return bean;
    }
}

in your config file add the following :

@Import(Java8DateTimeConfiguration.class)

This will serialize and de-serialize all properties LocalDateTime and ZonedDateTime as long as you are using objectMapper created by spring.

The format that you got for ZonedDateTime is : "2017-12-27T08:55:17.317+02:00[Asia/Jerusalem]" for LocalDateTime is : "2017-12-27T09:05:30.523"

Oracle date "Between" Query

As APC rightly pointed out, your start_date column appears to be a TIMESTAMP but it could be a TIMESTAMP WITH LOCAL TIMEZONE or TIMESTAMP WITH TIMEZONE datatype too. These could well influence any queries you were doing on the data if your database server was in a different timezone to yourself. However, let's keep this simple and assume you are in the same timezone as your server. First, to give you the confidence, check that the start_date is a TIMESTAMP data type.

Use the SQLPlus DESCRIBE command (or the equivalent in your IDE) to verify this column is a TIMESTAMP data type.

eg

DESCRIBE mytable

Should report :

Name        Null? Type
----------- ----- ------------
NAME              VARHAR2(20) 
START_DATE        TIMESTAMP

If it is reported as a Type = TIMESTAMP then you can query your date ranges with simplest TO_TIMESTAMP date conversion, one which requires no argument (or picture).

We use TO_TIMESTAMP to ensure that any index on the START_DATE column is considered by the optimizer. APC's answer also noted that a function based index could have been created on this column and that would influence the SQL predicate but we cannot comment on that in this query. If you want to know how to find out what indexes have been applied to table, post another question and we can answer that separately.

So, assuming there is an index on start_date, which is a TIMESTAMP datatype and you want the optimizer to consider it, your SQL would be :

select * from mytable where start_date between to_timestamp('15-JAN-10') AND to_timestamp('17-JAN-10')+.9999999

+.999999999 is very close to but isn't quite 1 so the conversion of 17-JAN-10 will be as close to midnight on that day as possible, therefore you query returns both rows.

The database will see the BETWEEN as from 15-JAN-10 00:00:00:0000000 to 17-JAN-10 23:59:59:99999 and will therefore include all dates from 15th,16th and 17th Jan 2010 whatever the time component of the timestamp.

Hope that helps.

Dazzer

Why can't I reference my class library?

I had a similar issue in VS 2010, when creating a test project for an MVC 2 application. The symptoms were identical.

The message from ReSharper was somewhat misleading. For a moment I completely ignored ReSharper and did it the "manual VS way":

  1. I cleaned the solution.
  2. I manually added the reference to the MVC project.
  3. I manually added the using directives.
  4. ctrl-shift-b

At this stage I got a compilation error: I should have referenced the System.Web.Mvc assembly in my test project (sigh). Adding this reference causes the project to compile. The ReSharper issues remain, but the ReSharper test runner works.

When I restart VS, the ReSharper errors are gone too. I'm not sure if the restart is required - simply closing the .cs file might be enough.

From now on, when I see the ReSharper message

Failed to reference module. Probably, reference will produce circular dependencies between projects.

I'll read

Failed to reference module. Probably, reference will produce circular dependencies between projects, or you are missing some references to dependencies of the reference's dependencies.

How to change status bar color to match app in Lollipop? [Android]

Add this line in style of v21 if you use two style.

  <item name="android:statusBarColor">#43434f</item>

Most efficient way to concatenate strings in JavaScript?

I did a quick test in both node and chrome and found in both cases += is faster:

var profile = func => { 
    var start = new Date();
    for (var i = 0; i < 10000000; i++) func('test');
    console.log(new Date() - start);
}
profile(x => "testtesttesttesttest");
profile(x => `${x}${x}${x}${x}${x}`);
profile(x => x + x + x + x + x );
profile(x => { var s = x; s += x; s += x; s += x; s += x; return s; });
profile(x => [x, x, x, x, x].join(""));
profile(x => { var a = [x]; a.push(x); a.push(x); a.push(x); a.push(x); return a.join(""); });

results in node: 7.0.10

  • assignment: 8
  • template literals: 524
  • plus: 382
  • plus equals: 379
  • array join: 1476
  • array push join: 1651

results from chrome 86.0.4240.198:

  • assignment: 6
  • template literals: 531
  • plus: 406
  • plus equals: 403
  • array join: 1552
  • array push join: 1813

How to make my layout able to scroll down?

For using scroll view along with Relative layout :

<ScrollView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:fillViewport="true"> <!--IMPORTANT otherwise backgrnd img. will not fill the whole screen -->

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingBottom="@dimen/activity_vertical_margin"
        android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:paddingTop="@dimen/activity_vertical_margin"
        android:background="@drawable/background_image"
    >

    <!-- Bla Bla Bla i.e. Your Textviews/Buttons etc. -->
    </RelativeLayout>
</ScrollView>

Scheduling Python Script to run every hour accurately

   #For scheduling task execution
import schedule
import time

def job():
    print("I'm working...")

schedule.every(1).minutes.do(job)
#schedule.every().hour.do(job)
#schedule.every().day.at("10:30").do(job)
#schedule.every(5).to(10).minutes.do(job)
#schedule.every().monday.do(job)
#schedule.every().wednesday.at("13:15").do(job)
#schedule.every().minute.at(":17").do(job)

while True:
    schedule.run_pending()
    time.sleep(1)

Cast from VARCHAR to INT - MySQL

For casting varchar fields/values to number format can be little hack used:

SELECT (`PROD_CODE` * 1) AS `PROD_CODE` FROM PRODUCT`

Convert Time DataType into AM PM Format:

In SQL 2012 you can use the Format() function.

https://technet.microsoft.com/en-us/library/hh213505%28v=sql.110%29.aspx

Skip casting if the column type is (datetime).

Example:

SELECT FORMAT(StartTime,'hh:mm tt') AS StartTime
FROM TableA

Requested registry access is not allowed

As a temporary fix, users can right click the utility and select "Run as administrator."

You must enable the openssl extension to download files via https

The Valery's answer helped me: https://stackoverflow.com/a/14265815/492457

WAMP uses different php.ini files in the CLI and for Apache. when you enable php_openssl through the WAMP UI, you enable it for Apache, not for the CLI. You need to modify C:\wamp\bin\php\php-5.4.3\php.ini to enable it for the CLI.

how to know status of currently running jobs

EXEC msdb.dbo.sp_help_job @Job_name = 'Your Job Name'

check field execution_status

0 - Returns only those jobs that are not idle or suspended.
1 - Executing.
2 - Waiting for thread.
3 - Between retries.
4 - Idle.
5 - Suspended.
7 - Performing completion actions.

If you need the result of execution, check the field last_run_outcome

0 = Failed
1 = Succeeded
3 = Canceled
5 = Unknown

https://msdn.microsoft.com/en-us/library/ms186722.aspx

What is the largest TCP/IP network port number allowable for IPv4?

It depends on which range you're talking about, but the dynamic range goes up to 65535 or 2^16-1 (16 bits).

http://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers

Get current time as formatted string in Go?

Find more info in this post: Get current date and time in various format in golang

This is a taste of the different formats that you'll find in the previous post:

enter image description here

RestTemplate: How to send URL and query parameters together

One simple way to do that is:

String url = "http://test.com/Services/rest/{id}/Identifier"

UriComponents uriComponents = UriComponentsBuilder.fromUriString(url).build();
uriComponents = uriComponents.expand(Collections.singletonMap("id", "1234"));

and then adds the query params.

Can I write or modify data on an RFID tag?

We have recently started looking into RFID solutions at my work place and we found a cheap solution for testing purposes.

One of the units from here:

http://www.sdid.com/products.shtml

Plugs into any windows mobile device with an SD slot and allows reading / writing. There is also a development kit to get you on your way with your own apps.

Hope this helps

How to delete a stash created with git stash create?

It also works

git stash drop <index>

like

git stash drop 5

How to Turn Off Showing Whitespace Characters in Visual Studio IDE

If the Toggle Visual Space icon shall be added to a Visual Studio toolbar of your choice, because it shall be turned on and off via mouse click, then follow this instruction:

  1. Customize the desired toolbar

  2. Click on Customize...

  3. Click on Add Command...

  4. Go to Edit and chose Toggle Visual Space

  5. Click on OK

Tested with Visual Studio 2019.

jQuery AJAX file upload PHP

**1. index.php**
<body>
    <span id="msg" style="color:red"></span><br/>
    <input type="file" id="photo"><br/>
  <script type="text/javascript" src="jquery-3.2.1.min.js"></script>
  <script type="text/javascript">
    $(document).ready(function(){
      $(document).on('change','#photo',function(){
        var property = document.getElementById('photo').files[0];
        var image_name = property.name;
        var image_extension = image_name.split('.').pop().toLowerCase();

        if(jQuery.inArray(image_extension,['gif','jpg','jpeg','']) == -1){
          alert("Invalid image file");
        }

        var form_data = new FormData();
        form_data.append("file",property);
        $.ajax({
          url:'upload.php',
          method:'POST',
          data:form_data,
          contentType:false,
          cache:false,
          processData:false,
          beforeSend:function(){
            $('#msg').html('Loading......');
          },
          success:function(data){
            console.log(data);
            $('#msg').html(data);
          }
        });
      });
    });
  </script>
</body>

**2.upload.php**
<?php
if($_FILES['file']['name'] != ''){
    $test = explode('.', $_FILES['file']['name']);
    $extension = end($test);    
    $name = rand(100,999).'.'.$extension;

    $location = 'uploads/'.$name;
    move_uploaded_file($_FILES['file']['tmp_name'], $location);

    echo '<img src="'.$location.'" height="100" width="100" />';
}

Finding multiple occurrences of a string within a string in Python

Brand new to programming in general and working through an online tutorial. I was asked to do this as well, but only using the methods I had learned so far (basically strings and loops). Not sure if this adds any value here, and I know this isn't how you would do it, but I got it to work with this:

needle = input()
haystack = input()
counter = 0
n=-1
for i in range (n+1,len(haystack)+1):
   for j in range(n+1,len(haystack)+1):
      n=-1
      if needle != haystack[i:j]:
         n = n+1
         continue
      if needle == haystack[i:j]:
         counter = counter + 1
print (counter)

Scanf/Printf double variable C

When a float is passed to printf, it is automatically converted to a double. This is part of the default argument promotions, which apply to functions that have a variable parameter list (containing ...), largely for historical reasons. Therefore, the “natural” specifier for a float, %f, must work with a double argument. So the %f and %lf specifiers for printf are the same; they both take a double value.

When scanf is called, pointers are passed, not direct values. A pointer to float is not converted to a pointer to double (this could not work since the pointed-to object cannot change when you change the pointer type). So, for scanf, the argument for %f must be a pointer to float, and the argument for %lf must be a pointer to double.

Finding the direction of scrolling in a UIScrollView?

The solution

func scrollViewDidScroll(scrollView: UIScrollView) {
     if(scrollView.panGestureRecognizer.translationInView(scrollView.superview).y > 0)
     {
         print("up")
     }
    else
    {
         print("down")
    } 
}

gcc-arm-linux-gnueabi command not found

You have installed a toolchain which was compiled for i686 on a box which is running an x86_64 userland.

Use an i686 VM.

How to mkdir only if a directory does not already exist?

Referring to man page man mkdir for option -p

   -p, --parents
          no error if existing, make parent directories as needed

which will create all directories in a given path, if exists throws no error otherwise it creates all directories from left to right in the given path. Try the below command. the directories newdir and anotherdir doesn't exists before issuing this command

Correct Usage

mkdir -p /tmp/newdir/anotherdir

After executing the command you can see newdir and anotherdir created under /tmp. You can issue this command as many times you want, the command always have exit(0). Due to this reason most people use this command in shell scripts before using those actual paths.

Android Webview - Webpage should fit the device screen

You can use this

    WebView browser = (WebView) findViewById(R.id.webview);
    browser.getSettings().setLoadWithOverviewMode(true);
    browser.getSettings().setUseWideViewPort(true);

this fixes size based on screen size.

Java JSON serialization - best practice

Have your tried json-io (https://github.com/jdereg/json-io)?

This library allows you to serialize / deserialize any Java object graph, including object graphs with cycles in them (e.g., A->B, B->A). It does not require your classes to implement any particular interface or inherit from any particular Java class.

In addition to serialization of Java to JSON (and JSON to Java), you can use it to format (pretty print) JSON:

String niceFormattedJson = JsonWriter.formatJson(jsonString)

How do I get HTTP Request body content in Laravel?

Inside controller inject Request object. So if you want to access request body inside controller method 'foo' do the following:

public function foo(Request $request){
    $bodyContent = $request->getContent();
}

Check whether number is even or odd

This following program can handle large numbers ( number of digits greater than 20 )

package com.isEven.java;
import java.util.Scanner;

public class isEvenValuate{

public static void main(String[] args) {            

        Scanner in = new Scanner(System.in);
        String digit = in.next();

        int y = Character.getNumericValue(digit.charAt(digit.length()-1));

        boolean isEven = (y&1)==0;

        if(isEven)
            System.out.println("Even");
        else
            System.out.println("Odd");

    }
}

Here is the output ::

  122873215981652362153862153872138721637272
  Even

SQL MERGE statement to update data

I often used Bacon Bits great answer as I just can not memorize the syntax.

But I usually add a CTE as an addition to make the DELETE part more useful because very often you will want to apply the merge only to a part of the target table.

WITH target as (
    SELECT * FROM dbo.energydate WHERE DateTime > GETDATE()
)
MERGE INTO target WITH (HOLDLOCK)
USING dbo.temp_energydata AS source
    ON target.webmeterID = source.webmeterID
    AND target.DateTime = source.DateTime
WHEN MATCHED THEN 
    UPDATE SET target.kWh = source.kWh
WHEN NOT MATCHED BY TARGET THEN
    INSERT (webmeterID, DateTime, kWh)
    VALUES (source.webmeterID, source.DateTime, source.kWh)
WHEN NOT MATCHED BY SOURCE THEN
    DELETE

Difference between window.location.href and top.location.href

top refers to the window object which contains all the current frames ( father of the rest of the windows ). window is the current window.

http://www.howtocreate.co.uk/tutorials/javascript/browserinspecific

so top.location.href can contain the "master" page link containing all the frames, while window.location.href just contains the "current" page link.

How to set a bitmap from resource

just replace this line

bm = BitmapFactory.decodeResource(null, R.id.image);

with

Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.YourImageName);

I mean to say just change null value with getResources() If you use this code in any button or Image view click event just append getApplicationContext() before getResources()..

How to detect Safari, Chrome, IE, Firefox and Opera browser?

UAParser is one of the lightweight JavaScript Library to identify browser, engine, OS, CPU, and device type/model from userAgent string.

There's an CDN available. Here, I have included a example code to detect browser using UAParser.

<!doctype html>
<html>
<head>
<script src="https://cdn.jsdelivr.net/npm/ua-parser-js@0/dist/ua-parser.min.js"></script>
<script type="text/javascript">
    var parser = new UAParser();
    var result = parser.getResult();
    console.log(result.browser);     // {name: "Chromium", version: "15.0.874.106"}
</script>
</head>
<body>
</body>
</html>

Now you can use the value of result.browser to conditionally program your page.

Source Tutorial: How to detect browser, engine, OS, CPU, and device using JavaScript?

generate model using user:references vs user_id:integer

how does rails know that user_id is a foreign key referencing user?

Rails itself does not know that user_id is a foreign key referencing user. In the first command rails generate model Micropost user_id:integer it only adds a column user_id however rails does not know the use of the col. You need to manually put the line in the Micropost model

class Micropost < ActiveRecord::Base
  belongs_to :user
end

class User < ActiveRecord::Base
  has_many :microposts
end

the keywords belongs_to and has_many determine the relationship between these models and declare user_id as a foreign key to User model.

The later command rails generate model Micropost user:references adds the line belongs_to :user in the Micropost model and hereby declares as a foreign key.

FYI
Declaring the foreign keys using the former method only lets the Rails know about the relationship the models/tables have. The database is unknown about the relationship. Therefore when you generate the EER Diagrams using software like MySql Workbench you find that there is no relationship threads drawn between the models. Like in the following pic enter image description here

However, if you use the later method you find that you migration file looks like:

def change
    create_table :microposts do |t|
      t.references :user, index: true

      t.timestamps null: false
    end
    add_foreign_key :microposts, :users

Now the foreign key is set at the database level. and you can generate proper EER diagrams. enter image description here

Pip - Fatal error in launcher: Unable to create process using '"'

One more very basic and simple solution. Run the related python version's installation file (setup file) and click repair mode. It hardly takes one-two minutes and everything works perfectly after that :)

Passing an array as parameter in JavaScript

JavaScript is a dynamically typed language. This means that you never need to declare the type of a function argument (or any other variable). So, your code will work as long as arrayP is an array and contains elements with a value property.

Why am I seeing "TypeError: string indices must be integers"?

item is most likely a string in your code; the string indices are the ones in the square brackets, e.g., gravatar_id. So I'd first check your data variable to see what you received there; I guess that data is a list of strings (or at least a list containing at least one string) while it should be a list of dictionaries.

Python, HTTPS GET with basic authentication

A correct way to do basic auth in Python3 urllib.request with certificate validation follows.

Note that certifi is not mandatory. You can use your OS bundle (likely *nix only) or distribute Mozilla's CA Bundle yourself. Or if the hosts you communicate with are just a few, concatenate CA file yourself from the hosts' CAs, which can reduce the risk of MitM attack caused by another corrupt CA.

#!/usr/bin/env python3


import urllib.request
import ssl

import certifi


context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
context.verify_mode = ssl.CERT_REQUIRED
context.load_verify_locations(certifi.where())
httpsHandler = urllib.request.HTTPSHandler(context = context)

manager = urllib.request.HTTPPasswordMgrWithDefaultRealm()
manager.add_password(None, 'https://domain.com/', 'username', 'password')
authHandler = urllib.request.HTTPBasicAuthHandler(manager)

opener = urllib.request.build_opener(httpsHandler, authHandler)

# Used globally for all urllib.request requests.
# If it doesn't fit your design, use opener directly.
urllib.request.install_opener(opener)

response = urllib.request.urlopen('https://domain.com/some/path')
print(response.read())

Listening for variable changes in JavaScript

Please guys remember the initial question was for VARIABLES, not for OBJECTS ;)

in addition to all answers above, I created a tiny lib called forTheWatch.js, that use the same way to catch and callback for changes in normal global variables in javascript.

Compatible with JQUERY variables, no need to use OBJECTS, and you can pass directly an ARRAY of several variables if needed.

If it can be helpful... : https://bitbucket.org/esabora/forthewatch
Basically you just have to call the function :
watchIt("theVariableToWatch", "varChangedFunctionCallback");

And sorry by advance if not relevant.

How can I get argv[] as int?

You can use the function int atoi (const char * str);.
You need to include #include <stdlib.h> and use the function in this way:
int x = atoi(argv[1]);
Here more information if needed: atoi - C++ Reference

How to set input type date's default value to today?

Since Date type only accepts the format "yyyy-MM-dd", you need to format the date value accordingly.

Here is the solution for this,

var d = new Date();
var month = d.getMonth();
var month_actual = month + 1;

if (month_actual < 10) {
  month_actual = "0"+month_actual; 
  }

var day_val = d.getDate();
if (day_val < 10) {
  day_val = "0"+day_val; 
  }

document.getElementById("datepicker_id").value = d.getFullYear()+"-"+ month_actual +"-"+day_val;

HTML5 <video> element on Android

This might not exactly answer your question, but we're using the 3GP or 3GP2 file format. Better even to use the rtsp protocol, but the Android browser will also recognize the 3GP file format.

You can use something like

self.location = URL_OF_YOUR_3GP_FILE

to trigger the video player. The file will be streamed and after playback ends, handling is returned to the browser.

For me this solves a lot of problems with current video tag implementation on android devices.

Instagram: Share photo from webpage

The short answer is: No. The only way to post images is through the mobile app.

From the Instagram API documentation: http://instagram.com/developer/endpoints/media/

At this time, uploading via the API is not possible. We made a conscious choice not to add this for the following reasons:

  • Instagram is about your life on the go – we hope to encourage photos from within the app. However, in the future we may give whitelist access to individual apps on a case by case basis.
  • We want to fight spam & low quality photos. Once we allow uploading from other sources, it's harder to control what comes into the Instagram ecosystem.

All this being said, we're working on ways to ensure users have a consistent and high-quality experience on our platform.

How do I enable MSDTC on SQL Server?

@Dan,

Do I not need msdtc enabled for transactions to work?

Only distributed transactions - Those that involve more than a single connection. Make doubly sure you are only opening a single connection within the transaction and it won't escalate - Performance will be much better too.

How to uncommit my last commit in Git

If you aren't totally sure what you mean by "uncommit" and don't know if you want to use git reset, please see "Revert to a previous Git commit".

If you're trying to understand git reset better, please see "Can you explain what "git reset" does in plain English?".


If you know you want to use git reset, it still depends what you mean by "uncommit". If all you want to do is undo the act of committing, leaving everything else intact, use:

git reset --soft HEAD^

If you want to undo the act of committing and everything you'd staged, but leave the work tree (your files intact):

git reset HEAD^

And if you actually want to completely undo it, throwing away all uncommitted changes, resetting everything to the previous commit (as the original question asked):

git reset --hard HEAD^

The original question also asked it's HEAD^ not HEAD. HEAD refers to the current commit - generally, the tip of the currently checked-out branch. The ^ is a notation which can be attached to any commit specifier, and means "the commit before". So, HEAD^ is the commit before the current one, just as master^ is the commit before the tip of the master branch.

Here's the portion of the git-rev-parse documentation describing all of the ways to specify commits (^ is just a basic one among many).

PostgreSQL: ERROR: operator does not exist: integer = character varying

I think it is telling you exactly what is wrong. You cannot compare an integer with a varchar. PostgreSQL is strict and does not do any magic typecasting for you. I'm guessing SQLServer does typecasting automagically (which is a bad thing).

If you want to compare these two different beasts, you will have to cast one to the other using the casting syntax ::.

Something along these lines:

create view view1
as 
select table1.col1,table2.col1,table3.col3
from table1 
inner join
table2 
inner join 
table3
on 
table1.col4::varchar = table2.col5
/* Here col4 of table1 is of "integer" type and col5 of table2 is of type "varchar" */
/* ERROR: operator does not exist: integer = character varying */
....;

Notice the varchar typecasting on the table1.col4.

Also note that typecasting might possibly render your index on that column unusable and has a performance penalty, which is pretty bad. An even better solution would be to see if you can permanently change one of the two column types to match the other one. Literately change your database design.

Or you could create a index on the casted values by using a custom, immutable function which casts the values on the column. But this too may prove suboptimal (but better than live casting).

The most accurate way to check JS object's type?

Accepted answer is correct, but I like to define this little utility in most projects I build.

var types = {
   'get': function(prop) {
      return Object.prototype.toString.call(prop);
   },
   'null': '[object Null]',
   'object': '[object Object]',
   'array': '[object Array]',
   'string': '[object String]',
   'boolean': '[object Boolean]',
   'number': '[object Number]',
   'date': '[object Date]',
}

Used like this:

if(types.get(prop) == types.number) {

}

If you're using angular you can even have it cleanly injected:

angular.constant('types', types);

How to increment a variable on a for loop in jinja template?

Here's my solution:

Put all the counters in a dictionary:

{% set counter = {
    'counter1': 0,
    'counter2': 0,
    'etc': 0,
    } %}

Define a macro to increment them easily:

{% macro increment(dct, key, inc=1)%}
    {% if dct.update({key: dct[key] + inc}) %} {% endif %}
{% endmacro %}

Now, whenever you want to increment the 'counter1' counter, just do:

{{ increment(counter, 'counter1') }}

php: loop through json array

Decode the JSON string using json_decode() and then loop through it using a regular loop:

$arr = json_decode('[{"var1":"9","var2":"16","var3":"16"},{"var1":"8","var2":"15","var3":"15"}]');

foreach($arr as $item) { //foreach element in $arr
    $uses = $item['var1']; //etc
}

Using LIKE operator with stored procedure parameters

Your datatype for @location nchar(20) should be @location nvarchar(20), since nChar has a fixed length (filled with Spaces).
If Location is nchar too you will have to convert it:

 ... Cast(Location as nVarchar(200)) like '%'+@location+'%' ...   

To enable nullable parameters with and AND condition just use IsNull or Coalesce for comparison, which is not needed in your example using OR.

e.g. if you would like to compare for Location AND Date and Time.

@location nchar(20),
@time time,
@date date
as
select DonationsTruck.VechileId, Phone, Location, [Date], [Time]
from Vechile, DonationsTruck
where Vechile.VechileId = DonationsTruck.VechileId
and (((Location like '%'+IsNull(@location,Location)+'%')) and [Date]=IsNUll(@date,date) and [Time] = IsNull(@time,Time))

Can you do a partial checkout with Subversion?

I wrote a script to automate complex sparse checkouts.

#!/usr/bin/env python

'''
This script makes a sparse checkout of an SVN tree in the current working directory.

Given a list of paths in an SVN repository, it will:
1. Checkout the common root directory
2. Update with depth=empty for intermediate directories
3. Update with depth=infinity for the leaf directories
'''

import os
import getpass
import pysvn

__author__ = "Karl Ostmo"
__date__ = "July 13, 2011"

# =============================================================================

# XXX The os.path.commonprefix() function does not behave as expected!
# See here: http://mail.python.org/pipermail/python-dev/2002-December/030947.html
# and here: http://nedbatchelder.com/blog/201003/whats_the_point_of_ospathcommonprefix.html
# and here (what ever happened?): http://bugs.python.org/issue400788
from itertools import takewhile
def allnamesequal(name):
    return all(n==name[0] for n in name[1:])

def commonprefix(paths, sep='/'):
    bydirectorylevels = zip(*[p.split(sep) for p in paths])
    return sep.join(x[0] for x in takewhile(allnamesequal, bydirectorylevels))

# =============================================================================
def getSvnClient(options):

    password = options.svn_password
    if not password:
        password = getpass.getpass('Enter SVN password for user "%s": ' % options.svn_username)

    client = pysvn.Client()
    client.callback_get_login = lambda realm, username, may_save: (True, options.svn_username, password, True)
    return client

# =============================================================================
def sparse_update_with_feedback(client, new_update_path):
    revision_list = client.update(new_update_path, depth=pysvn.depth.empty)

# =============================================================================
def sparse_checkout(options, client, repo_url, sparse_path, local_checkout_root):

    path_segments = sparse_path.split(os.sep)
    path_segments.reverse()

    # Update the middle path segments
    new_update_path = local_checkout_root
    while len(path_segments) > 1:
        path_segment = path_segments.pop()
        new_update_path = os.path.join(new_update_path, path_segment)
        sparse_update_with_feedback(client, new_update_path)
        if options.verbose:
            print "Added internal node:", path_segment

    # Update the leaf path segment, fully-recursive
    leaf_segment = path_segments.pop()
    new_update_path = os.path.join(new_update_path, leaf_segment)

    if options.verbose:
        print "Will now update with 'recursive':", new_update_path
    update_revision_list = client.update(new_update_path)

    if options.verbose:
        for revision in update_revision_list:
            print "- Finished updating %s to revision: %d" % (new_update_path, revision.number)

# =============================================================================
def group_sparse_checkout(options, client, repo_url, sparse_path_list, local_checkout_root):

    if not sparse_path_list:
        print "Nothing to do!"
        return

    checkout_path = None
    if len(sparse_path_list) > 1:
        checkout_path = commonprefix(sparse_path_list)
    else:
        checkout_path = sparse_path_list[0].split(os.sep)[0]



    root_checkout_url = os.path.join(repo_url, checkout_path).replace("\\", "/")
    revision = client.checkout(root_checkout_url, local_checkout_root, depth=pysvn.depth.empty)

    checkout_path_segments = checkout_path.split(os.sep)
    for sparse_path in sparse_path_list:

        # Remove the leading path segments
        path_segments = sparse_path.split(os.sep)
        start_segment_index = 0
        for i, segment in enumerate(checkout_path_segments):
            if segment == path_segments[i]:
                start_segment_index += 1
            else:
                break

        pruned_path = os.sep.join(path_segments[start_segment_index:])
        sparse_checkout(options, client, repo_url, pruned_path, local_checkout_root)

# =============================================================================
if __name__ == "__main__":

    from optparse import OptionParser
    usage = """%prog  [path2] [more paths...]"""

    default_repo_url = "http://svn.example.com/MyRepository"
    default_checkout_path = "sparse_trunk"

    parser = OptionParser(usage)
    parser.add_option("-r", "--repo_url", type="str", default=default_repo_url, dest="repo_url", help='Repository URL (default: "%s")' % default_repo_url)
    parser.add_option("-l", "--local_path", type="str", default=default_checkout_path, dest="local_path", help='Local checkout path (default: "%s")' % default_checkout_path)

    default_username = getpass.getuser()
    parser.add_option("-u", "--username", type="str", default=default_username, dest="svn_username", help='SVN login username (default: "%s")' % default_username)
    parser.add_option("-p", "--password", type="str", dest="svn_password", help="SVN login password")

    parser.add_option("-v", "--verbose", action="store_true", default=False, dest="verbose", help="Verbose output")
    (options, args) = parser.parse_args()

    client = getSvnClient(options)
    group_sparse_checkout(
        options,
        client,
        options.repo_url,
        map(os.path.relpath, args),
        options.local_path)

Is there a CSS selector for text nodes?

Text nodes cannot have margins or any other style applied to them, so anything you need style applied to must be in an element. If you want some of the text inside of your element to be styled differently, wrap it in a span or div, for example.

Missing artifact com.microsoft.sqlserver:sqljdbc4:jar:4.0

It is not too hard. I have not read the license yet. However I have proven this works. You can copy sqljdbc4 jar file to a network share or local directory. Your build.gradle should look like this :

apply plugin: 'java'
//apply plugin: 'maven'
//apply plugin: 'enhance'

sourceCompatibility = 1.8
version = '1.0'

//library versions
def hibernateVersion='4.3.10.Final'
def microsoftSQLServerJDBCLibVersion='4.0'
def springVersion='2.5.6'

def log4jVersion='1.2.16'
def jbossejbapiVersion='3.0.0.GA'

repositories {
    mavenCentral()
    maven{url "file://Sharedir/releases"}
}

dependencies {
    testCompile group: 'junit', name: 'junit', version: '4.11'
    compile "org.hibernate:hibernate-core:$hibernateVersion"
    compile "com.microsoft.sqlserver:sqljdbc4:$microsoftSQLServerJDBCLibVersion"
}

task showMeCache << {
    configurations.compile.each { println it }
}

under the sharedir/releases directory, I have directory similar to maven structure which is \sharedir\releases\com\microsoft\sqlserver\sqljdbc4\4.0\sqljdbc4-4.0.jar

good luck.

David Yen

What is the maximum possible length of a .NET string?

Since the Length property of System.String is an Int32, I would guess that that the maximum length would be 2,147,483,647 chars (max Int32 size). If it allowed longer you couldn't check the Length since that would fail.

CSS Positioning Elements Next to each other

If you want them to be displayed side by side, why is sideContent the child of mainContent? make them siblings then use:

float:left; display:inline; width: 49%;

on both of them.

#mainContent, #sideContent {float:left; display:inline; width: 49%;}

node.js + mysql connection pooling

i always use connection.relase(); after pool.getconnetion like

pool.getConnection(function (err, connection) {
      connection.release();
        if (!err)
        {
            console.log('*** Mysql Connection established with ', config.database, ' and connected as id ' + connection.threadId);
            //CHECKING USERNAME EXISTENCE
            email = receivedValues.email
            connection.query('SELECT * FROM users WHERE email = ?', [email],
                function (err, rows) {
                    if (!err)
                    {
                        if (rows.length == 1)
                        {
                            if (bcrypt.compareSync(req.body.password, rows[0].password))
                            {
                                var alldata = rows;
                                var userid = rows[0].id;
                                var tokendata = (receivedValues, userid);
                                var token = jwt.sign(receivedValues, config.secret, {
                                    expiresIn: 1440 * 60 * 30 // expires in 1440 minutes
                                });
                                console.log("*** Authorised User");
                                res.json({
                                    "code": 200,
                                    "status": "Success",
                                    "token": token,
                                    "userData": alldata,
                                    "message": "Authorised User!"
                                });
                                logger.info('url=', URL.url, 'Responce=', 'User Signin, username', req.body.email, 'User Id=', rows[0].id);
                                return;
                            }
                            else
                            {
                                console.log("*** Redirecting: Unauthorised User");
                                res.json({"code": 200, "status": "Fail", "message": "Unauthorised User!"});
                                logger.error('*** Redirecting: Unauthorised User');
                                return;
                            }
                        }
                        else
                        {
                            console.error("*** Redirecting: No User found with provided name");
                            res.json({
                                "code": 200,
                                "status": "Error",
                                "message": "No User found with provided name"
                            });
                            logger.error('url=', URL.url, 'No User found with provided name');
                            return;
                        }
                    }
                    else
                    {
                        console.log("*** Redirecting: Error for selecting user");
                        res.json({"code": 200, "status": "Error", "message": "Error for selecting user"});
                        logger.error('url=', URL.url, 'Error for selecting user', req.body.email);
                        return;
                    }
                });
            connection.on('error', function (err) {
                console.log('*** Redirecting: Error Creating User...');
                res.json({"code": 200, "status": "Error", "message": "Error Checking Username Duplicate"});
                return;
            });
        }
        else
        {
            Errors.Connection_Error(res);
        }
    });

SyntaxError: Use of const in strict mode?

Update your node and it will resolve this problem.

Play audio file from the assets directory

enter image description here

start sound

startSound("mp3/ba.mp3");

method

private void startSound(String filename) {
    AssetFileDescriptor afd = null;
    try {
        afd = getResources().getAssets().openFd(filename);
    } catch (IOException e) {
        e.printStackTrace();
    }
    MediaPlayer player = new MediaPlayer();
    try {
        assert afd != null;
        player.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
    } catch (IOException e) {
        e.printStackTrace();
    }
    try {
        player.prepare();
    } catch (IOException e) {
        e.printStackTrace();
    }
    player.start();
}

SyntaxError: "can't assign to function call"

You have done it backwards, it should be:

amount = invest(amount,top_company(5,year,year+1),year)

What are the options for (keyup) in Angular2?

I was searching for a way to bind to multiple key events - specifically, Shift+Enter - but couldn't find any good resources online. But after logging the keydown binding

<textarea (keydown)=onKeydownEvent($event)></textarea>

I discovered that the keyboard event provided all of the information I needed to detect Shift+Enter. Turns out that $event returns a fairly detailed KeyboardEvent.

onKeydownEvent(event: KeyboardEvent): void {
   if (event.keyCode === 13 && event.shiftKey) {
       // On 'Shift+Enter' do this...
   }
}

There also flags for the CtrlKey, AltKey, and MetaKey (i.e. Command key on Mac).

No need for the KeyEventsPlugin, JQuery, or a pure JS binding.

Is there a simple way to increment a datetime object one month in Python?

>>> now
datetime.datetime(2016, 1, 28, 18, 26, 12, 980861)
>>> later = now.replace(month=now.month+1)
>>> later
datetime.datetime(2016, 2, 28, 18, 26, 12, 980861)

EDIT: Fails on

y = datetime.date(2016, 1, 31); y.replace(month=2) results in ValueError: day is out of range for month

Ther is no simple way to do it, but you can use your own function like answered below.

Upgrade to python 3.8 using conda

Open Anaconda Prompt (base):

  1. Update conda:
conda update -n base -c defaults conda
  1. Create new environment with Python 3.8:
conda create -n python38 python=3.8
  1. Activate your new Python 3.8 environment:
conda activate python38
  1. Start Python 3.8:
python

How to dismiss AlertDialog in android

Just set the view as null that will close the AlertDialog simple.

Moving Panel in Visual Studio Code to right side

As of June 2019 this setting can be found through searching 'Panel' - if you want to change the default there is an option for it as shown in the screenshot:enter image description here

How to always show scrollbar

setVertical* helped to make vertical scrollbar always visible programmatically

scrollView.setScrollbarFadingEnabled(false);
scrollView.setVerticalScrollBarEnabled(true);
scrollView.setVerticalFadingEdgeEnabled(false);

How to change font in ipython notebook

In JupyterNotebook cell, Simply you can use:

%%html
<style type='text/css'>
.CodeMirror{
font-size: 17px;
</style>

Override browser form-filling and input highlighting with HTML/CSS

You can also change the name attribute of your form elements to be something generated so that the browser won't keep track of it. HOWEVER firefox 2.x+ and google chrome seems to not have much problems with that if the request url is identical. Try basically adding a salt request param and a salt field name for the sign-up form.

However I think autocomplete="off" is still top solution :)

How do I use PHP namespaces with autoload?

https://thomashunter.name/blog/simple-php-namespace-friendly-autoloader-class/

You’ll want to put your class files into a folder named Classes, which is in the same directory as the entry point into your PHP application. If classes use namespaces, the namespaces will be converted into the directory structure.

Unlike a lot of other auto-loaders, underscores will not be converted into directory structures (it’s tricky to do PHP < 5.3 pseudo namespaces along with PHP >= 5.3 real namespaces).

<?php
class Autoloader {
    static public function loader($className) {
        $filename = "Classes/" . str_replace("\\", '/', $className) . ".php";
        if (file_exists($filename)) {
            include($filename);
            if (class_exists($className)) {
                return TRUE;
            }
        }
        return FALSE;
    }
}
spl_autoload_register('Autoloader::loader');

You’ll want to place the following code into your main PHP script (entry point):

require_once("Classes/Autoloader.php");

Here’s an example directory layout:

index.php
Classes/
  Autoloader.php
  ClassA.php - class ClassA {}
  ClassB.php - class ClassB {}
  Business/
    ClassC.php - namespace Business; classC {}
    Deeper/
      ClassD.php - namespace Business\Deeper; classD {}

List of IP Space used by Facebook

# Bloqueio facebook
for ip in `whois -h whois.radb.net '!gAS32934' | grep /`
do
  iptables -A FORWARD -p all -d $ip -j REJECT
done

Format a datetime into a string with milliseconds

from datetime import datetime
from time import clock

t = datetime.utcnow()
print 't == %s    %s\n\n' % (t,type(t))

n = 100000

te = clock()
for i in xrange(1):
    t_stripped = t.strftime('%Y%m%d%H%M%S%f')
print clock()-te
print t_stripped," t.strftime('%Y%m%d%H%M%S%f')"

print

te = clock()
for i in xrange(1):
    t_stripped = str(t).replace('-','').replace(':','').replace('.','').replace(' ','')
print clock()-te
print t_stripped," str(t).replace('-','').replace(':','').replace('.','').replace(' ','')"

print

te = clock()
for i in xrange(n):
    t_stripped = str(t).translate(None,' -:.')
print clock()-te
print t_stripped," str(t).translate(None,' -:.')"

print

te = clock()
for i in xrange(n):
    s = str(t)
    t_stripped = s[:4] + s[5:7] + s[8:10] + s[11:13] + s[14:16] + s[17:19] + s[20:] 
print clock()-te
print t_stripped," s[:4] + s[5:7] + s[8:10] + s[11:13] + s[14:16] + s[17:19] + s[20:] "

result

t == 2011-09-28 21:31:45.562000    <type 'datetime.datetime'>


3.33410112179
20110928212155046000  t.strftime('%Y%m%d%H%M%S%f')

1.17067364707
20110928212130453000 str(t).replace('-','').replace(':','').replace('.','').replace(' ','')

0.658806915404
20110928212130453000 str(t).translate(None,' -:.')

0.645189262881
20110928212130453000 s[:4] + s[5:7] + s[8:10] + s[11:13] + s[14:16] + s[17:19] + s[20:]

Use of translate() and slicing method run in same time
translate() presents the advantage to be usable in one line

Comparing the times on the basis of the first one:

1.000 * t.strftime('%Y%m%d%H%M%S%f')

0.351 * str(t).replace('-','').replace(':','').replace('.','').replace(' ','')

0.198 * str(t).translate(None,' -:.')

0.194 * s[:4] + s[5:7] + s[8:10] + s[11:13] + s[14:16] + s[17:19] + s[20:]

JCheckbox - ActionListener and ItemListener?

The difference is that ActionEvent is fired when the action is performed on the JCheckBox that is its state is changed either by clicking on it with the mouse or with a space bar or a mnemonic. It does not really listen to change events whether the JCheckBox is selected or deselected.

For instance, if JCheckBox c1 (say) is added to a ButtonGroup. Changing the state of other JCheckBoxes in the ButtonGroup will not fire an ActionEvent on other JCheckBox, instead an ItemEvent is fired.

Final words: An ItemEvent is fired even when the user deselects a check box by selecting another JCheckBox (when in a ButtonGroup), however ActionEvent is not generated like that instead ActionEvent only listens whether an action is performed on the JCheckBox (to which the ActionListener is registered only) or not. It does not know about ButtonGroup and all other selection/deselection stuff.

Return HTTP status code 201 in flask

Ripping off Luc's comment here, but to return a blank response, like a 201 the simplest option is to use the following return in your route.

return "", 201

So for example:

    @app.route('/database', methods=["PUT"])
    def database():
        update_database(request)
        return "", 201

Android SQLite SELECT Query

Try trimming the string to make sure there is no extra white space:

Cursor c = db.rawQuery("SELECT * FROM tbl1 WHERE TRIM(name) = '"+name.trim()+"'", null);

Also use c.moveToFirst() like @thinksteep mentioned.


This is a complete code for select statements.

SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.rawQuery("SELECT column1,column2,column3 FROM table ", null);
if (c.moveToFirst()){
    do {
        // Passing values 
        String column1 = c.getString(0);
        String column2 = c.getString(1);
        String column3 = c.getString(2); 
        // Do something Here with values
    } while(c.moveToNext());
}
c.close();
db.close();

Call break in nested if statements

Just remove the break. since it is already inside first if it will not execute else. It will exit anyway.

How do I revert back to an OpenWrt router configuration?

Those who are facing this problem: Don't panic.

Short answer:

Restart your router, and this problem will be fixed. (But if your restart button is not working, you need to do a nine-step process to do the restart. Hitting the restart button is just one of them.)

Long answer: Let's learn how to restart the router.

  1. Set your PC's IP address: 192.168.1.2 and subnetmask 255.255.255.0 and gateway 192.168.1.1
  2. Power off the router
  3. Disconnect the WAN cable
  4. Only connect your PC Ethernet cable to ETH0
  5. Power on the router
  6. Wait for the router to start the boot sequence (SYS LED starts blinking)
  7. When the SYS LED is blinking, hit the restart button (the SYS LED will be blinking at a faster rate means your router is in failsafe mode). (You have to hit the button before the router boots.)
  8. telnet 192.168.1.1
  9. Run these commands:

    mount_root ## this remounts your partitions from read-only to read/write mode
    
    firstboot  ## This will reset your router after reboot
    
    reboot -f ## And force reboot
    
  10. Log in the web interface using web browser.

link to see the official failsafe mode.

WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for 'jquery'. Please add a ScriptResourceMapping named jquery(case-sensitive)

The problem occurred due to the Control validator. Just Add the J Query reference to your web page as follows and then add the Validation Settings in your web.config file to overcome the problem. I too faced the same problem and the below gave the solution to my problem.

Step1:

Code to be added in web page

Step2 :

Code to be added in Web.config file

It will resolve your problem.

android on Text Change Listener

I wrote my own extension for this, very helpful for me. (Kotlin)

You can write only like that :

editText.customAfterTextChanged { editable -> 
    //You have accessed the editable object. 
}

My extension :

fun EditText.customAfterTextChanged(action: (Editable?)-> Unit){
    this.addTextChangedListener(object : TextWatcher {
       override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {}
       override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {}
       override fun afterTextChanged(editable: Editable?) {
        action(editable)
    }
})}

Soft hyphen in HTML (<wbr> vs. &shy;)

I suggest using wbr, so the code can be written like this:

<p>???????,???<wbr
></wbr>??;?????</p>

It won't lead space between charaters, while &shy; won't stop spaces created by line breaks.

Print line numbers starting at zero using awk

NR starts at 1, so use

awk '{print NR-1 "," $0}'

ORA-29283: invalid file operation ORA-06512: at "SYS.UTL_FILE", line 536

Assume file is already created in the predefined directory with name "table.txt"

  • 1) change the ownership for file :

    sudo chown username:username table.txt
    
  • 2) change the mode of the file

    sudo chmod 777 table.txt
    

Now, try it should work!

ImportError: no module named win32api

After installing pywin32

Steps to correctly install your module (pywin32)

  1. First search where is your python pip is present

    1a. For Example in my case location of pip - C:\Users\username\AppData\Local\Programs\Python\Python36-32\Scripts

  2. Then open your command prompt and change directory to your pip folder location.

    cd C:\Users\username\AppData\Local\Programs\Python\Python36-32\Scripts
    
    C:\Users\username\AppData\Local\Programs\Python\Python36-32\Scripts>pip install 
    pypiwin32
    

Restart your IDE

All done now you can use the module .

Get timezone from DateTime

You could use TimeZoneInfo class

The TimeZone class recognizes local time zone, and can convert times between Coordinated Universal Time (UTC) and local time. A TimeZoneInfo object can represent any time zone, and methods of the TimeZoneInfo class can be used to convert the time in one time zone to the corresponding time in any other time zone. The members of the TimeZoneInfo class support the following operations:

  1. Retrieving a time zone that is already defined by the operating system.

  2. Enumerating the time zones that are available on a system.

  3. Converting times between different time zones.

  4. Creating a new time zone that is not already defined by the operating system.

    Serializing a time zone for later retrieval.

Can two or more people edit an Excel document at the same time?

yes if it is SharePoint 2010 and above by using the Office feature co-authoring

Turn ON/OFF Camera LED/flash light in Samsung Galaxy Ace 2.2.1 & Galaxy Tab

I will soon released a new version of my app to support to galaxy ace.

You can download here: https://play.google.com/store/apps/details?id=droid.pr.coolflashlightfree

In order to solve your problem you should do this:

this._camera = Camera.open();     
this._camera.startPreview();
this._camera.autoFocus(new AutoFocusCallback() {
public void onAutoFocus(boolean success, Camera camera) {
}
});

Parameters params = this._camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_ON);
this._camera.setParameters(params);

params = this._camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_OFF);
this._camera.setParameters(params);

don't worry about FLASH_MODE_OFF because this will keep the light on, strange but it's true

to turn off the led just release the camera

Receiving "Attempted import error:" in react app

I guess I am coming late, but this info might be useful to anyone I found out something, which might be simple but important. if you use export on a function directly i.e

export const addPost = (id) =>{
  ...
 }

Note while importing you need to wrap it in curly braces i.e. import {addPost} from '../URL';

But when using export default i.e

const addPost = (id) =>{
  ...
 }

export default addPost,

Then you can import without curly braces i.e. import addPost from '../url';

export default addPost

I hope this helps anyone who got confused as me.

What is the `data-target` attribute in Bootstrap 3?

The toggle tells Bootstrap what to do and the target tells Bootstrap which element is going to open. So whenever a link like that is clicked, a modal with an id of “basicModal” will appear.

How do I rename both a Git local and remote branch name?

If you have already pushed the wrong name to remote, do the following:

  1. Switch to the local branch you want to rename

    git checkout <old_name>

  2. Rename the local branch

    git branch -m <new_name>

  3. Push the <new_name> local branch and reset the upstream branch

    git push origin -u <new_name>

  4. Delete the <old_name> remote branch

    git push origin --delete <old_name>

This was based on this article.

Connect to sqlplus in a shell script and run SQL scripts

For example:

sqlplus -s admin/password << EOF
whenever sqlerror exit sql.sqlcode;
set echo off 
set heading off

@pl_script_1.sql
@pl_script_2.sql

exit;
EOF

CSS3 background image transition

Considering background-images can't be animated, I created a little SCSS mixin allowing to transition between 2 different background-images using pseudo selectors before and after. They are at different z-index layers. The one that is ahead starts with opacity 0 and becomes visible with hover.

You can use it the same approach for creating animations with linear-gradients too.

scss

@mixin bkg-img-transition( $bkg1, $bkg2, $transTime:0.5s ){  
  position: relative;  
  z-index: 100; 
  &:before, &:after {
    background-size: cover;  
    content: '';    
    display: block;
    height: 100%;
    position: absolute;
    top: 0; left: 0;    
    width: 100%;    
    transition: opacity $transTime;
  }
  &:before {    
    z-index: -101;
    background-image: url("#{$bkg1}");    
  }
  &:after {    
    z-index: -100;
    opacity: 0;
    background-image: url("#{$bkg2}");    
  }
  &:hover {
     &:after{
       opacity: 1; 
     }
  }  
}

Now you can simply use it with

@include bkg-img-transition("https://picsum.photos/300/300/?random","https://picsum.photos/g/300/300");

You can check it out here: https://jsfiddle.net/pablosgpacheco/01rmg0qL/

OracleCommand SQL Parameters Binding

You need to use something like this:

 OracleCommand oraCommand = new OracleCommand("SELECT fullname FROM sup_sys.user_profile
                       WHERE domain_user_name = :userName", db);

More can be found in this MSDN article: http://msdn.microsoft.com/en-us/library/system.data.oracleclient.oraclecommand.parameters%28v=vs.100%29.aspx

It is advised you use the : character instead of @ for Oracle.

Getting 400 bad request error in Jquery Ajax POST

Yes. You need to stringify the JSON data orlse 400 bad request error occurs as it cannot identify the data.

400 Bad Request

Bad Request. Your browser sent a request that this server could not understand.

Plus you need to add content type and datatype as well. If not you will encounter 415 error which says Unsupported Media Type.

415 Unsupported Media Type

Try this.

var newData =   {
                  "subject:title":"Test Name",
                  "subject:description":"Creating test subject to check POST method API",
                  "sub:tags": ["facebook:work", "facebook:likes"],
                  "sampleSize" : 10,
                  "values": ["science", "machine-learning"]
                  };

var dataJson = JSON.stringify(newData);

$.ajax({
  type: 'POST',
  url: "http://localhost:8080/project/server/rest/subjects",
  data: dataJson,
  error: function(e) {
    console.log(e);
  },
  dataType: "json",
  contentType: "application/json"
});

With this way you can modify the data you need with ease. It wont confuse you as it is defined outside the ajax block.

Transpose a matrix in Python

You can use zip with * to get transpose of a matrix:

>>> A = [[ 1, 2, 3],[ 4, 5, 6]]
>>> zip(*A)
[(1, 4), (2, 5), (3, 6)]
>>> lis  = [[1,2,3], 
... [4,5,6],
... [7,8,9]]
>>> zip(*lis)
[(1, 4, 7), (2, 5, 8), (3, 6, 9)]

If you want the returned list to be a list of lists:

>>> [list(x) for x in zip(*lis)]
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]
#or
>>> map(list, zip(*lis))
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]

Django - taking values from POST request

For django forms you can do this;

form = UserLoginForm(data=request.POST) #getting the whole data from the user.
user = form.save() #saving the details obtained from the user.
username = user.cleaned_data.get("username") #where "username" in parenthesis is the name of the Charfield (the variale name i.e, username = forms.Charfield(max_length=64))

Should we pass a shared_ptr by reference or by value?

This question has been discussed and answered by Scott, Andrei and Herb during Ask Us Anything session at C++ and Beyond 2011. Watch from 4:34 on shared_ptr performance and correctness.

Shortly, there is no reason to pass by value, unless the goal is to share ownership of an object (eg. between different data structures, or between different threads).

Unless you can move-optimise it as explained by Scott Meyers in the talk video linked above, but that is related to actual version of C++ you can use.

A major update to this discussion has happened during GoingNative 2012 conference's Interactive Panel: Ask Us Anything! which is worth watching, especially from 22:50.

Python: converting a list of dictionaries to json

To convert it to a single dictionary with some decided keys value, you can use the code below.

data = ListOfDict.copy()
PrecedingText = "Obs_"
ListOfDictAsDict = {}
for i in range(len(data)):
    ListOfDictAsDict[PrecedingText + str(i)] = data[i]

Using putty to scp from windows to Linux

Use scp priv_key.pem source user@host:target if you need to connect using a private key.

or if using pscp then use pscp -i priv_key.ppk source user@host:target

Number of days in particular month of particular year?

// 1 means Sunday ,2 means Monday .... 7 means Saturday
//month starts with 0 (January)

MonthDisplayHelper monthDisplayHelper = new MonthDisplayHelper(2019,4);
int numbeOfDaysInMonth = monthDisplayHelper.getNumberOfDaysInMonth();

Phonegap + jQuery Mobile, real world sample or tutorial

This is a nice 5-part tutorial that covers a lot of useful material: http://mobile.tutsplus.com/tutorials/phonegap/phonegap-from-scratch/
(Anyone else noticing a trend forming here??? hehehee )

And this will definitely be of use to all developers:
http://blip.tv/mobiletuts/weinre-demonstration-5922038
=)
Todd

Edit I just finished a nice four part tutorial building an app to write, save, edit, & delete notes using jQuery mobile (only), it was very practical & useful, but it was also only for jQM. So, I looked to see what else they had on DZone.

I'm now going to start sorting through these search results. At a glance, it looks really promising. I remembered this post; so I thought I'd steer people to it. ?

What is the difference between a mutable and immutable string in C#?

An object is mutable if, once created, its state can be changed by calling various operations on it, otherwise it is immutable.

Immutable String

In C# (and .NET) a string is represented by class System.String. The string keyword is an alias for this class.

The System.String class is immutable, i.e once created its state cannot be altered.

So all the operations you perform on a string like Substring, Remove, Replace, concatenation using '+' operator etc will create a new string and return it.

See the following program for demonstration -

string str = "mystring";
string newString = str.Substring(2);
Console.WriteLine(newString);
Console.WriteLine(str);

This will print 'string' and 'mystring' respectively.

For the benefits of immutability and why string are immutable check Why .NET String is immutable?.

Mutable String

If you want to have a string which you want to modify often you can use the StringBuilder class. Operations on a StringBuilder instance will modify the same object.

For more advice on when to use StringBuilder refer to When to use StringBuilder?.

Could not resolve com.android.support:appcompat-v7:26.1.0 in Android Studio new project

Just go to File\Settings\Gradle. Deselect the "Offline work" box. Now you can connect and download any necessary or missing dependencies

Clearing all cookies with JavaScript

And here's one to clear all cookies in all paths and all variants of the domain (www.mydomain.com, mydomain.com etc):

(function () {
    var cookies = document.cookie.split("; ");
    for (var c = 0; c < cookies.length; c++) {
        var d = window.location.hostname.split(".");
        while (d.length > 0) {
            var cookieBase = encodeURIComponent(cookies[c].split(";")[0].split("=")[0]) + '=; expires=Thu, 01-Jan-1970 00:00:01 GMT; domain=' + d.join('.') + ' ;path=';
            var p = location.pathname.split('/');
            document.cookie = cookieBase + '/';
            while (p.length > 0) {
                document.cookie = cookieBase + p.join('/');
                p.pop();
            };
            d.shift();
        }
    }
})();

What is the Difference Between Mercurial and Git?

I'm currently in the process of migrating from SVN to a DVCS (while blogging about my findings, my first real blogging effort...), and I've done a bit of research (=googling). As far as I can see you can do most of the things with both packages. It seems like git has a few more or better implemented advanced features, I do feel that the integration with windows is a bit better for mercurial, with TortoiseHg. I know there's Git Cheetah as well (I tried both), but the mercurial solution just feels more robust.

Seeing how they're both open-source (right?) I don't think either will be lacking important features. If something is important, people will ask for it, people will code it.

I think that for common practices, Git and Mercurial are more than sufficient. They both have big projects that use them (Git -> linux kernel, Mercurial -> Mozilla foundation projects, both among others of course), so I don't think either are really lacking something.

That being said, I am interested in what other people say about this, as it would make a great source for my blogging efforts ;-)

Windows cannot find 'http:/.127.0.0.1:%HTTPPORT%/apex/f?p=4950'. Make sure you typed the name correctly, and then try again

Reading through all these answers, they failed to show the "correct" way of doing it according to Oracle.

Oracle is the only software company I know that heavily relies on custom environment variables. To add %HTTPPORT% to your environment variables, you first need to search for "System Environment Variables" in Windows. There, you should find a button "Change Environment Variables". In the new window, select "New" and type in HTTPPORT as name and 8080 as value. Now, log off and on again, and it magically works!

django admin - add custom form fields that are not part of the model

you can always create new admin template , and do what you need in your admin_view (override the admin add url to your admin_view):

 url(r'^admin/mymodel/mymodel/add/$' , 'admin_views.add_my_special_model')

Determining the current foreground application from a background task or service

For cases when we need to check from our own service/background-thread whether our app is in foreground or not. This is how I implemented it, and it works fine for me:

public class TestApplication extends Application implements Application.ActivityLifecycleCallbacks {

    public static WeakReference<Activity> foregroundActivityRef = null;

    @Override
    public void onActivityStarted(Activity activity) {
        foregroundActivityRef = new WeakReference<>(activity);
    }

    @Override
    public void onActivityStopped(Activity activity) {
        if (foregroundActivityRef != null && foregroundActivityRef.get() == activity) {
            foregroundActivityRef = null;
        }
    }

    // IMPLEMENT OTHER CALLBACK METHODS
}

Now to check from other classes, whether app is in foreground or not, simply call:

if(TestApplication.foregroundActivityRef!=null){
    // APP IS IN FOREGROUND!
    // We can also get the activity that is currently visible!
}

Update (as pointed out by SHS):

Do not forget to register for the callbacks in your Application class's onCreate method.

@Override
public void onCreate() {
    ...
    registerActivityLifecycleCallbacks(this);
}

In Perl, what is the difference between a .pm (Perl module) and .pl (Perl script) file?

At the very core, the file extension you use makes no difference as to how perl interprets those files.

However, putting modules in .pm files following a certain directory structure that follows the package name provides a convenience. So, if you have a module Example::Plot::FourD and you put it in a directory Example/Plot/FourD.pm in a path in your @INC, then use and require will do the right thing when given the package name as in use Example::Plot::FourD.

The file must return true as the last statement to indicate successful execution of any initialization code, so it's customary to end such a file with 1; unless you're sure it'll return true otherwise. But it's better just to put the 1;, in case you add more statements.

If EXPR is a bareword, the require assumes a ".pm" extension and replaces "::" with "/" in the filename for you, to make it easy to load standard modules. This form of loading of modules does not risk altering your namespace.

All use does is to figure out the filename from the package name provided, require it in a BEGIN block and invoke import on the package. There is nothing preventing you from not using use but taking those steps manually.

For example, below I put the Example::Plot::FourD package in a file called t.pl, loaded it in a script in file s.pl.

C:\Temp> cat t.pl
package Example::Plot::FourD;

use strict; use warnings;

sub new { bless {} => shift }

sub something { print "something\n" }

"Example::Plot::FourD"

C:\Temp> cat s.pl
#!/usr/bin/perl
use strict; use warnings;

BEGIN {
    require 't.pl';
}

my $p = Example::Plot::FourD->new;
$p->something;


C:\Temp> s
something

This example shows that module files do not have to end in 1, any true value will do.

How do you get the list of targets in a makefile?

Under Bash (at least), this can be done automatically with tab completion:

make spacetabtab

What is the most effective way to get the index of an iterator of an std::vector?

Beside int float string etc., you can put extra data to .second when using diff. types like:

std::map<unsigned long long int, glm::ivec2> voxels_corners;
std::map<unsigned long long int, glm::ivec2>::iterator it_corners;

or

struct voxel_map {
    int x,i;
};

std::map<unsigned long long int, voxel_map> voxels_corners;
std::map<unsigned long long int, voxel_map>::iterator it_corners;

when

long long unsigned int index_first=some_key; // llu in this case...
int i=0;
voxels_corners.insert(std::make_pair(index_first,glm::ivec2(1,i++)));

or

long long unsigned int index_first=some_key;
int index_counter=0;
voxel_map one;
one.x=1;
one.i=index_counter++;

voxels_corners.insert(std::make_pair(index_first,one));

with right type || structure you can put anything in the .second including a index number that is incremented when doing an insert.

instead of

it_corners - _corners.begin()

or

std::distance(it_corners.begin(), it_corners)

after

it_corners = voxels_corners.find(index_first+bdif_x+x_z);

the index is simply:

int vertice_index = it_corners->second.y;

when using the glm::ivec2 type

or

int vertice_index = it_corners->second.i;

in case of the structure data type

How do I apply CSS3 transition to all properties except background-position?

Try:

-webkit-transition: all .2s linear, background-position 0;

This worked for me on something similar..

MySQL, Concatenate two columns

In php, we have two option to concatenate table columns.

First Option using Query

In query, CONCAT keyword used to concatenate two columns

SELECT CONCAT(`SUBJECT`,'_', `YEAR`) AS subject_year FROM `table_name`;

Second Option using symbol ( . )

After fetch the data from database table, assign the values to variable, then using ( . ) Symbol and concatenate the values

$subject = $row['SUBJECT'];
$year = $row['YEAR'];
$subject_year = $subject . "_" . $year;

Instead of underscore( _ ) , we will use the spaces, comma, letters,numbers..etc

How to find if directory exists in Python

You're looking for os.path.isdir, or os.path.exists if you don't care whether it's a file or a directory:

>>> import os
>>> os.path.isdir('new_folder')
True
>>> os.path.exists(os.path.join(os.getcwd(), 'new_folder', 'file.txt'))
False

Alternatively, you can use pathlib:

 >>> from pathlib import Path
 >>> Path('new_folder').is_dir()
 True
 >>> (Path.cwd() / 'new_folder' / 'file.txt').exists()
 False

Configuring diff tool with .gitconfig

Here's the part of my ~/.gitconfig where I configure diff and merge tools. I like diffmerge by SourceGear. (I like it very very much, as a matter of fact).

[merge]
        tool = diffmerge
[mergetool "diffmerge"]
        cmd = "diffmerge --merge --result=\"$MERGED\" \"$LOCAL\" \"$(if test -f \"$BASE\"; then echo \"$BASE\"; else echo \"$LOCAL\"; fi)\" \"$REMOTE\""
        trustExitCode = false
[diff]
        tool = diffmerge
[difftool "diffmerge"]
        cmd = diffmerge \"$LOCAL\" \"$REMOTE\"

So, you see, you're defining a tool named "diffmerge" in the [difftool "diffmerge"] line. Then I'm setting the tool "diffmerge" as the default in the [diff] tool = section.

I obviously have the "diffmerge" command in my path, here. Otherwise I'd need to give a full path to the executable.

Image scaling causes poor quality in firefox/internet explorer but not chrome

Remember that sizes on the web are increasing dramatically. 3 years ago, I did an overhaul to bring our 500 px wide site layout to 1000. Now, where many sites are doing the jump to 1200, we jumped past that and went to a 2560 max optimized for 1600 wide (or 80% depending on the content level) main content area with responsiveness to allow the exact same ratios and look and feel on a laptop (1366x768) and on mobile (1280x720 or smaller).

Dynamic resizing is an integral part of this and will only become more-so as responsiveness becomes more and more important in 2013.

My smartphone has no trouble dealing with the content with 25 items on a page being resized - neither the computation for resizing nor the bandwidth. 3 seconds loads the page from fresh. Looks great on our 6 year old presentation laptop (1366x768) and on the projector (800x600).

Only on Mozilla Firefox does it look genuinely atrocious. It even looks just fine on IE8 (never used/updated since I installed it 2.5 years ago).

How to save a data frame as CSV to a user selected location using tcltk

You need not to use even the package "tcltk". You can simply do as shown below:

write.csv(x, file = "c:\\myname\\yourfile.csv", row.names = FALSE)

Give your path inspite of "c:\myname\yourfile.csv".

How to get substring of NSString?

Here is a little combination of @Regexident Option 1 and @Garett answers, to get a powerful string cutter between a prefix and suffix, with MORE...ANDMORE words on it.

NSString *haystack = @"MOREvalue:hello World:valueANDMORE";
NSString *prefix = @"value:";
NSString *suffix = @":value";
NSRange prefixRange = [haystack rangeOfString:prefix];
NSRange suffixRange = [[haystack substringFromIndex:prefixRange.location+prefixRange.length] rangeOfString:suffix];
NSRange needleRange = NSMakeRange(prefixRange.location+prefix.length, suffixRange.location);
NSString *needle = [haystack substringWithRange:needleRange];
NSLog(@"needle: %@", needle);

Default string initialization: NULL or Empty?

I always initialise them as NULL.

I always use string.IsNullOrEmpty(someString) to check it's value.

Simple.

how to add or embed CKEditor in php page

After reading the Quick Start Guide

In your HTML page add an element that CKEditor should replace:

<textarea name="content" id="editor"></textarea>

Load the classic editor build (here CDN location is used):

<script src="https://cdn.ckeditor.com/ckeditor5/10.0.1/classic/ckeditor.js"></script>

Call the ClassicEditor.create() method.

<script>
    ClassicEditor
        .create( document.querySelector( '#editor' ) )
        .catch( error => {
            console.error( error );
        } );
</script>

Example

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>CKEditor 5 - Classic editor</title>
    <script src="https://cdn.ckeditor.com/ckeditor5/10.0.1/classic/ckeditor.js"></script>
</head>
<body>
    <h1>Classic editor</h1>
    <textarea name="content" id="editor">
        <p>This is some sample content.</p>
    </textarea>
    <script>
        ClassicEditor
            .create( document.querySelector( '#editor' ) )
            .catch( error => {
                console.error( error );
            } );
    </script>
</body>
</html>

This example is for the specific classic editor. FOr other variants, only CDN will change.

Returning value that was passed into a method

The generic Returns<T> method can handle this situation nicely.

_mock.Setup(x => x.DoSomething(It.IsAny<string>())).Returns<string>(x => x);

Or if the method requires multiple inputs, specify them like so:

_mock.Setup(x => x.DoSomething(It.IsAny<string>(), It.IsAny<int>())).Returns((string x, int y) => x);

Best approach to remove time part of datetime in SQL Server

How about select cast(cast my_datetime_field as date) as datetime)? This results in the same date, with the time set to 00:00, but avoids any conversion to text and also avoids any explicit numeric rounding.

MySQL Data - Best way to implement paging?

Define OFFSET for the query. For example

page 1 - (records 01-10): offset = 0, limit=10;

page 2 - (records 11-20) offset = 10, limit =10;

and use the following query :

SELECT column FROM table LIMIT {someLimit} OFFSET {someOffset};

example for page 2:

SELECT column FROM table
LIMIT 10 OFFSET 10;

Send email from localhost running XAMMP in PHP using GMAIL mail server

Simplest way is to use PHPMailer and Gmail SMTP. The configuration would be like the below.

require 'PHPMailer/PHPMailerAutoload.php';
$mail = new PHPMailer;

$mail->isSMTP();                            
$mail->Host = 'smtp.gmail.com';            
$mail->SMTPAuth = true;                     
$mail->Username = 'Email Address';          
$mail->Password = 'Email Account Password'; 
$mail->SMTPSecure = 'tls';               
$mail->Port = 587;                  

Example script and full source code can be found from here - How to Send Email from Localhost in PHP

Aggregate multiple columns at once

We can use the formula method of aggregate. The variables on the 'rhs' of ~ are the grouping variables while the . represents all other variables in the 'df1' (from the example, we assume that we need the mean for all the columns except the grouping), specify the dataset and the function (mean).

aggregate(.~id1+id2, df1, mean)

Or we can use summarise_each from dplyr after grouping (group_by)

library(dplyr)
df1 %>%
    group_by(id1, id2) %>% 
    summarise_each(funs(mean))

Or using summarise with across (dplyr devel version - ‘0.8.99.9000’)

df1 %>% 
    group_by(id1, id2) %>%
    summarise(across(starts_with('val'), mean))

Or another option is data.table. We convert the 'data.frame' to 'data.table' (setDT(df1), grouped by 'id1' and 'id2', we loop through the subset of data.table (.SD) and get the mean.

library(data.table)
setDT(df1)[, lapply(.SD, mean), by = .(id1, id2)] 

data

df1 <- structure(list(id1 = c("a", "a", "a", "a", "b", "b", 
"b", "b"
), id2 = c("x", "x", "y", "y", "x", "y", "x", "y"), 
val1 = c(1L, 
2L, 3L, 4L, 1L, 4L, 3L, 2L), val2 = c(9L, 4L, 5L, 9L, 7L, 4L, 
9L, 8L)), .Names = c("id1", "id2", "val1", "val2"), 
class = "data.frame", row.names = c("1", 
"2", "3", "4", "5", "6", "7", "8"))

PHP Undefined Index

if you use isset like the answer posted already by singles, just make sure there is a bracket at the end like so:
$query_age = (isset($_GET['query_age']) ? $_GET['query_age'] : null);

How can I get the Google cache age of any URL or web page?

You'll need to scrape the resulting page, but you can view the most recent cache page using this URL:

http://webcache.googleusercontent.com/search?q=cache:www.something.com/path

Google information is put in the first div in the body tag.

check if array is empty (vba excel)

Above methods didn´t work for me. This did:

  Dim arrayIsNothing As Boolean

    On Error Resume Next
    arrayIsNothing = IsNumeric(UBound(YOUR_ARRAY)) And False
    If Err.Number <> 0 Then arrayIsNothing = True
    Err.Clear
    On Error GoTo 0

    'Now you can test:
    if arrayIsNothing then ...

How to get start and end of day in Javascript?

Using the luxon.js library, same can be achieved using startOf and endOf methods by passing the 'day' as parameter

var DateTime = luxon.DateTime;
DateTime.local().startOf('day').toUTC().toISO(); //2017-11-16T18:30:00.000Z
DateTime.local().endOf('day').toUTC().toISO(); //2017-11-17T18:29:59.999Z
DateTime.fromISO(new Date().toISOString()).startOf('day').toUTC().toISO(); //2017-11-16T18:30:00.000Z

remove .toUTC() if you need only the local time

and you may ask why not moment.js, answer is here for that.

Specific Time Range Query in SQL Server

I'm assuming you want all three of those as part of the selection criteria. You'll need a few statements in your where but they will be similar to the link your question contained.

SELECT *
  FROM MyTable
  WHERE [dateColumn] > '3/1/2009' AND [dateColumn] <= DATEADD(day,1,'3/31/2009') 
        --make it inclusive for a datetime type
    AND DATEPART(hh,[dateColumn]) >= 6 AND DATEPART(hh,[dateColumn]) <= 22 
        -- gets the hour of the day from the datetime
    AND DATEPART(dw,[dateColumn]) >= 3 AND DATEPART(dw,[dateColumn]) <= 5 
        -- gets the day of the week from the datetime

Hope this helps.

How do you read from stdin?

The answer proposed by others:

for line in sys.stdin:
  print line

is very simple and pythonic, but it must be noted that the script will wait until EOF before starting to iterate on the lines of input.

This means that tail -f error_log | myscript.py will not process lines as expected.

The correct script for such a use case would be:

while 1:
    try:
        line = sys.stdin.readline()
    except KeyboardInterrupt:
        break

    if not line:
        break

    print line

UPDATE
From the comments it has been cleared that on python 2 only there might be buffering involved, so that you end up waiting for the buffer to fill or EOF before the print call is issued.

Redirecting to previous page after login? PHP

You should first get user refer page in a variable using $_SERVER['HTTP_REFERER']; in your login page.

LIKE:

<?php 
    session_start();
    $refPage = $_SERVER['HTTP_REFERER']; 
?>

And now when the user clicks to Login then change header location to user refer page

LIKE:

<?php 
if(isset($_POST[login])){
    session_start();
    header('location:' . $refPage);
}
?>

And in this time you should first check that user refers page empty or not because your user can visit direct your login page then your $refPage variable will be empty so after Click to Login page stays here

LIKE:

<?php
if(isset($_POST[login])){
    session_start();
    $refPage = $_SERVER['HTTP_REFERER'];  // get reffer page url
    if(empty($refPage)){ 
        header('location: yourredirectpage'); // if ref page is empty then set default redirect page.
    }else{
        header('location:' . $refPage); // or if ref page in not empty then redirect page to reffer page
    }
}
?>


Or you can use input type hidden where you can set value $_SERVER['HTTP_REFERER'];

LIKE:

<input type="hidden" name="refPage" value="<?php echo $_SERVER['HTTP_REFERER']; ?>">

And when a user clicks to Login then you can get the refPage value and redirect the previous page. And you should also check empty refer page. Because your user can visit direct your login page.


Thank you.

How to insert current datetime in postgresql insert query

You can of course format the result of current_timestamp(). Please have a look at the various formatting functions in the official documentation.

AngularJs ReferenceError: $http is not defined

Just to complete Amit Garg answer, there are several ways to inject dependencies in AngularJS.


You can also use $inject to add a dependency:

var MyController = function($scope, $http) {
  // ...
}
MyController.$inject = ['$scope', '$http'];

How to get pip to work behind a proxy server

On Ubuntu, you can set proxy by using

export http_proxy=http://username:password@proxy:port
export https_proxy=http://username:password@proxy:port

or if you are having SOCKS error use

export all_proxy=http://username:password@proxy:port

Then run pip

sudo -E pip3 install {packageName}

How to redirect single url in nginx?

If you need to duplicate more than a few redirects, you might consider using a map:

# map is outside of server block
map $uri $redirect_uri {
    ~^/issue1/?$    http://example.com/shop/issues/custom_isse_name1;
    ~^/issue2/?$    http://example.com/shop/issues/custom_isse_name2;
    ~^/issue3/?$    http://example.com/shop/issues/custom_isse_name3;
    # ... or put these in an included file
}

location / {
    try_files $uri $uri/ @redirect-map;
}

location @redirect-map {
    if ($redirect_uri) {  # redirect if the variable is defined
        return 301 $redirect_uri;
    }
}

Signing a Windows EXE file

Use following link to sign .exe (setup/ installer)file (sign exe/setup file without using Microsoft setup signtool)

https://ebourg.github.io/jsign/#files

sample command java -jar jsign-2.0.jar --keystore keystore.jks" --alias alias --storepass password MyInstaller.exe

Worked for me :)

Iterate through <select> options

can also Use parameterized each with index and the element.

$('#selectIntegrationConf').find('option').each(function(index,element){
 console.log(index);
 console.log(element.value);
 console.log(element.text);
 });

// this will also work

$('#selectIntegrationConf option').each(function(index,element){
 console.log(index);
 console.log(element.value);
 console.log(element.text);
 });

Convert Dictionary to JSON in Swift

You are making a wrong assumption. Just because the debugger/Playground shows your dictionary in square brackets (which is how Cocoa displays dictionaries) that does not mean that is the way the JSON output is formatted.

Here is example code that will convert a dictionary of strings to JSON:

Swift 3 version:

import Foundation

let dictionary = ["aKey": "aValue", "anotherKey": "anotherValue"]
if let theJSONData = try? JSONSerialization.data(
    withJSONObject: dictionary,
    options: []) {
    let theJSONText = String(data: theJSONData,
                               encoding: .ascii)
    print("JSON string = \(theJSONText!)")
}

To display the above in "pretty printed" format you'd change the options line to:

    options: [.prettyPrinted]

Or in Swift 2 syntax:

import Foundation
 
let dictionary = ["aKey": "aValue", "anotherKey": "anotherValue"]
let theJSONData = NSJSONSerialization.dataWithJSONObject(
  dictionary ,
  options: NSJSONWritingOptions(0),
  error: nil)
let theJSONText = NSString(data: theJSONData!,
  encoding: NSASCIIStringEncoding)
println("JSON string = \(theJSONText!)")

The output of that is

"JSON string = {"anotherKey":"anotherValue","aKey":"aValue"}"

Or in pretty format:

{
  "anotherKey" : "anotherValue",
  "aKey" : "aValue"
}

The dictionary is enclosed in curly braces in the JSON output, just as you'd expect.

EDIT:

In Swift 3/4 syntax, the code above looks like this:

  let dictionary = ["aKey": "aValue", "anotherKey": "anotherValue"]
    if let theJSONData = try?  JSONSerialization.data(
      withJSONObject: dictionary,
      options: .prettyPrinted
      ),
      let theJSONText = String(data: theJSONData,
                               encoding: String.Encoding.ascii) {
          print("JSON string = \n\(theJSONText)")
    }
  }

What is the best way to remove a table row with jQuery?

Easy.. Try this

$("table td img.delete").click(function () {
    $(this).parent().parent().parent().fadeTo(400, 0, function () { 
        $(this).remove();
    });
    return false;
});

How to open a PDF file in an <iframe>?

This is the code to link an HTTP(S) accessible PDF from an <iframe>:

<iframe src="https://research.google.com/pubs/archive/44678.pdf"
   width="800" height="600">

Fiddle: http://jsfiddle.net/cEuZ3/1545/

EDIT: and you can use Javascript, from the <a> tag (onclick event) to set iFrame' SRC attribute at run-time...

EDIT 2: Apparently, it is a bug (but there are workarounds):

PDF files do not open in Internet Explorer with Adobe Reader 10.0 - users get an empty gray screen. How can I fix this for my users?

Get Android .apk file VersionName or VersionCode WITHOUT installing apk

Kotlin:

var ver: String = packageManager.getPackageInfo(packageName, 0).versionName

How to resize a custom view programmatically?

this.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, theSizeIWant));

Problem solved!

NOTE: Be sure to use the parent Layout's LayoutParams. Mine is LinearLayout.LayoutParams!

What is android:weightSum in android, and how does it work?

After some experimenting, I think the algorithm for LinearLayout is this:

Assume that weightSum is set to a value. The case of absence is discussed later.

First, divide the weightSum by the number of elements whith match_parent or fill_parent in the dimension of the LinearLayout (e.g. layout_width for orientation="horizontal"). We will call this value the weight multiplier w_m for each element. The default value for weightSum is 1.0, so the default weight multiplier is 1/n, where n is the number of fill_parent elements; wrap_content elements do not contribute to n.

w_m = weightSum / #fill_parent

E.g. when weightSum is 60, and there are 3 fill_parent elements, the weight multiplier is 20. The weight multiplier is the default value for e.g. layout_width if the attribute is absent.

Second, the maximum possible expansion of every element is computed. First, the wrap_content elements are computed according to their contents. Their expansion is deducted from the expansion of the parent container. We will call the remainer expansion_remainer. This remainder is distributed among fill_parent elements according to their layout_weight.

Third, the expansion of every fill_parent element is computed as:

w_m - ( layout_weight / w_m ) * maximum_possible_expansion

Example:

If weightSum is 60, and there are 3 fill_parent elements with the weigths 10, 20 and 30, their expansion on the screen is 2/3, 1/3 and 0/3 of the parent container.

weight | expansion
     0 | 3/3
    10 | 2/3
    20 | 1/3
    30 | 0/3
    40 | 0/3

The minimum expansion is capped at 0. The maximum expansion is capped at parent size, i.e. weights are capped at 0.

If an element is set to wrap_content, its expansion is calculated first, and the remaining expansion is subject to distribution among the fill_parent elements. If weightSum is set, this leads to layout_weight having no effect on wrap_content elements. However, wrap_content elements can still be pushed out of the visible area by elements whose weight is lower than weight multiplier (e.g. between 0-1 for weightSum= 1 or between 0-20 for the above example).

If no weightSum is specified, it is computed as the sum of all layout_weight values, including elements with wrap_content set! So having layout_weight set on wrap_content elements, can influence their expansion. E.g. a negative weight will shrink the other fill_parent elements. Before the fill_parent elements are laid out, will the above formula be applied to wrap_content elements, with maximum possible expansion being their expansion according to the wrapped content. The wrap_content elements will be shrunk, and afterwards the maximum possible expansion for the remaining fill_parent elements is computed and distributed.

This can lead to unintuitive results.

Google Maps API Multiple Markers with Infowindows

Here is the code snippet which will work for sure. You can visit below link for working jsFiddle and explainantion in detail. How to locate multiple addresses on google maps with perfect zoom

var infowindow = new google.maps.InfoWindow();  
google.maps.event.addListener(marker, 'mouseover', (function(marker) {  
           return function() {  
               var content = address;  
               infowindow.setContent(content);  
               infowindow.open(map, marker);  
           }  
         })(marker));  

What's the difference between a Python module and a Python package?

First, keep in mind that, in its precise definition, a module is an object in the memory of a Python interpreter, often created by reading one or more files from disk. While we may informally call a disk file such as a/b/c.py a "module," it doesn't actually become one until it's combined with information from several other sources (such as sys.path) to create the module object.

(Note, for example, that two modules with different names can be loaded from the same file, depending on sys.path and other settings. This is exactly what happens with python -m my.module followed by an import my.module in the interpreter; there will be two module objects, __main__ and my.module, both created from the same file on disk, my/module.py.)

A package is a module that may have submodules (including subpackages). Not all modules can do this. As an example, create a small module hierarchy:

$ mkdir -p a/b
$ touch a/b/c.py

Ensure that there are no other files under a. Start a Python 3.4 or later interpreter (e.g., with python3 -i) and examine the results of the following statements:

import a
a                ? <module 'a' (namespace)>
a.b              ? AttributeError: module 'a' has no attribute 'b'
import a.b.c
a.b              ? <module 'a.b' (namespace)>
a.b.c            ? <module 'a.b.c' from '/home/cjs/a/b/c.py'>

Modules a and a.b are packages (in fact, a certain kind of package called a "namespace package," though we wont' worry about that here). However, module a.b.c is not a package. We can demonstrate this by adding another file, a/b.py to the directory structure above and starting a fresh interpreter:

import a.b.c
? ImportError: No module named 'a.b.c'; 'a.b' is not a package
import a.b
a                ? <module 'a' (namespace)>
a.__path__       ? _NamespacePath(['/.../a'])
a.b              ? <module 'a.b' from '/home/cjs/tmp/a/b.py'>
a.b.__path__     ? AttributeError: 'module' object has no attribute '__path__'

Python ensures that all parent modules are loaded before a child module is loaded. Above it finds that a/ is a directory, and so creates a namespace package a, and that a/b.py is a Python source file which it loads and uses to create a (non-package) module a.b. At this point you cannot have a module a.b.c because a.b is not a package, and thus cannot have submodules.

You can also see here that the package module a has a __path__ attribute (packages must have this) but the non-package module a.b does not.

How to configure robots.txt to allow everything?

I understand that this is fairly old question and has some pretty good answers. But, here is my two cents for the sake of completeness.

As per the official documentation, there are four ways, you can allow complete access for robots to access your site.

Clean:

Specify a global matcher with a disallow segment as mentioned by @unor. So your /robots.txt looks like this.

User-agent: *
Disallow:

The hack:

Create a /robots.txt file with no content in it. Which will default to allow all for all type of Bots.

I don't care way:

Do not create a /robots.txt altogether. Which should yield the exact same results as the above two.

The ugly:

From the robots documentation for meta tags, You can use the following meta tag on all your pages on your site to let the Bots know that these pages are not supposed to be indexed.

<META NAME="ROBOTS" CONTENT="NOINDEX">

In order for this to be applied to your entire site, You will have to add this meta tag for all of your pages. And this tag should strictly be placed under your HEAD tag of the page. More about this meta tag here.

How do I get the web page contents from a WebView?

Have you considered fetching the HTML separately, and then loading it into a webview?

String fetchContent(WebView view, String url) throws IOException {
    HttpClient httpClient = new DefaultHttpClient();
    HttpGet get = new HttpGet(url);
    HttpResponse response = httpClient.execute(get);
    StatusLine statusLine = response.getStatusLine();
    int statusCode = statusLine.getStatusCode();
    HttpEntity entity = response.getEntity();
    String html = EntityUtils.toString(entity); // assume html for simplicity
    view.loadDataWithBaseURL(url, html, "text/html", "utf-8", url); // todo: get mime, charset from entity
    if (statusCode != 200) {
        // handle fail
    }
    return html;
}

Java: method to get position of a match in a String?

Finding a single index

As others have said, use text.indexOf(match) to find a single match.

String text = "0123456789hello0123456789";
String match = "hello";
int position = text.indexOf(match); // position = 10

Finding multiple indexes

Because of @StephenC's comment about code maintainability and my own difficulty in understanding @polygenelubricants' answer, I wanted to find another way to get all the indexes of a match in a text string. The following code (which is modified from this answer) does so:

String text = "0123hello9012hello8901hello7890";
String match = "hello";

int index = text.indexOf(match);
int matchLength = match.length();
while (index >= 0) {  // indexOf returns -1 if no match found
    System.out.println(index);
    index = text.indexOf(match, index + matchLength);
}

Conversion of a datetime2 data type to a datetime data type results out-of-range value

The Entity Framework 4 works with the datetime2 data type so in db the corresponding field must be datetime2 for SQL Server 2008.

To achive the solution there are two ways.

  1. To use the datetime data type in Entity Framwork 4 you have to switch the ProviderManifestToken in the edmx-file to "2005".
  2. If you set corresponding field as Allow Null (it converts it to NULLABLE) so then EF automatically uses date objects as datetime.

How to store JSON object in SQLite database

An alternative could be to use the new JSON extension for SQLite. I've only just come across this myself: https://www.sqlite.org/json1.html This would allow you to perform a certain level of querying the stored JSON. If you used VARCHAR or TEXT to store a JSON string you would have no ability to query it. This is a great article showing its usage (in python) http://charlesleifer.com/blog/using-the-sqlite-json1-and-fts5-extensions-with-python/

Subtract two variables in Bash

Alternatively to the suggested 3 methods you can try let which carries out arithmetic operations on variables as follows:

let COUNT=$FIRSTV-$SECONDV

or

let COUNT=FIRSTV-SECONDV

Cleanest way to toggle a boolean variable in Java?

Unfortunately, there is no short form like numbers have increment/decrement:

i++;

I would like to have similar short expression to invert a boolean, dmth like:

isEmpty!;

How to delete the first row of a dataframe in R?

I am not expert, but this may work as well,

dat <- dat[2:nrow(dat), ]

Terminating a script in PowerShell

Terminates this process and gives the underlying operating system the specified exit code.

https://msdn.microsoft.com/en-us/library/system.environment.exit%28v=vs.110%29.aspx

[Environment]::Exit(1)

This will allow you to exit with a specific exit code, that can be picked up from the caller.

How to style a checkbox using CSS

Simple to implement and easily customizable solution

After a lot of search and testing I got this solution which is simple to implement and easier to customize. In this solution:

  1. You don't need external libraries and files
  2. You don't need to add extra HTML in your page
  3. You don't need to change checkbox names and id

Simple put the flowing CSS at the top of your page and all checkboxes style will change like this:

Enter image description here

_x000D_
_x000D_
input[type=checkbox] {
  transform: scale(1.5);
}

input[type=checkbox] {
  width: 30px;
  height: 30px;
  margin-right: 8px;
  cursor: pointer;
  font-size: 17px;
  visibility: hidden;
}

input[type=checkbox]:after {
  content: " ";
  background-color: #fff;
  display: inline-block;
  margin-left: 10px;
  padding-bottom: 5px;
  color: #00BFF0;
  width: 22px;
  height: 25px;
  visibility: visible;
  border: 1px solid #00BFF0;
  padding-left: 3px;
  border-radius: 5px;
}

input[type=checkbox]:checked:after {
  content: "\2714";
  padding: -5px;
  font-weight: bold;
}
_x000D_
<input type="checkbox" id="checkbox1" />
<label for="checkbox1">Checkbox</label>
_x000D_
_x000D_
_x000D_

.rar, .zip files MIME Type

You should not trust $_FILES['upfile']['mime'], check MIME type by yourself. For that purpose, you may use fileinfo extension, enabled by default as of PHP 5.3.0.

  $fileInfo = new finfo(FILEINFO_MIME_TYPE);
  $fileMime = $fileInfo->file($_FILES['upfile']['tmp_name']);
  $validMimes = array( 
    'zip' => 'application/zip',
    'rar' => 'application/x-rar',
  );

  $fileExt = array_search($fileMime, $validMimes, true);
  if($fileExt != 'zip' && $fileExt != 'rar')
    throw new RuntimeException('Invalid file format.');

NOTE: Don't forget to enable the extension in your php.ini and restart your server:

extension=php_fileinfo.dll

Using generic std::function objects with member functions in one class

You can use functors if you want a less generic and more precise control under the hood. Example with my win32 api to forward api message from a class to another class.

IListener.h

#include <windows.h>
class IListener { 
    public:
    virtual ~IListener() {}
    virtual LRESULT operator()(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) = 0;
};

Listener.h

#include "IListener.h"
template <typename D> class Listener : public IListener {
    public:
    typedef LRESULT (D::*WMFuncPtr)(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam); 

    private:
    D* _instance;
    WMFuncPtr _wmFuncPtr; 

    public:
    virtual ~Listener() {}
    virtual LRESULT operator()(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) override {
        return (_instance->*_wmFuncPtr)(hWnd, uMsg, wParam, lParam);
    }

    Listener(D* instance, WMFuncPtr wmFuncPtr) {
        _instance = instance;
        _wmFuncPtr = wmFuncPtr;
    }
};

Dispatcher.h

#include <map>
#include "Listener.h"

class Dispatcher {
    private:
        //Storage map for message/pointers
        std::map<UINT /*WM_MESSAGE*/, IListener*> _listeners; 

    public:
        virtual ~Dispatcher() { //clear the map }

        //Return a previously registered callable funtion pointer for uMsg.
        IListener* get(UINT uMsg) {
            typename std::map<UINT, IListener*>::iterator itEvt;
            if((itEvt = _listeners.find(uMsg)) == _listeners.end()) {
                return NULL;
            }
            return itEvt->second;
        }

        //Set a member function to receive message. 
        //Example Button->add<MyClass>(WM_COMMAND, this, &MyClass::myfunc);
        template <typename D> void add(UINT uMsg, D* instance, typename Listener<D>::WMFuncPtr wmFuncPtr) {
            _listeners[uMsg] = new Listener<D>(instance, wmFuncPtr);
        }

};

Usage principles

class Button {
    public:
    Dispatcher _dispatcher;
    //button window forward all received message to a listener
    LRESULT onMessage(HWND hWnd, UINT uMsg, WPARAM w, LPARAM l) {
        //to return a precise message like WM_CREATE, you have just
        //search it in the map.
        return _dispatcher[uMsg](hWnd, uMsg, w, l);
    }
};

class Myclass {
    Button _button;
    //the listener for Button messages
    LRESULT button_listener(HWND hWnd, UINT uMsg, WPARAM w, LPARAM l) {
        return 0;
    }

    //Register the listener for Button messages
    void initialize() {
        //now all message received from button are forwarded to button_listener function 
       _button._dispatcher.add(WM_CREATE, this, &Myclass::button_listener);
    }
};

Good luck and thank to all for sharing knowledge.

Add carriage return to a string

string s2 = s1.Replace(",", ",\r\n");

WampServer: php-win.exe The program can't start because MSVCR110.dll is missing

What solves my problem: I am using 64 bit Windows 7, so I thought I could install 64 bit Wamp. After I Installed the 32-bit version the error does not appear. So something in the developing process at Wamp went wrong...

Dynamically allocating an array of objects

I'd recommend using std::vector: something like

typedef std::vector<int> A;
typedef std::vector<A> AS;

There's nothing wrong with the slight overkill of STL, and you'll be able to spend more time implementing the specific features of your app instead of reinventing the bicycle.

How do I set 'semi-bold' font via CSS? Font-weight of 600 doesn't make it look like the semi-bold I see in my Photoshop file

In CSS, for the font-weight property, the value: normal defaults to the numeric value 400, and bold to 700.

If you want to specify other weights, you need to give the number value. That number value needs to be supported for the font family that you are using.

For example you would define semi-bold like this:

font-weight: 600;

Here an JSFiddle using 'Open Sans' font family, loaded with the above weights.

How to style a clicked button in CSS

There are three states of button

  • Normal : You can select like this button
  • Hover : You can select like this button:hover
  • Pressed/Clicked : You can select like this button:active

Normal:

.button
 {
     //your css
 }

Active

 .button:active
{
        //your css
}

Hover

 .button:hover
{
        //your css
}

SNIPPET:

Use :active to style the active state of button.

_x000D_
_x000D_
button:active{_x000D_
   background-color:red;_x000D_
}
_x000D_
<button>Click Me</button>
_x000D_
_x000D_
_x000D_

How to write new line character to a file in Java

    PrintWriter out = null; // for writting in file    
    String newLine = System.getProperty("line.separator"); // taking new line 
    out.print("1st Line"+newLine); // print with new line
    out.print("2n Line"+newLine);  // print with new line
    out.close();

wget command to download a file and save as a different filename

You would use the command Mechanical snail listed. Notice the uppercase O. Full command line to use could be:

wget www.examplesite.com/textfile.txt --output-document=newfile.txt

or

wget www.examplesite.com/textfile.txt -O newfile.txt

Hope that helps.

Div with horizontal scrolling only

For horizontal scroll, keep these two properties in mind:

overflow-x:scroll;
white-space: nowrap;

See working link : click me

HTML

<p>overflow:scroll</p>
<div class="scroll">You can use the overflow property when you want to have better   control of the layout. The default value is visible.You can use the overflow property when you want     to have better control of the layout. The default value is visible.</div>

CSS

div.scroll
{
background-color:#00FFFF;
height:40px;
overflow-x:scroll;
white-space: nowrap;
}

Does MySQL ignore null values on unique constraints?

A simple answer would be : No, it doesn't

Explanation : According to the definition of unique constraints (SQL-92)

A unique constraint is satisfied if and only if no two rows in a table have the same non-null values in the unique columns

This statement can have two interpretations as :

  • No two rows can have same values i.e. NULL and NULL is not allowed
  • No two non-null rows can have values i.e NULL and NULL is fine, but StackOverflow and StackOverflow is not allowed

Since MySQL follows second interpretation, multiple NULL values are allowed in UNIQUE constraint column. Second, if you would try to understand the concept of NULL in SQL, you will find that two NULL values can be compared at all since NULL in SQL refers to unavailable or unassigned value (you can't compare nothing with nothing). Now, if you are not allowing multiple NULL values in UNIQUE constraint column, you are contracting the meaning of NULL in SQL. I would summarise my answer by saying :

MySQL supports UNIQUE constraint but not on the cost of ignoring NULL values

remove first element from array and return the array minus the first element

This can be done in one line with lodash _.tail:

_x000D_
_x000D_
var arr = ["item 1", "item 2", "item 3", "item 4"];_x000D_
console.log(_.tail(arr));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
_x000D_
_x000D_
_x000D_

Get index of a row of a pandas dataframe as an integer

Little sum up for searching by row:

This can be useful if you don't know the column values ??or if columns have non-numeric values

if u want get index number as integer u can also do:

item = df[4:5].index.item()
print(item)
4

it also works in numpy / list:

numpy = df[4:7].index.to_numpy()[0]
lista = df[4:7].index.to_list()[0]

in [x] u pick number in range [4:7], for example if u want 6:

numpy = df[4:7].index.to_numpy()[2]
print(numpy)
6

for DataFrame:

df[4:7]

    A          B
4   5   0.894525
5   6   0.978174
6   7   0.859449

or:

df[(df.index>=4) & (df.index<7)]

    A          B
4   5   0.894525
5   6   0.978174
6   7   0.859449   

How to make Scrollable Table with fixed headers using CSS

What you want to do is separate the content of the table from the header of the table. You want only the <th> elements to be scrolled. You can easily define this separation in HTML with the <tbody> and the <thead> elements.
Now the header and the body of the table are still connected to each other, they will still have the same width (and same scroll properties). Now to let them not 'work' as a table anymore you can set the display: block. This way <thead> and <tbody> are separated.

table tbody, table thead
{
    display: block;
}

Now you can set the scroll to the body of the table:

table tbody 
{
   overflow: auto;
   height: 100px;
}

And last, because the <thead> doesn't share the same width as the body anymore, you should set a static width to the header of the table:

th
{
    width: 72px;
}

You should also set a static width for <td>. This solves the issue of the unaligned columns.

td
{
    width: 72px;
}


Note that you are also missing some HTML elements. Every row should be in a <tr> element, that includes the header row:

<tr>
     <th>head1</th>
     <th>head2</th>
     <th>head3</th>
     <th>head4</th>
</tr>

I hope this is what you meant.

jsFiddle

Addendum

If you would like to have more control over the column widths, have them to vary in width between each other, and course keep the header and body columns aligned, you can use the following example:

    table th:nth-child(1), td:nth-child(1) { min-width: 50px;  max-width: 50px; }
    table th:nth-child(2), td:nth-child(2) { min-width: 100px; max-width: 100px; }
    table th:nth-child(3), td:nth-child(3) { min-width: 150px; max-width: 150px; }
    table th:nth-child(4), td:nth-child(4) { min-width: 200px; max-width: 200px; }

Change the "From:" address in Unix "mail"

It's also possible to set both the From name and from address using something like:

 echo test | mail -s "test" [email protected] -- -F'Some Name<[email protected]>' -t

For some reason passing -F'Some Name' and [email protected] doesn't work, but passing in the -t to sendmail works and is "easy".

How could I create a list in c++?

Create list using C++ templates

i.e

template <class T> struct Node 
{
    T data;
    Node * next;
};
    
template <class T> class List 
{
    Node<T> *head,*tail;
        
    public: 
        void push(T const&);  // push element 
        void pop();           // pop element 
        bool empty()          // return true if empty. 
}; 

Then you can write the code like:

List<MyClass>;

The type T is not dynamic in run time.It is only for the compile time.

For complete example click here.

For C++ templates tutorial click here.

warning: implicit declaration of function

I think the question is not 100% answered. I was searching for issue with missing typeof(), which is compile time directive.

Following links will shine light on the situation:

https://gcc.gnu.org/onlinedocs/gcc-5.3.0/gcc/Typeof.html

https://gcc.gnu.org/onlinedocs/gcc-5.3.0/gcc/Alternate-Keywords.html#Alternate-Keywords

as of conculsion try to use __typeof__() instead. Also gcc ... -Dtypeof=__typeof__ ... can help.

How do you update Xcode on OSX to the latest version?

Sometime I don't see the Xcode update in Updates tab in AppStore
So I search Xcode in AppStore enter image description here

Then click update and it update

Python check if website exists

It's better to check that status code is < 400, like it was done here. Here is what do status codes mean (taken from wikipedia):

  • 1xx - informational
  • 2xx - success
  • 3xx - redirection
  • 4xx - client error
  • 5xx - server error

If you want to check if page exists and don't want to download the whole page, you should use Head Request:

import httplib2
h = httplib2.Http()
resp = h.request("http://www.google.com", 'HEAD')
assert int(resp[0]['status']) < 400

taken from this answer.

If you want to download the whole page, just make a normal request and check the status code. Example using requests:

import requests

response = requests.get('http://google.com')
assert response.status_code < 400

See also similar topics:

Hope that helps.

jQuery: select all elements of a given class, except for a particular Id

Use the :not selector.

$(".thisclass:not(#thisid)").doAction();

If you have multiple ids or selectors just use the comma delimiter, in addition:

(".thisclass:not(#thisid,#thatid)").doAction();

Null pointer Exception on .setOnClickListener

android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference

Because Submit button is inside login_modal so you need to use loginDialog view to access button:

Submit = (Button)loginDialog.findViewById(R.id.Submit);

Override devise registrations controller

In your form are you passing in any other attributes, via mass assignment that don't belong to your user model, or any of the nested models?

If so, I believe the ActiveRecord::UnknownAttributeError is triggered in this instance.

Otherwise, I think you can just create your own controller, by generating something like this:

# app/controllers/registrations_controller.rb
class RegistrationsController < Devise::RegistrationsController
  def new
    super
  end

  def create
    # add custom create logic here
  end

  def update
    super
  end
end 

And then tell devise to use that controller instead of the default with:

# app/config/routes.rb
devise_for :users, :controllers => {:registrations => "registrations"}

Difference between single and double quotes in Bash

There is a clear distinction between the usage of ' ' and " ".

When ' ' is used around anything, there is no "transformation or translation" done. It is printed as it is.

With " ", whatever it surrounds, is "translated or transformed" into its value.

By translation/ transformation I mean the following: Anything within the single quotes will not be "translated" to their values. They will be taken as they are inside quotes. Example: a=23, then echo '$a' will produce $a on standard output. Whereas echo "$a" will produce 23 on standard output.

Java: Date from unix timestamp

Sometimes you need to work with adjustments.

Don't use cast to long! Use nanoadjustment.

For example, using Oanda Java API for trading you can get datetime as UNIX format.

For example: 1592523410.590566943

    System.out.println("instant with nano = " + Instant.ofEpochSecond(1592523410, 590566943));
    System.out.println("instant = " + Instant.ofEpochSecond(1592523410));

you get:

instant with nano = 2020-06-18T23:36:50.590566943Z
instant = 2020-06-18T23:36:50Z

Also, use:

 Date date = Date.from( Instant.ofEpochSecond(1592523410, 590566943) );

How to open a WPF Popup when another control is clicked, using XAML markup only?

The following approach is the same as Helge Klein's, except that the popup closes automatically when you click anywhere outside the Popup (including the ToggleButton itself):

<ToggleButton x:Name="Btn" IsHitTestVisible="{Binding ElementName=Popup, Path=IsOpen, Mode=OneWay, Converter={local:BoolInverter}}">
    <TextBlock Text="Click here for popup!"/>
</ToggleButton>

<Popup IsOpen="{Binding IsChecked, ElementName=Btn}" x:Name="Popup" StaysOpen="False">
    <Border BorderBrush="Black" BorderThickness="1" Background="LightYellow">
        <CheckBox Content="This is a popup"/>
    </Border>
</Popup>

"BoolInverter" is used in the IsHitTestVisible binding so that when you click the ToggleButton again, the popup closes:

public class BoolInverter : MarkupExtension, IValueConverter
{
    public override object ProvideValue(IServiceProvider serviceProvider)
    {
        return this;
    }

    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value is bool)
            return !(bool)value;
        return value;
    }
    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return Convert(value, targetType, parameter, culture);
    }
}

...which shows the handy technique of combining IValueConverter and MarkupExtension in one.

I did discover one problem with this technique: WPF is buggy when two popups are on the screen at the same time. Specifically, if your toggle button is on the "overflow popup" in a toolbar, then there will be two popups open after you click it. You may then find that the second popup (your popup) will stay open when you click anywhere else on your window. At that point, closing the popup is difficult. The user cannot click the ToggleButton again to close the popup because IsHitTestVisible is false because the popup is open! In my app I had to use a few hacks to mitigate this problem, such as the following test on the main window, which says (in the voice of Louis Black) "if the popup is open and the user clicks somewhere outside the popup, close the friggin' popup.":

PreviewMouseDown += (s, e) =>
{
    if (Popup.IsOpen)
    {
        Point p = e.GetPosition(Popup.Child);
        if (!IsInRange(p.X, 0, ((FrameworkElement)Popup.Child).ActualWidth) ||
            !IsInRange(p.Y, 0, ((FrameworkElement)Popup.Child).ActualHeight))
            Popup.IsOpen = false;
    }
};
// Elsewhere...
public static bool IsInRange(int num, int lo, int hi) => 
    num >= lo && num <= hi;

How to perform Unwind segue programmatically?

FYI: In order for @Vadim's answer to work with a manual unwind seque action called from within a View Controller you must place the command:

[self performSegueWithIdentifier:(NSString*) identifier sender:(id) sender];

inside of the overriden class method viewDidAppear like so:

-(void) viewDidAppear:(BOOL) animated
{
    [super viewDidAppear: animated];

    [self performSegueWithIdentifier:@"SomeSegueIdentifier" sender:self];
}

If you put it in other ViewController methods like viewDidLoad or viewWillAppear it will be ignored.

Get Value of Radio button group

Your quotes only need to surround the value part of the attribute-equals selector, [attr='val'], like this:

$('a#check_var').click(function() {
  alert($("input:radio[name='r']:checked").val()+ ' '+
        $("input:radio[name='s']:checked").val());
});?

You can see the working version here.

CSS transition shorthand with multiple properties?

I think that this should work:

.element {
   -webkit-transition: all .3s;
   -moz-transition: all .3s;
   -o-transition: all .3s;
   transition: all .3s;
}

Convert string into Date type on Python

Use datetime.datetime.strptime:

>>> import datetime
>>> date = datetime.datetime.strptime('2012-02-10', '%Y-%m-%d')
>>> date.isoweekday()
5

Java: How to get input from System.console()

Scanner in = new Scanner(System.in);

int i = in.nextInt();
String s = in.next();

Show empty string when date field is 1/1/1900

Two nitpicks. (1) Best not to use string literals for column alias - that is deprecated. (2) Just use style 120 to get the same value.

    CASE 
      WHEN CreatedDate = '19000101' THEN '' 
      WHEN CreatedDate = '18000101' THEN '' 
      ELSE Convert(varchar(19), CreatedDate, 120)
    END AS [Created Date]

WordPress: get author info from post id

If you want it outside of loop then use the below code.

<?php
$author_id = get_post_field ('post_author', $cause_id);
$display_name = get_the_author_meta( 'display_name' , $author_id ); 
echo $display_name;
?>

Need to install urllib2 for Python 3.5.1

Acording to the docs:

Note The urllib2 module has been split across several modules in Python 3 named urllib.request and urllib.error. The 2to3 tool will automatically adapt imports when converting your sources to Python 3.

So it appears that it is impossible to do what you want but you can use appropriate python3 functions from urllib.request.