Programs & Examples On #Bundles

My eclipse won't open, i download the bundle pack it keeps saying error log

Make sure you have the prerequisite, a JVM (http://wiki.eclipse.org/Eclipse/Installation#Install_a_JVM) installed.

This will be a JRE and JDK package.

There are a number of sources which includes: http://www.oracle.com/technetwork/java/javase/downloads/index.html.

No provider for HttpClient

You have not provided providers in your module:

<strike>import { HttpModule } from '@angular/http';</strike>
import { HttpClientModule, HttpClient } from '@angular/common/http';

@NgModule({
  imports: [
    BrowserModule,
    HttpClientModule,
    BrowserAnimationsModule,
    FormsModule,
    AppRoutingModule
  ],
  providers: [ HttpClientModule, ... ]
  // ...
})
export class MyModule { /* ... */ }

Using HttpClient in Tests

You will need to add the HttpClientTestingModule to the TestBed configuration when running ng test and getting the "No provider for HttpClient" error:

// Http testing module and mocking controller
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';

// Other imports
import { TestBed } from '@angular/core/testing';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';

describe('HttpClient testing', () => {
  let httpClient: HttpClient;
  let httpTestingController: HttpTestingController;

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [ HttpClientTestingModule ]
    });

    // Inject the http service and test controller for each test
    httpClient = TestBed.get(HttpClient);
    httpTestingController = TestBed.get(HttpTestingController);
  });

  it('works', () => {
  });
});

VSCode cannot find module '@angular/core' or any other modules

for Visual Studio -->

    Seems like you don't have `node_modules` directory in your project folder.
     
    Execute this command where `package.json` file is located:
    
     npm install 

Use custom build output folder when using create-react-app

webpack =>

renamed as build to dist

output: {
      filename: '[name].bundle.js',
      path: path.resolve(__dirname, 'dist'),
    },

How to decrease prod bundle size?

Firstly, vendor bundles are huge simply because Angular 2 relies on a lot of libraries. Minimum size for Angular 2 app is around 500KB (250KB in some cases, see bottom post).
Tree shaking is properly used by angular-cli.
Do not include .map files, because used only for debugging. Moreover, if you use hot replacement module, remove it to lighten vendor.

To pack for production, I personnaly use Webpack (and angular-cli relies on it too), because you can really configure everything for optimization or debugging.
If you want to use Webpack, I agree it is a bit tricky a first view, but see tutorials on the net, you won't be disappointed.
Else, use angular-cli, which get the job done really well.

Using Ahead-of-time compilation is mandatory to optimize apps, and shrink Angular 2 app to 250KB.

Here is a repo I created (github.com/JCornat/min-angular) to test minimal Angular bundle size, and I obtain 384kB. I am sure there is easy way to optimize it.

Talking about big apps, using the AngularClass/angular-starter configuration, the same as in the repo above, my bundle size for big apps (150+ components) went from 8MB (4MB without map files) to 580kB.

Error: Unexpected value 'undefined' imported by the module

This can be caused by multiple scenarios like

  1. Missing commas
imports: [
    BrowserModule
   ,routing <= Missing Comma
   ,FeatureComponentsModule
  ],
  1. Double Commas
imports: [
    BrowserModule, 
   ,routing <=Double Comma
   ,FeatureComponentsModule
  ],
  1. Exporting Nothing from the Module
  2. Syntax errors
  3. Typo Errors
  4. Semicolons inside Objects, Arrays
  5. Incorrect import Statements

Angular2 QuickStart npm start is not working correctly

Try this:

  1. Install Latest versions npm/nodejs I purged my npm installation
  2. After that, install tsd npm install -g tsd
  3. Then clone https://github.com/johnpapa/angular2-tour-of-heroes.git
  4. Finally npm i and npm start

Angular2 Exception: Can't bind to 'routerLink' since it isn't a known native property

If you use shared modules, just add RouterModule to a Module where your component is declared and don't forget to add <router-outlet></router-outlet>

Referenced from here RouterLink does not work

What is @RenderSection in asp.net MVC

Here the defination of Rendersection from MSDN

In layout pages, renders the content of a named section.MSDN

In _layout.cs page put

@RenderSection("Bottom",false)

Here render the content of bootom section and specifies false boolean property to specify whether the section is required or not.

@section Bottom{
       This message form bottom.
}

That meaning if you want to bottom section in all pages, then you must use false as the second parameter at Rendersection method.

Running Composer returns: "Could not open input file: composer.phar"

To googlers who installed composer via HomeBrew: make a symbolic link for /usr/local/bin/composer

ln -s /usr/local/bin/composer /usr/local/bin/composer.phar

ASP.NET MVC Bundle not rendering script files on staging server. It works on development server

Things to check when enabling the bundle optimization;

BundleTable.EnableOptimizations = true;

and

webconfig debug = "false"
  1. the bundles.IgnoreList.Clear();

this will ignore the minified assets of your bundles like *.min.css or *.min.js which can cause an undefine error of your script. To fix is replace the .min asset to original. if you do this you may not need the bundles.IgnoreList.Clear(); e.g.

bundles.Add(new ScriptBundle("~/bundles/datatablesjs")
      .Include("~/Scripts/datatables.min.js") <---- change this to non minified ver.
  1. Make sure the names of the bundles of your css and js are unique.

    bundles.Add(new StyleBundle("~/bundles/datatablescss").Include( ...) );

    bundles.Add(new ScriptBundle("~/bundles/datatablesjs").Include( ...) );

  2. Make sure you use the Render name of your @Script.Render and Style.Render are the same on your bundle config. e.g.

    @Styles.Render("~/bundles/datatablescss")

    @Scripts.Render("~/bundles/datatablesjs")

How to add Date Picker Bootstrap 3 on MVC 5 project using the Razor engine?

Checkout Shield UI's Date Picker for MVC. A powerful component that you can integrate with a few lines like:

@(Html.ShieldDatePicker()
    .Name("datepicker"))

Import Google Play Services library in Android Studio

I had similar issue Cannot resolve com.google.android.gms.common.

I followed setup guide http://developer.android.com/google/play-services/setup.html and it works!

Summary:

  1. Installed/Updated Google Play Services, and Google Repository from SDK Manager
  2. Added dependency in build.gradle: compile 'com.google.android.gms:play-services:4.0.30'
  3. Updated AndroidManifest.xml with <meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version" />

Multiple dex files define Landroid/support/v4/accessibilityservice/AccessibilityServiceInfoCompat

Received the following error

Execution failed for task ':app:transformDexArchiveWithDexMergerForDebug'.

com.android.build.api.transform.TransformException: com.android.dex.DexException: Multiple dex files define Landroid/support/constraint/ConstraintSet$1

Fix : go to Build -> Clean Project

How to resume Fragment from BackStack if exists

I know this is quite late to answer this question but I resolved this problem by myself and thought worth sharing it with everyone.`

public void replaceFragment(BaseFragment fragment) {
    FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
    final FragmentManager fManager = getSupportFragmentManager();
    BaseFragment fragm = (BaseFragment) fManager.findFragmentByTag(fragment.getFragmentTag());
    transaction.setCustomAnimations(R.anim.enter_from_right, R.anim.exit_to_left, R.anim.enter_from_left, R.anim.exit_to_right);

    if (fragm == null) {  //here fragment is not available in the stack
        transaction.replace(R.id.container, fragment, fragment.getFragmentTag());
        transaction.addToBackStack(fragment.getFragmentTag());
    } else { 
        //fragment was found in the stack , now we can reuse the fragment
        // please do not add in back stack else it will add transaction in back stack
        transaction.replace(R.id.container, fragm, fragm.getFragmentTag()); 
    }
    transaction.commit();
}

And in the onBackPressed()

 @Override
public void onBackPressed() {
    if(getSupportFragmentManager().getBackStackEntryCount()>1){
        super.onBackPressed();
    }else{
        finish();
    }
}

Android Studio: Gradle - build fails -- Execution failed for task ':dexDebug'

just add in build.gradle

compile 'com.parse.bolts:bolts-android:1.+'

compile 'com.parse:parse-android:1.11.0'

and sync Project with Gradle Files enter image description here But Don't Add The parse Jar in libs :) OKK

How to use Tomcat 8 in Eclipse?

UPDATE: Eclipse Mars EE and later have native support for Tomcat8. Use this only if you have an earlier version of eclipse.


The latest version of Eclipse still does not support Tomcat 8, but you can add the new version of WTP and Tomcat 8 support will be added natively. To do this:

  • Download the latest version of Eclipse for Java EE
  • Go to the WTP downloads page, select the latest version (currently 3.6), and download the zip (under Traditional Zip Files...Web App Developers). Here's the current link.
  • Copy the all of the files in features and plugins directories of the downloaded WTP into the corresponding Eclipse directories in your Eclipse folder (overwriting the existing files).

Start Eclipse and you should have a Tomcat 8 option available when you go to deploy. enter image description here

How to build an android library with Android Studio and gradle?

Gradle Build Tools 2.2.0+ - Everything just works

This is the correct way to do it

In trying to avoid experimental and frankly fed up with the NDK and all its hackery I am happy that 2.2.x of the Gradle Build Tools came out and now it just works. The key is the externalNativeBuild and pointing ndkBuild path argument at an Android.mk or change ndkBuild to cmake and point the path argument at a CMakeLists.txt build script.

android {
    compileSdkVersion 19
    buildToolsVersion "25.0.2"

    defaultConfig {
        minSdkVersion 19
        targetSdkVersion 19

        ndk {
            abiFilters 'armeabi', 'armeabi-v7a', 'x86'
        }

        externalNativeBuild {
            cmake {
                cppFlags '-std=c++11'
                arguments '-DANDROID_TOOLCHAIN=clang',
                        '-DANDROID_PLATFORM=android-19',
                        '-DANDROID_STL=gnustl_static',
                        '-DANDROID_ARM_NEON=TRUE',
                        '-DANDROID_CPP_FEATURES=exceptions rtti'
            }
        }
    }

    externalNativeBuild {
        cmake {
             path 'src/main/jni/CMakeLists.txt'
        }
        //ndkBuild {
        //   path 'src/main/jni/Android.mk'
        //}
    }
}

For much more detail check Google's page on adding native code.

After this is setup correctly you can ./gradlew installDebug and off you go. You will also need to be aware that the NDK is moving to clang since gcc is now deprecated in the Android NDK.

MVC 4 Edit modal form using Bootstrap

In reply to Dimitrys answer but using Ajax.BeginForm the following works at least with MVC >5 (4 not tested).

  1. write a model as shown in the other answers,

  2. In the "parent view" you will probably use a table to show the data. Model should be an ienumerable. I assume, the model has an id-property. Howeverm below the template, a placeholder for the modal and corresponding javascript

    <table>
    @foreach (var item in Model)
    {
        <tr> <td id="[email protected]"> 
            @Html.Partial("dataRowView", item)
        </td> </tr>
    }
    </table>
    
    <div class="modal fade" id="editor-container" tabindex="-1" 
         role="dialog" aria-labelledby="editor-title">
        <div class="modal-dialog modal-lg" role="document">
            <div class="modal-content" id="editor-content-container"></div>
        </div>
    </div> 
    
    <script type="text/javascript">
        $(function () {
            $('.editor-container').click(function () {
                var url = "/area/controller/MyEditAction";  
                var id = $(this).attr('data-id');  
                $.get(url + '/' + id, function (data) {
                    $('#editor-content-container').html(data);
                    $('#editor-container').modal('show');
                });
            });
        });
    
        function success(data,status,xhr) {
            $('#editor-container').modal('hide');
            $('#editor-content-container').html("");
        }
    
        function failure(xhr,status,error) {
            $('#editor-content-container').html(xhr.responseText);
            $('#editor-container').modal('show');
        }
    </script>
    

note the "editor-success-id" in data table rows.

  1. The dataRowView is a partial containing the presentation of an model's item.

    @model ModelView
    @{
        var item = Model;
    }
    <div class="row">
            // some data 
            <button type="button" class="btn btn-danger editor-container" data-id="@item.Id">Edit</button>
    </div>
    
  2. Write the partial view that is called by clicking on row's button (via JS $('.editor-container').click(function () ... ).

    @model Model
    <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
            <span aria-hidden="true">&times;</span>
        </button>
        <h4 class="modal-title" id="editor-title">Title</h4>
    </div>
    @using (Ajax.BeginForm("MyEditAction", "Controller", FormMethod.Post,
                        new AjaxOptions
                        {
                            InsertionMode = InsertionMode.Replace,
                            HttpMethod = "POST",
                            UpdateTargetId = "editor-success-" + @Model.Id,
                            OnSuccess = "success",
                            OnFailure = "failure",
                        }))
    {
        @Html.ValidationSummary()
        @Html.AntiForgeryToken()
        @Html.HiddenFor(model => model.Id)
        <div class="modal-body">
            <div class="form-horizontal">
                // Models input fields
            </div>
        </div>
        <div class="modal-footer">
            <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
            <button type="submit" class="btn btn-primary">Save</button>
        </div>
    }
    

This is where magic happens: in AjaxOptions, UpdateTargetId will replace the data row after editing, onfailure and onsuccess will control the modal.

This is, the modal will only close when editing was successful and there have been no errors, otherwise the modal will be displayed after the ajax-posting to display error messages, e.g. the validation summary.

But how to get ajaxform to know if there is an error? This is the controller part, just change response.statuscode as below in step 5:

  1. the corresponding controller action method for the partial edit modal

    [HttpGet]
    public async Task<ActionResult> EditPartData(Guid? id)
    {
        // Find the data row and return the edit form
        Model input = await db.Models.FindAsync(id);
        return PartialView("EditModel", input);
    }
    
    [HttpPost, ValidateAntiForgeryToken]
    public async Task<ActionResult> MyEditAction([Bind(Include =
       "Id,Fields,...")] ModelView input)
    {
        if (TryValidateModel(input))
        {  
            // save changes, return new data row  
            // status code is something in 200-range
            db.Entry(input).State = EntityState.Modified;
            await db.SaveChangesAsync();
            return PartialView("dataRowView", (ModelView)input);
        }
    
        // set the "error status code" that will redisplay the modal
        Response.StatusCode = 400;
        // and return the edit form, that will be displayed as a 
        // modal again - including the modelstate errors!
        return PartialView("EditModel", (Model)input);
    }
    

This way, if an error occurs while editing Model data in a modal window, the error will be displayed in the modal with validationsummary methods of MVC; but if changes were committed successfully, the modified data table will be displayed and the modal window disappears.

Note: you get ajaxoptions working, you need to tell your bundles configuration to bind jquery.unobtrusive-ajax.js (may be installed by NuGet):

        bundles.Add(new ScriptBundle("~/bundles/jqueryajax").Include(
                    "~/Scripts/jquery.unobtrusive-ajax.js"));

Eclipse will not start and I haven't changed anything

Maybe worth mentioning that when I had this problem I followed bia.migueis's advice - move everything out of the plugins folder - and the workspace would open again, minus a lot of my configuration. But then after that, I copied/overwrote all the original files back into the plugins folder and opened the workspace again: it still worked and the settings I'd had before seemed to be intact.

How to get list of all installed packages along with version in composer?

The behaviour of this command as been modified so you don't have to pass the -i option:

[10:19:05] coil@coil:~/workspace/api$ composer show -i
You are using the deprecated option "installed". 
Only installed packages are shown by default now. 
The --all option can be used to show all packages.

Load content with ajax in bootstrap modal

The top voted answer is deprecated in Bootstrap 3.3 and will be removed in v4. Try this instead:

JavaScript:

// Fill modal with content from link href
$("#myModal").on("show.bs.modal", function(e) {
    var link = $(e.relatedTarget);
    $(this).find(".modal-body").load(link.attr("href"));
});

Html (Based on the official example. Note that for Bootstrap 3.* we set data-remote="false" to disable the deprecated Bootstrap load function):

<!-- Link trigger modal -->
<a href="remoteContent.html" data-remote="false" data-toggle="modal" data-target="#myModal" class="btn btn-default">
    Launch Modal
</a>

<!-- Default bootstrap modal example -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title" id="myModalLabel">Modal title</h4>
      </div>
      <div class="modal-body">
        ...
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>
      </div>
    </div>
  </div>
</div>

Try it yourself: https://jsfiddle.net/ednon5d1/

Simple example for Intent and Bundle

For example :

In MainActivity :

Intent intent = new Intent(this, OtherActivity.class);
intent.putExtra(OtherActivity.KEY_EXTRA, yourDataObject);
startActivity(intent);

In OtherActivity :

public static final String KEY_EXTRA = "com.example.yourapp.KEY_BOOK";

@Override
protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);

  String yourDataObject = null;

  if (getIntent().hasExtra(KEY_EXTRA)) {
      yourDataObject = getIntent().getStringExtra(KEY_EXTRA);
  } else {
      throw new IllegalArgumentException("Activity cannot find  extras " + KEY_EXTRA);
  }
  // do stuff
}

More informations here : http://developer.android.com/reference/android/content/Intent.html

MVC 4 client side validation not working

Ensure that you are using Attributes (e.g. RequiredAttribute) which comes under System.ComponentModel.DataAnnotations namespace

Unable to open debugger port in IntelliJ

Set the MAVEN_OPTS. It should work !!

export MAVEN_OPTS="-Xdebug -Xnoagent -Djava.compiler=NONE -Xrunjdwp:transport=dt_socket,address=4000,server=y,suspend=n"

mvn spring-boot:run -Dserver.port=8090

Why use @Scripts.Render("~/bundles/jquery")

Bundling is all about compressing several JavaScript or stylesheets files without any formatting (also referred as minified) into a single file for saving bandwith and number of requests to load a page.

As example you could create your own bundle:

bundles.Add(New ScriptBundle("~/bundles/mybundle").Include(
            "~/Resources/Core/Javascripts/jquery-1.7.1.min.js",
            "~/Resources/Core/Javascripts/jquery-ui-1.8.16.min.js",
            "~/Resources/Core/Javascripts/jquery.validate.min.js",
            "~/Resources/Core/Javascripts/jquery.validate.unobtrusive.min.js",
            "~/Resources/Core/Javascripts/jquery.unobtrusive-ajax.min.js",
            "~/Resources/Core/Javascripts/jquery-ui-timepicker-addon.js"))

And render it like this:

@Scripts.Render("~/bundles/mybundle")

One more advantage of @Scripts.Render("~/bundles/mybundle") over the native <script src="~/bundles/mybundle" /> is that @Scripts.Render() will respect the web.config debug setting:

  <system.web>
    <compilation debug="true|false" />

If debug="true" then it will instead render individual script tags for each source script, without any minification.

For stylesheets you will have to use a StyleBundle and @Styles.Render().

Instead of loading each script or style with a single request (with script or link tags), all files are compressed into a single JavaScript or stylesheet file and loaded together.

How to include CSS file in Symfony 2 and Twig?

The other answers are valid, but the Official Symfony Best Practices guide suggests using the web/ folder to store all assets, instead of different bundles.

Scattering your web assets across tens of different bundles makes it more difficult to manage them. Your designers' lives will be much easier if all the application assets are in one location.

Templates also benefit from centralizing your assets, because the links are much more concise[...]

I'd add to this by suggesting that you only put micro-assets within micro-bundles, such as a few lines of styles only required for a button in a button bundle, for example.

ASP.NET Bundles how to disable minification

Combine several answers, this works for me in ASP.NET MVC 4.

        bundles.Add(new ScriptBundle("~/Scripts/Common/js")
            .Include("~/Scripts/jquery-1.8.3.js")
            .Include("~/Scripts/zizhujy.com.js")
            .Include("~/Scripts/Globalize.js")
            .Include("~/Scripts/common.js")
            .Include("~/Scripts/requireLite/requireLite.js"));

        bundles.Add(new StyleBundle("~/Content/appLayoutStyles")
            .Include("~/Content/AppLayout.css"));

        bundles.Add(new StyleBundle("~/Content/css/App/FunGrapherStyles")
            .Include("~/Content/css/Apps/FunGrapher.css")
            .Include("~/Content/css/tables.css"));

#if DEBUG
        foreach (var bundle in BundleTable.Bundles)
        {
            bundle.Transforms.Clear();
        }
#endif

MVC4 StyleBundle not resolving images

I found that CssRewriteUrlTransform fails to run if you're referencing a *.css file and you have the associated *.min.css file in the same folder.

To fix this, either delete the *.min.css file or reference it directly in your bundle:

bundles.Add(new Bundle("~/bundles/bootstrap")
    .Include("~/Libs/bootstrap3/css/bootstrap.min.css", new CssRewriteUrlTransform()));

After that you do that, your URLs will be transformed correctly and your images should be correctly resolved.

MVC 4 @Scripts "does not exist"

The key here is to add

 <add namespace="System.Web.Optimization" /> 

to BOTH web.config files. My scenario was that I had System.Web.Optimization reference in both project and the main/root web.config but @Scripts still didn't work properly. You need to add the namespace reference to the Views web.config file to make it work.

UPDATE:

Since the release of MVC 4 System.Web.Optimization is now obsolete. If you're starting with a blank solution you will need to install the following nuget package:

Install-Package Microsoft.AspNet.Web.Optimization

You will still need to reference System.Web.Optimization in your web.config files. For more information see this topic:

How to add reference to System.Web.Optimization for MVC-3-converted-to-4 app

As many pointed out, restart of VS could be required after the above steps to make this work.

Symfony 2 EntityManager injection in service

Note as of Symfony 3.3 EntityManager is depreciated. Use EntityManagerInterface instead.

namespace AppBundle\Service;

use Doctrine\ORM\EntityManagerInterface;

class Someclass {
    protected $em;

    public function __construct(EntityManagerInterface $entityManager)
    {
        $this->em = $entityManager;
    }

    public function somefunction() {
        $em = $this->em;
        ...
    }
}

Accessing the logged-in user in a template

For symfony 2.6 and above we can use

{{ app.user.getFirstname() }}

as app.security global variable for Twig template has been deprecated and will be removed from 3.0

more info:

http://symfony.com/blog/new-in-symfony-2-6-security-component-improvements

and see the global variables in

http://symfony.com/doc/current/reference/twig_reference.html

Maven Could not resolve dependencies, artifacts could not be resolved

I had this problem. In my case it was caused by IntelliJ Idea messing around with some of the pom.xml files (which it seems to enjoy doing!). I just reverted to the original copy and things worked again!

Can I get a patch-compatible output from git-diff?

If you want to use patch you need to remove the a/ b/ prefixes that git uses by default. You can do this with the --no-prefix option (you can also do this with patch's -p option):

git diff --no-prefix [<other git-diff arguments>]

Usually though, it is easier to use straight git diff and then use the output to feed to git apply.

Most of the time I try to avoid using textual patches. Usually one or more of temporary commits combined with rebase, git stash and bundles are easier to manage.

For your use case I think that stash is most appropriate.

# save uncommitted changes
git stash

# do a merge or some other operation
git merge some-branch

# re-apply changes, removing stash if successful
# (you may be asked to resolve conflicts).
git stash pop

how do you pass images (bitmaps) between android activities using bundles?

in first.java

Intent i = new Intent(this, second.class);
                    i.putExtra("uri",uri);
                    startActivity(i);

in second.java

Bundle bd = getIntent().getExtras();
        Uri uri = bd.getParcelable("uri");
        Log.e("URI", uri.toString());
        try {
            Bitmap bitmap = Media.getBitmap(this.getContentResolver(), uri);
            imageView.setImageBitmap(bitmap);

        } 
        catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

Switch to another Git tag

Clone the repository as normal:

git clone git://github.com/rspec/rspec-tmbundle.git RSpec.tmbundle

Then checkout the tag you want like so:

git checkout tags/1.1.4

This will checkout out the tag in a 'detached HEAD' state. In this state, "you can look around, make experimental changes and commit them, and [discard those commits] without impacting any branches by performing another checkout".

To retain any changes made, move them to a new branch:

git checkout -b 1.1.4-jspooner

You can get back to the master branch by using:

git checkout master

Note, as was mentioned in the first revision of this answer, there is another way to checkout a tag:

git checkout 1.1.4

But as was mentioned in a comment, if you have a branch by that same name, this will result in git warning you that the refname is ambiguous and checking out the branch by default:

warning: refname 'test' is ambiguous.
Switched to branch '1.1.4'

The shorthand can be safely used if the repository does not share names between branches and tags.

How to include jQuery in ASP.Net project?

You can include the script file directly in your page/master page, etc using:

 <script type="text/javascript" src="/scripts/jquery.min.js"></script> 

Us use a Content Delivery network like Google or Microsoft:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script> 

or:

<script src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.js" type="text/javascript"></script>     

A cycle was detected in the build path of project xxx - Build Path Problem

Mark circular dependencies as "Warning" in Eclipse tool to avoid "A CYCLE WAS DETECTED IN THE BUILD PATH" error.

In Eclipse go to:

Windows -> Preferences -> Java-> Compiler -> Building -> Circular Dependencies

Best way to determine user's locale within browser

I did a bit of research regarding this & I have summarised my findings so far in below table

enter image description here

So the recommended solution is to write a a server side script to parse the Accept-Language header & pass it to client for setting the language of the website. It's weird that why the server would be needed to detect the language preference of client but that's how it is as of now There are other various hacks available to detect the language but reading the Accept-Language header is the recommended solution as per my understanding.

macro run-time error '9': subscript out of range

Why are you using a macro? Excel has Password Protection built-in. When you select File/Save As... there should be a Tools button by the Save button, click it then "General Options" where you can enter a "Password to Open" and a "Password to Modify".

Android XML Percent Symbol

Per google official documentation, use %1$s and %2$s http://developer.android.com/guide/topics/resources/string-resource.html#FormattingAndStyling

Hello, %1$s! You have %2$d new messages.

How to execute raw queries with Laravel 5.1?

    DB::statement("your query")

I used it for add index to column in migration

How to make audio autoplay on chrome

I add controls attribute too tag audio, and simply hide it in CSS. And all works fine in Chrome.

<audio autoplay loop controls id="playAudio">
  <source src="audio/source.mp3">
</audio>

How to get height of <div> in px dimension

Use .height() like this:

var result = $("#myDiv").height();

There's also .innerHeight() and .outerHeight() depending on exactly what you want.

You can test it here, play with the padding/margins/content to see how it changes around.

Storing C++ template function definitions in a .CPP file

There is, in the latest standard, a keyword (export) that would help alleviate this issue, but it isn't implemented in any compiler that I'm aware of, other than Comeau.

See the FAQ-lite about this.

How to compress an image via Javascript in the browser?

@PsychoWoods' answer is good. I would like to offer my own solution. This Javascript function takes an image data URL and a width, scales it to the new width, and returns a new data URL.

// Take an image URL, downscale it to the given width, and return a new image URL.
function downscaleImage(dataUrl, newWidth, imageType, imageArguments) {
    "use strict";
    var image, oldWidth, oldHeight, newHeight, canvas, ctx, newDataUrl;

    // Provide default values
    imageType = imageType || "image/jpeg";
    imageArguments = imageArguments || 0.7;

    // Create a temporary image so that we can compute the height of the downscaled image.
    image = new Image();
    image.src = dataUrl;
    oldWidth = image.width;
    oldHeight = image.height;
    newHeight = Math.floor(oldHeight / oldWidth * newWidth)

    // Create a temporary canvas to draw the downscaled image on.
    canvas = document.createElement("canvas");
    canvas.width = newWidth;
    canvas.height = newHeight;

    // Draw the downscaled image on the canvas and return the new data URL.
    ctx = canvas.getContext("2d");
    ctx.drawImage(image, 0, 0, newWidth, newHeight);
    newDataUrl = canvas.toDataURL(imageType, imageArguments);
    return newDataUrl;
}

This code can be used anywhere you have a data URL and want a data URL for a downscaled image.

Re-run Spring Boot Configuration Annotation Processor to update generated metadata

  1. Include a dependency on spring-boot-configuration-processor
  2. Click "Reimport All Maven Projects" in the Maven pane of IDEA
  3. Rebuild project

JavaScript alert box with timer

If you want an alert to appear after a certain about time, you can use this code:

setTimeout(function() { alert("my message"); }, time);

If you want an alert to appear and disappear after a specified interval has passed, then you're out of luck. When an alert has fired, the browser stops processing the javascript code until the user clicks "ok". This happens again when a confirm or prompt is shown.

If you want the appear/disappear behavior, then I would recommend using something like jQueryUI's dialog widget. Here's a quick example on how you might use it to achieve that behavior.

var dialog = $(foo).dialog('open');
setTimeout(function() { dialog.dialog('close'); }, time);

Can you install and run apps built on the .NET framework on a Mac?

You can use a .Net environment Visual studio, Take a look at the differences with the PC version.

A lighter editor would be Visual Code

Alternatives :

  1. Installing the Mono Project runtime . It allows you to re-compile the code and run it on a Mac, but this requires various alterations to the codebase, as the fuller .Net Framework is not available. (Also, WPF applications aren't supported here either.)

  2. Virtual machine (VMWare Fusion perhaps)

  3. Update your codebase to .Net Core, (before choosing this option take a look at this migration process)

    • .Net Core 3.1 is an open-source, free and available on Window, MacOs and Linux

    • As of September 14, a release candidate 1 of .Net Core 5.0 has been deployed on Window, MacOs and Linux.

[1] : Release candidate (RC) : releases providing early access to complete features. These releases are supported for production use when they have a go-live license

How can I set the max-width of a table cell using percentages?

Old question I know, but this is now possible using the css property table-layout: fixed on the table tag. Answer below from this question CSS percentage width and text-overflow in a table cell

This is easily done by using table-layout: fixed, but a little tricky because not many people know about this CSS property.

table {
  width: 100%;
  table-layout: fixed;
}

See it in action at the updated fiddle here: http://jsfiddle.net/Fm5bM/4/

How to style input and submit button with CSS?

form element UI is somewhat controlled by browser and operating system, so it is not trivial to style them very reliably in a way that it would look the same in all common browser/OS combinations.

Instead, if you want something specific, I would recommend to use a library that provides you stylable form elements. uniform.js is one such library.

Is there a free GUI management tool for Oracle Database Express?

you can always use the web based management tool that comes with oracle express db.. have tried using it? you can access it through http://host:port/apex if i remember correctly...

Alternative solutions are Oracle SQL Developer, TOAD etc...

Open Windows Explorer and select a file

Check out this snippet:

Private Sub openDialog()
    Dim fd As Office.FileDialog

    Set fd = Application.FileDialog(msoFileDialogFilePicker)

   With fd

      .AllowMultiSelect = False

      ' Set the title of the dialog box.
      .Title = "Please select the file."

      ' Clear out the current filters, and add our own.
      .Filters.Clear
      .Filters.Add "Excel 2003", "*.xls"
      .Filters.Add "All Files", "*.*"

      ' Show the dialog box. If the .Show method returns True, the
      ' user picked at least one file. If the .Show method returns
      ' False, the user clicked Cancel.
      If .Show = True Then
        txtFileName = .SelectedItems(1) 'replace txtFileName with your textbox

      End If
   End With
End Sub

I think this is what you are asking for.

Abstract methods in Java

Abstract methods means there is no default implementation for it and an implementing class will provide the details.

Essentially, you would have

abstract class AbstractObject {
   public abstract void method();
}

class ImplementingObject extends AbstractObject {
  public void method() {
    doSomething();
  }
}

So, it's exactly as the error states: your abstract method can not have a body.

There's a full tutorial on Oracle's site at: http://download.oracle.com/javase/tutorial/java/IandI/abstract.html

The reason you would do something like this is if multiple objects can share some behavior, but not all behavior.

A very simple example would be shapes:

You can have a generic graphic object, which knows how to reposition itself, but the implementing classes will actually draw themselves.

(This is taken from the site I linked above)

abstract class GraphicObject {
    int x, y;
    ...
    void moveTo(int newX, int newY) {
        ...
    }
    abstract void draw();
    abstract void resize();
}

class Circle extends GraphicObject {
    void draw() {
        ...
    }
    void resize() {
        ...
    }
}
class Rectangle extends GraphicObject {
    void draw() {
        ...
    }
    void resize() {
        ...
    }
}

How to add elements of a string array to a string array list?

Arrays.asList() method simply returns List type

char [] arr = { 'c','a','t'};    
ArrayList<Character> chars = new ArrayList<Character>();

To add the array into the list, first convert it to list and then call addAll

List arrList = Arrays.asList(arr);
chars.addAll(arrList);

The following line will cause compiler error

chars.addAll(Arrays.asList(arr));

How to compare two tags with git?

For a side-by-side visual representation, I use git difftool with openDiff set to the default viewer.

Example usage:

git difftool tags/<FIRST TAG> tags/<SECOND TAG>

If you are only interested in a specific file, you can use:

git difftool tags/<FIRST TAG>:<FILE PATH> tags/<SECOND TAG>:<FILE PATH>

As a side-note, the tags/<TAG>s can be replaced with <BRANCH>es if you are interested in diffing branches.

How can I create an array with key value pairs?

My PHP is a little rusty, but I believe you're looking for indexed assignment. Simply use:

$catList[$row["datasource_id"]] = $row["title"];

In PHP arrays are actually maps, where the keys can be either integers or strings. Check out PHP: Arrays - Manual for more information.

Disable all dialog boxes in Excel while running VB script?

From Excel Macro Security - www.excelfunctions.net:

Macro Security in Excel 2007, 2010 & 2013:

.....

The different Excel file types provided by the latest versions of Excel make it clear when workbook contains macros, so this in itself is a useful security measure. However, Excel also has optional macro security settings, which are controlled via the options menu. These are :

'Disable all macros without notification'

  • This setting does not allow any macros to run. When you open a new Excel workbook, you are not alerted to the fact that it contains macros, so you may not be aware that this is the reason a workbook does not work as expected.

'Disable all macros with notification'

  • This setting prevents macros from running. However, if there are macros in a workbook, a pop-up is displayed, to warn you that the macros exist and have been disabled.

'Disable all macros except digitally signed macros'

  • This setting only allow macros from trusted sources to run. All other macros do not run. When you open a new Excel workbook, you are not alerted to the fact that it contains macros, so you may not be aware that this is the reason a workbook does not work as expected.

'Enable all macros'

  • This setting allows all macros to run. When you open a new Excel workbook, you are not alerted to the fact that it contains macros and may not be aware of macros running while you have the file open.

If you trust the macros and are ok with enabling them, select this option:

'Enable all macros'

and this dialog box should not show up for macros.

As for the dialog for saving, after noting that this was running on Excel for Mac 2011, I came across the following question on SO, StackOverflow - Suppress dialog when using VBA to save a macro containing Excel file (.xlsm) as a non macro containing file (.xlsx). From it, removing the dialog does not seem to be possible, except for possibly by some Keyboard Input simulation. I would post another question to inquire about that. Sorry I could only get you halfway. The other option would be to use a Windows computer with Microsoft Excel, though I'm not sure if that is a option for you in this case.

Go test string contains substring

To compare, there are more options:

import (
    "fmt"
    "regexp"
    "strings"
)

const (
    str    = "something"
    substr = "some"
)

// 1. Contains
res := strings.Contains(str, substr)
fmt.Println(res) // true

// 2. Index: check the index of the first instance of substr in str, or -1 if substr is not present
i := strings.Index(str, substr)
fmt.Println(i) // 0

// 3. Split by substr and check len of the slice, or length is 1 if substr is not present
ss := strings.Split(str, substr)
fmt.Println(len(ss)) // 2

// 4. Check number of non-overlapping instances of substr in str
c := strings.Count(str, substr)
fmt.Println(c) // 1

// 5. RegExp
matched, _ := regexp.MatchString(substr, str)
fmt.Println(matched) // true

// 6. Compiled RegExp
re = regexp.MustCompile(substr)
res = re.MatchString(str)
fmt.Println(res) // true

Benchmarks: Contains internally calls Index, so the speed is almost the same (btw Go 1.11.5 showed a bit bigger difference than on Go 1.14.3).

BenchmarkStringsContains-4              100000000               10.5 ns/op             0 B/op          0 allocs/op
BenchmarkStringsIndex-4                 117090943               10.1 ns/op             0 B/op          0 allocs/op
BenchmarkStringsSplit-4                  6958126               152 ns/op              32 B/op          1 allocs/op
BenchmarkStringsCount-4                 42397729                29.1 ns/op             0 B/op          0 allocs/op
BenchmarkStringsRegExp-4                  461696              2467 ns/op            1326 B/op         16 allocs/op
BenchmarkStringsRegExpCompiled-4         7109509               168 ns/op               0 B/op          0 allocs/op

What is the difference between instanceof and Class.isAssignableFrom(...)?

Talking in terms of performance :

TL;DR

Use isInstance or instanceof which have similar performance. isAssignableFrom is slightly slower.

Sorted by performance:

  1. isInstance
  2. instanceof (+ 0.5%)
  3. isAssignableFrom (+ 2.7%)

Based on a benchmark of 2000 iterations on JAVA 8 Windows x64, with 20 warmup iterations.

In theory

Using a soft like bytecode viewer we can translate each operator into bytecode.

In the context of:

package foo;

public class Benchmark
{
  public static final Object a = new A();
  public static final Object b = new B();

  ...

}

JAVA:

b instanceof A;

Bytecode:

getstatic foo/Benchmark.b:java.lang.Object
instanceof foo/A

JAVA:

A.class.isInstance(b);

Bytecode:

ldc Lfoo/A; (org.objectweb.asm.Type)
getstatic foo/Benchmark.b:java.lang.Object
invokevirtual java/lang/Class isInstance((Ljava/lang/Object;)Z);

JAVA:

A.class.isAssignableFrom(b.getClass());

Bytecode:

ldc Lfoo/A; (org.objectweb.asm.Type)
getstatic foo/Benchmark.b:java.lang.Object
invokevirtual java/lang/Object getClass(()Ljava/lang/Class;);
invokevirtual java/lang/Class isAssignableFrom((Ljava/lang/Class;)Z);

Measuring how many bytecode instructions are used by each operator, we could expect instanceof and isInstance to be faster than isAssignableFrom. However, the actual performance is NOT determined by the bytecode but by the machine code (which is platform dependent). Let's do a micro benchmark for each of the operators.

The benchmark

Credit: As advised by @aleksandr-dubinsky, and thanks to @yura for providing the base code, here is a JMH benchmark (see this tuning guide):

class A {}
class B extends A {}

public class Benchmark {

    public static final Object a = new A();
    public static final Object b = new B();

    @Benchmark
    @BenchmarkMode(Mode.Throughput)
    @OutputTimeUnit(TimeUnit.MICROSECONDS)
    public boolean testInstanceOf()
    {
        return b instanceof A;
    }

    @Benchmark
    @BenchmarkMode(Mode.Throughput)
    @OutputTimeUnit(TimeUnit.MICROSECONDS)
    public boolean testIsInstance()
    {
        return A.class.isInstance(b);
    }

    @Benchmark
    @BenchmarkMode(Mode.Throughput)
    @OutputTimeUnit(TimeUnit.MICROSECONDS)
    public boolean testIsAssignableFrom()
    {
        return A.class.isAssignableFrom(b.getClass());
    }

    public static void main(String[] args) throws RunnerException {
        Options opt = new OptionsBuilder()
                .include(TestPerf2.class.getSimpleName())
                .warmupIterations(20)
                .measurementIterations(2000)
                .forks(1)
                .build();

        new Runner(opt).run();
    }
}

Gave the following results (score is a number of operations in a time unit, so the higher the score the better):

Benchmark                       Mode   Cnt    Score   Error   Units
Benchmark.testIsInstance        thrpt  2000  373,061 ± 0,115  ops/us
Benchmark.testInstanceOf        thrpt  2000  371,047 ± 0,131  ops/us
Benchmark.testIsAssignableFrom  thrpt  2000  363,648 ± 0,289  ops/us

Warning

  • the benchmark is JVM and platform dependent. Since there are no significant differences between each operation, it might be possible to get a different result (and maybe different order!) on a different JAVA version and/or platforms like Solaris, Mac or Linux.
  • the benchmark compares the performance of "is B an instance of A" when "B extends A" directly. If the class hierarchy is deeper and more complex (like B extends X which extends Y which extends Z which extends A), results might be different.
  • it is usually advised to write the code first picking one of the operators (the most convenient) and then profile your code to check if there are a performance bottleneck. Maybe this operator is negligible in the context of your code, or maybe...
  • in relation to the previous point, instanceof in the context of your code might get optimized more easily than an isInstance for example...

To give you an example, take the following loop:

class A{}
class B extends A{}

A b = new B();

boolean execute(){
  return A.class.isAssignableFrom(b.getClass());
  // return A.class.isInstance(b);
  // return b instanceof A;
}

// Warmup the code
for (int i = 0; i < 100; ++i)
  execute();

// Time it
int count = 100000;
final long start = System.nanoTime();
for(int i=0; i<count; i++){
   execute();
}
final long elapsed = System.nanoTime() - start;

Thanks to the JIT, the code is optimized at some point and we get:

  • instanceof: 6ms
  • isInstance: 12ms
  • isAssignableFrom : 15ms

Note

Originally this post was doing its own benchmark using a for loop in raw JAVA, which gave unreliable results as some optimization like Just In Time can eliminate the loop. So it was mostly measuring how long did the JIT compiler take to optimize the loop: see Performance test independent of the number of iterations for more details

Related questions

Difference between logical addresses, and physical addresses?

I found a article about Logical vs Physical Address in Operating System, which clearly explains about this.

Logical Address is generated by CPU while a program is running. The logical address is virtual address as it does not exist physically therefore it is also known as Virtual Address. This address is used as a reference to access the physical memory location by CPU. The term Logical Address Space is used for the set of all logical addresses generated by a programs perspective. The hardware device called Memory-Management Unit is used for mapping logical address to its corresponding physical address.

Physical Address identifies a physical location of required data in a memory. The user never directly deals with the physical address but can access by its corresponding logical address. The user program generates the logical address and thinks that the program is running in this logical address but the program needs physical memory for its execution therefore the logical address must be mapped to the physical address bu MMU before they are used. The term Physical Address Space is used for all physical addresses corresponding to the logical addresses in a Logical address space.

Logical and Physical Address comparision

Source: www.geeksforgeeks.org

input file appears to be a text format dump. Please use psql

The answer above didn't work for me, this worked:

psql db_development < postgres_db.dump

How to convert a unix timestamp (seconds since epoch) to Ruby DateTime?

One command to convert date time to Unix format and then to string

    DateTime.strptime(Time.now.utc.to_i.to_s,'%s').strftime("%d %m %y")

    Time.now.utc.to_i #Converts time from Unix format
    DateTime.strptime(Time.now.utc.to_i.to_s,'%s') #Converts date and time from unix format to DateTime

finally strftime is used to format date

Example:

    irb(main):034:0> DateTime.strptime("1410321600",'%s').strftime("%d %m %y")
    "10 09 14"

Python and pip, list all versions of a package that's available?

My take is a combination of a couple of posted answers, with some modifications to make them easier to use from within a running python environment.

The idea is to provide a entirely new command (modeled after the install command) that gives you an instance of the package finder to use. The upside is that it works with, and uses, any indexes that pip supports and reads your local pip configuration files, so you get the correct results as you would with a normal pip install.

I've made an attempt at making it compatible with both pip v 9.x and 10.x.. but only tried it on 9.x

https://gist.github.com/kaos/68511bd013fcdebe766c981f50b473d4

#!/usr/bin/env python
# When you want a easy way to get at all (or the latest) version of a certain python package from a PyPi index.

import sys
import logging

try:
    from pip._internal import cmdoptions, main
    from pip._internal.commands import commands_dict
    from pip._internal.basecommand import RequirementCommand
except ImportError:
    from pip import cmdoptions, main
    from pip.commands import commands_dict
    from pip.basecommand import RequirementCommand

from pip._vendor.packaging.version import parse as parse_version

logger = logging.getLogger('pip')

class ListPkgVersionsCommand(RequirementCommand):
    """
    List all available versions for a given package from:

    - PyPI (and other indexes) using requirement specifiers.
    - VCS project urls.
    - Local project directories.
    - Local or remote source archives.

    """
    name = "list-pkg-versions"
    usage = """
      %prog [options] <requirement specifier> [package-index-options] ...
      %prog [options] [-e] <vcs project url> ...
      %prog [options] [-e] <local project path> ...
      %prog [options] <archive url/path> ..."""

    summary = 'List package versions.'

    def __init__(self, *args, **kw):
        super(ListPkgVersionsCommand, self).__init__(*args, **kw)

        cmd_opts = self.cmd_opts

        cmd_opts.add_option(cmdoptions.install_options())
        cmd_opts.add_option(cmdoptions.global_options())
        cmd_opts.add_option(cmdoptions.use_wheel())
        cmd_opts.add_option(cmdoptions.no_use_wheel())
        cmd_opts.add_option(cmdoptions.no_binary())
        cmd_opts.add_option(cmdoptions.only_binary())
        cmd_opts.add_option(cmdoptions.pre())
        cmd_opts.add_option(cmdoptions.require_hashes())

        index_opts = cmdoptions.make_option_group(
            cmdoptions.index_group,
            self.parser,
        )

        self.parser.insert_option_group(0, index_opts)
        self.parser.insert_option_group(0, cmd_opts)

    def run(self, options, args):
        cmdoptions.resolve_wheel_no_use_binary(options)
        cmdoptions.check_install_build_global(options)

        with self._build_session(options) as session:
            finder = self._build_package_finder(options, session)

            # do what you please with the finder object here... ;)
            for pkg in args:
                logger.info(
                    '%s: %s', pkg,
                    ', '.join(
                        sorted(
                            set(str(c.version) for c in finder.find_all_candidates(pkg)),
                            key=parse_version,
                        )
                    )
                )


commands_dict[ListPkgVersionsCommand.name] = ListPkgVersionsCommand

if __name__ == '__main__':
    sys.exit(main())

Example output

./list-pkg-versions.py list-pkg-versions pika django
pika: 0.5, 0.5.1, 0.5.2, 0.9.1a0, 0.9.2a0, 0.9.3, 0.9.4, 0.9.5, 0.9.6, 0.9.7, 0.9.8, 0.9.9, 0.9.10, 0.9.11, 0.9.12, 0.9.13, 0.9.14, 0.10.0b1, 0.10.0b2, 0.10.0, 0.11.0b1, 0.11.0, 0.11.1, 0.11.2, 0.12.0b2
django: 1.1.3, 1.1.4, 1.2, 1.2.1, 1.2.2, 1.2.3, 1.2.4, 1.2.5, 1.2.6, 1.2.7, 1.3, 1.3.1, 1.3.2, 1.3.3, 1.3.4, 1.3.5, 1.3.6, 1.3.7, 1.4, 1.4.1, 1.4.2, 1.4.3, 1.4.4, 1.4.5, 1.4.6, 1.4.7, 1.4.8, 1.4.9, 1.4.10, 1.4.11, 1.4.12, 1.4.13, 1.4.14, 1.4.15, 1.4.16, 1.4.17, 1.4.18, 1.4.19, 1.4.20, 1.4.21, 1.4.22, 1.5, 1.5.1, 1.5.2, 1.5.3, 1.5.4, 1.5.5, 1.5.6, 1.5.7, 1.5.8, 1.5.9, 1.5.10, 1.5.11, 1.5.12, 1.6, 1.6.1, 1.6.2, 1.6.3, 1.6.4, 1.6.5, 1.6.6, 1.6.7, 1.6.8, 1.6.9, 1.6.10, 1.6.11, 1.7, 1.7.1, 1.7.2, 1.7.3, 1.7.4, 1.7.5, 1.7.6, 1.7.7, 1.7.8, 1.7.9, 1.7.10, 1.7.11, 1.8a1, 1.8b1, 1.8b2, 1.8rc1, 1.8, 1.8.1, 1.8.2, 1.8.3, 1.8.4, 1.8.5, 1.8.6, 1.8.7, 1.8.8, 1.8.9, 1.8.10, 1.8.11, 1.8.12, 1.8.13, 1.8.14, 1.8.15, 1.8.16, 1.8.17, 1.8.18, 1.8.19, 1.9a1, 1.9b1, 1.9rc1, 1.9rc2, 1.9, 1.9.1, 1.9.2, 1.9.3, 1.9.4, 1.9.5, 1.9.6, 1.9.7, 1.9.8, 1.9.9, 1.9.10, 1.9.11, 1.9.12, 1.9.13, 1.10a1, 1.10b1, 1.10rc1, 1.10, 1.10.1, 1.10.2, 1.10.3, 1.10.4, 1.10.5, 1.10.6, 1.10.7, 1.10.8, 1.11a1, 1.11b1, 1.11rc1, 1.11, 1.11.1, 1.11.2, 1.11.3, 1.11.4, 1.11.5, 1.11.6, 1.11.7, 1.11.8, 1.11.9, 1.11.10, 1.11.11, 1.11.12, 2.0, 2.0.1, 2.0.2, 2.0.3, 2.0.4

C# "must declare a body because it is not marked abstract, extern, or partial"

You need to either provide a body for both the getter and setter, or neither. Since you have non-trivial logic in your setter, you need a manually-implemented getter like so:

get { return _hour; }

If you decide you don't need the logic in the setter, you could go with an automatically-implemented property like so:

public int Hour { get; set; }

How do I call a dynamically-named method in Javascript?

Try These

Call Functions With Dynamic Names, like this:

let dynamic_func_name = 'alert';
(new Function(dynamic_func_name+'()'))()

with parameters:

let dynamic_func_name = 'alert';
let para_1 = 'HAHAHA';
let para_2 = 'ABCD';
(new Function(`${dynamic_func_name}('${para_1}','${para_2}')`))()

Run Dynamic Code:

let some_code = "alert('hahaha');";
(new Function(some_code))()

How to debug Lock wait timeout exceeded on MySQL?

The big problem with this exception is that its usually not reproducible in a test environment and we are not around to run innodb engine status when it happens on prod. So in one of the projects I put the below code into a catch block for this exception. That helped me catch the engine status when the exception happened. That helped a lot.

Statement st = con.createStatement();
ResultSet rs =  st.executeQuery("SHOW ENGINE INNODB STATUS");
while(rs.next()){
    log.info(rs.getString(1));
    log.info(rs.getString(2));
    log.info(rs.getString(3));
}

How to set ANDROID_HOME path in ubuntu?

sudo su -
gedit ~/.bashrc
export PATH=${PATH}:/your path
export PATH=${PATH}:/your path
export PATH=${PATH}:/opt/workspace/android/android-sdk-linux/tools
export PATH=${PATH}:/opt/workspace/android/android-sdk-linux/platform-tools

What's the point of the X-Requested-With header?

Make sure you read SilverlightFox's answer. It highlights a more important reason.

The reason is mostly that if you know the source of a request you may want to customize it a little bit.

For instance lets say you have a website which has many recipes. And you use a custom jQuery framework to slide recipes into a container based on a link they click. The link may be www.example.com/recipe/apple_pie

Now normally that returns a full page, header, footer, recipe content and ads. But if someone is browsing your website some of those parts are already loaded. So you can use an AJAX to get the recipe the user has selected but to save time and bandwidth don't load the header/footer/ads.

Now you can just write a secondary endpoint for the data like www.example.com/recipe_only/apple_pie but that's harder to maintain and share to other people.

But it's easier to just detect that it is an ajax request making the request and then returning only a part of the data. That way the user wastes less bandwidth and the site appears more responsive.

The frameworks just add the header because some may find it useful to keep track of which requests are ajax and which are not. But it's entirely dependent on the developer to use such techniques.

It's actually kind of similar to the Accept-Language header. A browser can request a website please show me a Russian version of this website without having to insert /ru/ or similar in the URL.

What's the difference between a temp table and table variable in SQL Server?

Just looking at the claim in the accepted answer that table variables don't participate in logging.

It seems generally untrue that there is any difference in quantity of logging (at least for insert/update/delete operations to the table itself though I have since found that there is some small difference in this respect for cached temporary objects in stored procedures due to additional system table updates).

I looked at the logging behaviour against both a @table_variable and a #temp table for the following operations.

  1. Successful Insert
  2. Multi Row Insert where statement rolled back due to constraint violation.
  3. Update
  4. Delete
  5. Deallocate

The transaction log records were almost identical for all operations.

The table variable version actually has a few extra log entries because it gets an entry added to (and later removed from) the sys.syssingleobjrefs base table but overall had a few less bytes logged purely as the internal name for table variables consumes 236 less bytes than for #temp tables (118 fewer nvarchar characters).

Full script to reproduce (best run on an instance started in single user mode and using sqlcmd mode)

:setvar tablename "@T" 
:setvar tablescript "DECLARE @T TABLE"

/*
 --Uncomment this section to test a #temp table
:setvar tablename "#T" 
:setvar tablescript "CREATE TABLE #T"
*/

USE tempdb 
GO    
CHECKPOINT

DECLARE @LSN NVARCHAR(25)

SELECT @LSN = MAX([Current LSN])
FROM fn_dblog(null, null) 


EXEC(N'BEGIN TRAN StartBatch
SAVE TRAN StartBatch
COMMIT

$(tablescript)
(
[4CA996AC-C7E1-48B5-B48A-E721E7A435F0] INT PRIMARY KEY DEFAULT 0,
InRowFiller char(7000) DEFAULT ''A'',
OffRowFiller varchar(8000) DEFAULT REPLICATE(''B'',8000),
LOBFiller varchar(max) DEFAULT REPLICATE(cast(''C'' as varchar(max)),10000)
)


BEGIN TRAN InsertFirstRow
SAVE TRAN InsertFirstRow
COMMIT

INSERT INTO $(tablename)
DEFAULT VALUES

BEGIN TRAN Insert9Rows
SAVE TRAN Insert9Rows
COMMIT


INSERT INTO $(tablename) ([4CA996AC-C7E1-48B5-B48A-E721E7A435F0])
SELECT TOP 9 ROW_NUMBER() OVER (ORDER BY (SELECT 0))
FROM sys.all_columns

BEGIN TRAN InsertFailure
SAVE TRAN InsertFailure
COMMIT


/*Try and Insert 10 rows, the 10th one will cause a constraint violation*/
BEGIN TRY
INSERT INTO $(tablename) ([4CA996AC-C7E1-48B5-B48A-E721E7A435F0])
SELECT TOP (10) (10 + ROW_NUMBER() OVER (ORDER BY (SELECT 0))) % 20
FROM sys.all_columns
END TRY
BEGIN CATCH
PRINT ERROR_MESSAGE()
END CATCH

BEGIN TRAN Update10Rows
SAVE TRAN Update10Rows
COMMIT

UPDATE $(tablename)
SET InRowFiller = LOWER(InRowFiller),
    OffRowFiller  =LOWER(OffRowFiller),
    LOBFiller  =LOWER(LOBFiller)


BEGIN TRAN Delete10Rows
SAVE TRAN Delete10Rows
COMMIT

DELETE FROM  $(tablename)
BEGIN TRAN AfterDelete
SAVE TRAN AfterDelete
COMMIT

BEGIN TRAN EndBatch
SAVE TRAN EndBatch
COMMIT')


DECLARE @LSN_HEX NVARCHAR(25) = 
        CAST(CAST(CONVERT(varbinary,SUBSTRING(@LSN, 1, 8),2) AS INT) AS VARCHAR) + ':' +
        CAST(CAST(CONVERT(varbinary,SUBSTRING(@LSN, 10, 8),2) AS INT) AS VARCHAR) + ':' +
        CAST(CAST(CONVERT(varbinary,SUBSTRING(@LSN, 19, 4),2) AS INT) AS VARCHAR)        

SELECT 
    [Operation],
    [Context],
    [AllocUnitName],
    [Transaction Name],
    [Description]
FROM   fn_dblog(@LSN_HEX, null) AS D
WHERE  [Current LSN] > @LSN  

SELECT CASE
         WHEN GROUPING(Operation) = 1 THEN 'Total'
         ELSE Operation
       END AS Operation,
       Context,
       AllocUnitName,
       COALESCE(SUM([Log Record Length]), 0) AS [Size in Bytes],
       COUNT(*)                              AS Cnt
FROM   fn_dblog(@LSN_HEX, null) AS D
WHERE  [Current LSN] > @LSN  
GROUP BY GROUPING SETS((Operation, Context, AllocUnitName),())

Results

+-----------------------+--------------------+---------------------------+---------------+------+---------------+------+------------------+
|                       |                    |                           |             @TV      |             #TV      |                  |
+-----------------------+--------------------+---------------------------+---------------+------+---------------+------+------------------+
| Operation             | Context            | AllocUnitName             | Size in Bytes | Cnt  | Size in Bytes | Cnt  | Difference Bytes |
+-----------------------+--------------------+---------------------------+---------------+------+---------------+------+------------------+
| LOP_ABORT_XACT        | LCX_NULL           |                           | 52            | 1    | 52            | 1    |                  |
| LOP_BEGIN_XACT        | LCX_NULL           |                           | 6056          | 50   | 6056          | 50   |                  |
| LOP_COMMIT_XACT       | LCX_NULL           |                           | 2548          | 49   | 2548          | 49   |                  |
| LOP_COUNT_DELTA       | LCX_CLUSTERED      | sys.sysallocunits.clust   | 624           | 3    | 624           | 3    |                  |
| LOP_COUNT_DELTA       | LCX_CLUSTERED      | sys.sysrowsets.clust      | 208           | 1    | 208           | 1    |                  |
| LOP_COUNT_DELTA       | LCX_CLUSTERED      | sys.sysrscols.clst        | 832           | 4    | 832           | 4    |                  |
| LOP_CREATE_ALLOCCHAIN | LCX_NULL           |                           | 120           | 3    | 120           | 3    |                  |
| LOP_DELETE_ROWS       | LCX_INDEX_INTERIOR | Unknown Alloc Unit        | 720           | 9    | 720           | 9    |                  |
| LOP_DELETE_ROWS       | LCX_MARK_AS_GHOST  | sys.sysallocunits.clust   | 444           | 3    | 444           | 3    |                  |
| LOP_DELETE_ROWS       | LCX_MARK_AS_GHOST  | sys.sysallocunits.nc      | 276           | 3    | 276           | 3    |                  |
| LOP_DELETE_ROWS       | LCX_MARK_AS_GHOST  | sys.syscolpars.clst       | 628           | 4    | 628           | 4    |                  |
| LOP_DELETE_ROWS       | LCX_MARK_AS_GHOST  | sys.syscolpars.nc         | 484           | 4    | 484           | 4    |                  |
| LOP_DELETE_ROWS       | LCX_MARK_AS_GHOST  | sys.sysidxstats.clst      | 176           | 1    | 176           | 1    |                  |
| LOP_DELETE_ROWS       | LCX_MARK_AS_GHOST  | sys.sysidxstats.nc        | 144           | 1    | 144           | 1    |                  |
| LOP_DELETE_ROWS       | LCX_MARK_AS_GHOST  | sys.sysiscols.clst        | 100           | 1    | 100           | 1    |                  |
| LOP_DELETE_ROWS       | LCX_MARK_AS_GHOST  | sys.sysiscols.nc1         | 88            | 1    | 88            | 1    |                  |
| LOP_DELETE_ROWS       | LCX_MARK_AS_GHOST  | sys.sysobjvalues.clst     | 596           | 5    | 596           | 5    |                  |
| LOP_DELETE_ROWS       | LCX_MARK_AS_GHOST  | sys.sysrowsets.clust      | 132           | 1    | 132           | 1    |                  |
| LOP_DELETE_ROWS       | LCX_MARK_AS_GHOST  | sys.sysrscols.clst        | 528           | 4    | 528           | 4    |                  |
| LOP_DELETE_ROWS       | LCX_MARK_AS_GHOST  | sys.sysschobjs.clst       | 1040          | 6    | 1276          | 6    | 236              |
| LOP_DELETE_ROWS       | LCX_MARK_AS_GHOST  | sys.sysschobjs.nc1        | 820           | 6    | 1060          | 6    | 240              |
| LOP_DELETE_ROWS       | LCX_MARK_AS_GHOST  | sys.sysschobjs.nc2        | 820           | 6    | 1060          | 6    | 240              |
| LOP_DELETE_ROWS       | LCX_MARK_AS_GHOST  | sys.sysschobjs.nc3        | 480           | 6    | 480           | 6    |                  |
| LOP_DELETE_ROWS       | LCX_MARK_AS_GHOST  | sys.syssingleobjrefs.clst | 96            | 1    |               |      | -96              |
| LOP_DELETE_ROWS       | LCX_MARK_AS_GHOST  | sys.syssingleobjrefs.nc1  | 88            | 1    |               |      | -88              |
| LOP_DELETE_ROWS       | LCX_MARK_AS_GHOST  | Unknown Alloc Unit        | 72092         | 19   | 72092         | 19   |                  |
| LOP_DELETE_ROWS       | LCX_TEXT_MIX       | Unknown Alloc Unit        | 16348         | 37   | 16348         | 37   |                  |
| LOP_FORMAT_PAGE       | LCX_HEAP           | Unknown Alloc Unit        | 1596          | 19   | 1596          | 19   |                  |
| LOP_FORMAT_PAGE       | LCX_IAM            | Unknown Alloc Unit        | 252           | 3    | 252           | 3    |                  |
| LOP_FORMAT_PAGE       | LCX_INDEX_INTERIOR | Unknown Alloc Unit        | 84            | 1    | 84            | 1    |                  |
| LOP_FORMAT_PAGE       | LCX_TEXT_MIX       | Unknown Alloc Unit        | 4788          | 57   | 4788          | 57   |                  |
| LOP_HOBT_DDL          | LCX_NULL           |                           | 108           | 3    | 108           | 3    |                  |
| LOP_HOBT_DELTA        | LCX_NULL           |                           | 9600          | 150  | 9600          | 150  |                  |
| LOP_INSERT_ROWS       | LCX_CLUSTERED      | sys.sysallocunits.clust   | 456           | 3    | 456           | 3    |                  |
| LOP_INSERT_ROWS       | LCX_CLUSTERED      | sys.syscolpars.clst       | 644           | 4    | 644           | 4    |                  |
| LOP_INSERT_ROWS       | LCX_CLUSTERED      | sys.sysidxstats.clst      | 180           | 1    | 180           | 1    |                  |
| LOP_INSERT_ROWS       | LCX_CLUSTERED      | sys.sysiscols.clst        | 104           | 1    | 104           | 1    |                  |
| LOP_INSERT_ROWS       | LCX_CLUSTERED      | sys.sysobjvalues.clst     | 616           | 5    | 616           | 5    |                  |
| LOP_INSERT_ROWS       | LCX_CLUSTERED      | sys.sysrowsets.clust      | 136           | 1    | 136           | 1    |                  |
| LOP_INSERT_ROWS       | LCX_CLUSTERED      | sys.sysrscols.clst        | 544           | 4    | 544           | 4    |                  |
| LOP_INSERT_ROWS       | LCX_CLUSTERED      | sys.sysschobjs.clst       | 1064          | 6    | 1300          | 6    | 236              |
| LOP_INSERT_ROWS       | LCX_CLUSTERED      | sys.syssingleobjrefs.clst | 100           | 1    |               |      | -100             |
| LOP_INSERT_ROWS       | LCX_CLUSTERED      | Unknown Alloc Unit        | 135888        | 19   | 135888        | 19   |                  |
| LOP_INSERT_ROWS       | LCX_INDEX_INTERIOR | Unknown Alloc Unit        | 1596          | 19   | 1596          | 19   |                  |
| LOP_INSERT_ROWS       | LCX_INDEX_LEAF     | sys.sysallocunits.nc      | 288           | 3    | 288           | 3    |                  |
| LOP_INSERT_ROWS       | LCX_INDEX_LEAF     | sys.syscolpars.nc         | 500           | 4    | 500           | 4    |                  |
| LOP_INSERT_ROWS       | LCX_INDEX_LEAF     | sys.sysidxstats.nc        | 148           | 1    | 148           | 1    |                  |
| LOP_INSERT_ROWS       | LCX_INDEX_LEAF     | sys.sysiscols.nc1         | 92            | 1    | 92            | 1    |                  |
| LOP_INSERT_ROWS       | LCX_INDEX_LEAF     | sys.sysschobjs.nc1        | 844           | 6    | 1084          | 6    | 240              |
| LOP_INSERT_ROWS       | LCX_INDEX_LEAF     | sys.sysschobjs.nc2        | 844           | 6    | 1084          | 6    | 240              |
| LOP_INSERT_ROWS       | LCX_INDEX_LEAF     | sys.sysschobjs.nc3        | 504           | 6    | 504           | 6    |                  |
| LOP_INSERT_ROWS       | LCX_INDEX_LEAF     | sys.syssingleobjrefs.nc1  | 92            | 1    |               |      | -92              |
| LOP_INSERT_ROWS       | LCX_TEXT_MIX       | Unknown Alloc Unit        | 5112          | 71   | 5112          | 71   |                  |
| LOP_MARK_SAVEPOINT    | LCX_NULL           |                           | 508           | 8    | 508           | 8    |                  |
| LOP_MODIFY_COLUMNS    | LCX_CLUSTERED      | Unknown Alloc Unit        | 1560          | 10   | 1560          | 10   |                  |
| LOP_MODIFY_HEADER     | LCX_HEAP           | Unknown Alloc Unit        | 3780          | 45   | 3780          | 45   |                  |
| LOP_MODIFY_ROW        | LCX_CLUSTERED      | sys.syscolpars.clst       | 384           | 4    | 384           | 4    |                  |
| LOP_MODIFY_ROW        | LCX_CLUSTERED      | sys.sysidxstats.clst      | 100           | 1    | 100           | 1    |                  |
| LOP_MODIFY_ROW        | LCX_CLUSTERED      | sys.sysrowsets.clust      | 92            | 1    | 92            | 1    |                  |
| LOP_MODIFY_ROW        | LCX_CLUSTERED      | sys.sysschobjs.clst       | 1144          | 13   | 1144          | 13   |                  |
| LOP_MODIFY_ROW        | LCX_IAM            | Unknown Alloc Unit        | 4224          | 48   | 4224          | 48   |                  |
| LOP_MODIFY_ROW        | LCX_PFS            | Unknown Alloc Unit        | 13632         | 169  | 13632         | 169  |                  |
| LOP_MODIFY_ROW        | LCX_TEXT_MIX       | Unknown Alloc Unit        | 108640        | 120  | 108640        | 120  |                  |
| LOP_ROOT_CHANGE       | LCX_CLUSTERED      | sys.sysallocunits.clust   | 960           | 10   | 960           | 10   |                  |
| LOP_SET_BITS          | LCX_GAM            | Unknown Alloc Unit        | 1200          | 20   | 1200          | 20   |                  |
| LOP_SET_BITS          | LCX_IAM            | Unknown Alloc Unit        | 1080          | 18   | 1080          | 18   |                  |
| LOP_SET_BITS          | LCX_SGAM           | Unknown Alloc Unit        | 120           | 2    | 120           | 2    |                  |
| LOP_SHRINK_NOOP       | LCX_NULL           |                           |               |      | 32            | 1    | 32               |
+-----------------------+--------------------+---------------------------+---------------+------+---------------+------+------------------+
| Total                 |                    |                           | 410144        | 1095 | 411232        | 1092 | 1088             |
+-----------------------+--------------------+---------------------------+---------------+------+---------------+------+------------------+

Are lists thread-safe?

Lists themselves are thread-safe. In CPython the GIL protects against concurrent accesses to them, and other implementations take care to use a fine-grained lock or a synchronized datatype for their list implementations. However, while lists themselves can't go corrupt by attempts to concurrently access, the lists's data is not protected. For example:

L[0] += 1

is not guaranteed to actually increase L[0] by one if another thread does the same thing, because += is not an atomic operation. (Very, very few operations in Python are actually atomic, because most of them can cause arbitrary Python code to be called.) You should use Queues because if you just use an unprotected list, you may get or delete the wrong item because of race conditions.

Adding items to a JComboBox

You can use String arrays to add jComboBox items

String [] items = { "First item", "Second item", "Third item", "Fourth item" };

JComboBox comboOne = new JComboBox (items);

Bash scripting, multiple conditions in while loop

The correct options are (in increasing order of recommendation):

# Single POSIX test command with -o operator (not recommended anymore).
# Quotes strongly recommended to guard against empty or undefined variables.
while [ "$stats" -gt 300 -o "$stats" -eq 0 ]

# Two POSIX test commands joined in a list with ||.
# Quotes strongly recommended to guard against empty or undefined variables.
while [ "$stats" -gt 300 ] || [ "$stats" -eq 0 ]

# Two bash conditional expressions joined in a list with ||.
while [[ $stats -gt 300 ]] || [[ $stats -eq 0 ]]

# A single bash conditional expression with the || operator.
while [[ $stats -gt 300 || $stats -eq 0 ]]

# Two bash arithmetic expressions joined in a list with ||.
# $ optional, as a string can only be interpreted as a variable
while (( stats > 300 )) || (( stats == 0 ))

# And finally, a single bash arithmetic expression with the || operator.
# $ optional, as a string can only be interpreted as a variable
while (( stats > 300 || stats == 0 ))

Some notes:

  1. Quoting the parameter expansions inside [[ ... ]] and ((...)) is optional; if the variable is not set, -gt and -eq will assume a value of 0.

  2. Using $ is optional inside (( ... )), but using it can help avoid unintentional errors. If stats isn't set, then (( stats > 300 )) will assume stats == 0, but (( $stats > 300 )) will produce a syntax error.

Are there any Java method ordering conventions?

Are you using Eclipse? If so I would stick with the default member sort order, because that is likely to be most familiar to whoever reads your code (although it is not my favourite sort order.)

How to disassemble a binary executable in Linux to get the assembly code?

ht editor can disassemble binaries in many formats. It is similar to Hiew, but open source.

To disassemble, open a binary, then press F6 and then select elf/image.

php REQUEST_URI

Since vars passed through url are $_GET vars, you can use filter_input() function:

$id = filter_input(INPUT_GET, 'id', FILTER_SANITIZE_NUMBER_INT);
$othervar = filter_input(INPUT_GET, 'othervar', FILTER_SANITIZE_FULL_SPECIAL_CHARS);

It would store the values of each var and sanitize/validate them too.

How to Ping External IP from Java Android

This is a simple ping I use in one of the projects:

public static class Ping {
    public String net = "NO_CONNECTION";
    public String host = "";
    public String ip = "";
    public int dns = Integer.MAX_VALUE;
    public int cnt = Integer.MAX_VALUE;
}

public static Ping ping(URL url, Context ctx) {
    Ping r = new Ping();
    if (isNetworkConnected(ctx)) {
        r.net = getNetworkType(ctx);
        try {
            String hostAddress;
            long start = System.currentTimeMillis();
            hostAddress = InetAddress.getByName(url.getHost()).getHostAddress();
            long dnsResolved = System.currentTimeMillis();
            Socket socket = new Socket(hostAddress, url.getPort());
            socket.close();
            long probeFinish = System.currentTimeMillis();
            r.dns = (int) (dnsResolved - start);
            r.cnt = (int) (probeFinish - dnsResolved);
            r.host = url.getHost();
            r.ip = hostAddress;
        }
        catch (Exception ex) {
            Timber.e("Unable to ping");
        }
    }
    return r;
}

public static boolean isNetworkConnected(Context context) {
    ConnectivityManager cm =
            (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
    return activeNetwork != null && activeNetwork.isConnectedOrConnecting();
}

@Nullable
public static String getNetworkType(Context context) {
    ConnectivityManager cm =
            (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
    if (activeNetwork != null) {
        return activeNetwork.getTypeName();
    }
    return null;
}

Usage: ping(new URL("https://www.google.com:443/"), this);

Result: {"cnt":100,"dns":109,"host":"www.google.com","ip":"212.188.10.114","net":"WIFI"}

How to create a byte array in C++?

Byte is not a standard type in C or C++. Try char, which is usually and at least 8 bits long.

White space showing up on right side of page when background image should extend full length of page

Debug your CSS for Ghost CSS Elements.

Use this bookmark to debug your CSS: https://blog.wernull.com/2013/04/debug-ghost-css-elements-causing-unwanted-scrolling/

Or add the CSS directly yourself:

* {
  background: #000 !important;
  color: #0f0 !important;
  outline: solid #f00 1px !important;
}

In my case a Facebook Like Button caused the problem.

Could not load file or assembly 'Microsoft.ReportViewer.WebForms'

This link gave me a clue that I didn't install a required update (my problemed concerned version nr, v11.0.0.0)

ReportViewer 2012 Update 'Gotcha' to be aware of

I installed the update SQLServer2008R2SP2

I downloaded ReportViewer.msi, which required to have installed Microsoft® System CLR Types for Microsoft® SQL Server® 2012 (look halfway down the page for installer)

In the GAC was now available WebForms v11.0.0.0 (C:\Windows\assembly\Microsoft.ReportViewer.WebForms v11.0.0.0 as well as Microsoft.ReportViewer.Common v11.0.0.0)

RegEx to parse or validate Base64 data

The best regexp which I could find up till now is in here https://www.npmjs.com/package/base64-regex

which is in the current version looks like:

module.exports = function (opts) {
  opts = opts || {};
  var regex = '(?:[A-Za-z0-9+\/]{4}\\n?)*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)';

  return opts.exact ? new RegExp('(?:^' + regex + '$)') :
                    new RegExp('(?:^|\\s)' + regex, 'g');
};

How to execute raw SQL in Flask-SQLAlchemy app

If you want to avoid tuples, another way is by calling the first, one or all methods:

query = db.engine.execute("SELECT * FROM blogs "
                           "WHERE id = 1 ")

assert query.first().name == "Welcome to my blog"

Draw a curve with css

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

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

Why do I need to configure the SQL dialect of a data source?

Dialect is the SQL dialect that your database uses.

List of SQL dialects for Hibernate.

Either provide it in hibernate.cfg.xml as :

<hibernate-configuration>
   <session-factory name="session-factory">
      <property name="hibernate.dialect">org.hibernate.dialect.SQLServerDialect</property>
       ...
   </session-factory>
</hibernate-configuration>

or in the properties file as :

hibernate.dialect=org.hibernate.dialect.SQLServerDialect

Is there a "null coalescing" operator in JavaScript?

After reading your clarification, @Ates Goral's answer provides how to perform the same operation you're doing in C# in JavaScript.

@Gumbo's answer provides the best way to check for null; however, it's important to note the difference in == versus === in JavaScript especially when it comes to issues of checking for undefined and/or null.

There's a really good article about the difference in two terms here. Basically, understand that if you use == instead of ===, JavaScript will try to coalesce the values you're comparing and return what the result of the comparison after this coalescence.

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

Vue allows for you to specify a default prop value and type directly, by making props an object (see: https://vuejs.org/guide/components.html#Prop-Validation):

props: {
  year: {
    default: 2016,
    type: Number
  }
}

If the wrong type is passed then it throws an error and logs it in the console, here's the fiddle:

https://jsfiddle.net/cexbqe2q/

jQuery hyperlinks - href value?

I almost had this problem and it was very deceiving. I am providing an answer in case someone winds up in my same position.

  1. I thought I had this problem
  2. But, I was using return false and javascript:void(0);
  3. Then a distinct difference in problem kept surfacing:
  4. I realized it's not going ALL the way to the top - and my problem zone was near the bottom of the page so this jump was strange and annoying.
  5. I realized I was using fadeIn() [jQuery library], which for a short time my content was display:none
  6. And then my content extended the reach of the page! Causing what looks like a jump!
  7. Using visibility hidden toggles now..

Hope this helps the person stuck with jumps!!

Is it better to use path() or url() in urls.py for django 2.0?

path is simply new in Django 2.0, which was only released a couple of weeks ago. Most tutorials won't have been updated for the new syntax.

It was certainly supposed to be a simpler way of doing things; I wouldn't say that URL is more powerful though, you should be able to express patterns in either format.

VB.NET Inputbox - How to identify when the Cancel Button is pressed?

Here is what I did and it worked perfectly for what I was looking to do:

Dim StatusDate As String
 StatusDate = InputBox("What status date do you want to pull?", "Enter Status Date", " ")

        If StatusDate = " " Then
            MessageBox.Show("You must enter a Status date to continue.")
            Exit Sub
        ElseIf StatusDate = "" Then
            Exit Sub
        End If

This key was to set the default value of the input box to be an actual space, so a user pressing just the OK button would return a value of " " while pressing cancel returns ""

From a usability standpoint, the defaulted value in the input box starts highlighted and is cleared when a user types so the experience is no different than if the box had no value.

CSS way to horizontally align table

Simple. IE6 and above will happily center your table with "margin: 0 auto;" if only the page renders in "standards" mode. To make this happen you need a valid doctype declaration, such as

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">

or

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

True, IE5.5 and below will still refuse to center the table but perhaps you can live with that, especially if the page is still functional with the table left aligned. I think by now users of IE5.5 and below are fairly used to some odd looking websites - but you still need to ensure that those visual glitches don't render your site unusable.

Happy coding!

EDIT: Sorry, I should perhaps point out that you do not have to have a "strict" doctype to get IE6 and up into "standards" rendering mode. I realised it might seem that way from the doctype examples I posted above. For example, this doctype declaration will of course work equally:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

HTTP vs HTTPS performance

I can tell you (as a dialup user) that the same page over SSL is several times slower than via regular HTTP...

How to get a variable value if variable name is stored as string?

Modified my search keywords and Got it :).

eval a=\$$a
Thanks for your time.

Why cannot change checkbox color whatever I do?

I also had this problem. I use chrome to code because I'm currently a newbie. I was able to change the colour of the checkboxes and radio selectors when they were checked ONLY using CSS. The current degree that is set in the hue-rotate() turns the blue checks red. I first used the grayscale(1) with the filter: but you don't need it. However, if you just want plain flat gray, go for the grayscale value for filter.

I've ONLY tested this in Chrome but it works with just plain old HTML and CSS, let me know in the comments section if it works in other browsers.

_x000D_
_x000D_
input[type="checkbox"],
input[type="radio"] {
  filter: hue-rotate(140deg);
  }
_x000D_
<body>
  <label for="radio1">Eau de Toilette</label>
  <input type="radio" id="radio1" name="example1"><br>
  <label for="radio2">Eau de Parfum</label>
  <input type="radio" id="radio2" name="example1"><br>
  <label for="check1">Orange Zest</label>
  <input type="checkbox" id="check1" name="example2"><br>
  <label for="check2">Lemons</label>
  <input type="checkbox" id="check2" name="example2"><br>
 </body>
_x000D_
_x000D_
_x000D_

How do I pass multiple attributes into an Angular.js attribute directive?

The directive can access any attribute that is defined on the same element, even if the directive itself is not the element.

Template:

<div example-directive example-number="99" example-function="exampleCallback()"></div>

Directive:

app.directive('exampleDirective ', function () {
    return {
        restrict: 'A',   // 'A' is the default, so you could remove this line
        scope: {
            callback : '&exampleFunction',
        },
        link: function (scope, element, attrs) {
            var num = scope.$eval(attrs.exampleNumber);
            console.log('number=',num);
            scope.callback();  // calls exampleCallback()
        }
    };
});

fiddle

If the value of attribute example-number will be hard-coded, I suggest using $eval once, and storing the value. Variable num will have the correct type (a number).

Enable ASP.NET ASMX web service for HTTP POST / GET requests

Actually, I found a somewhat quirky way to do this. Add the protocol to your web.config, but inside a location element. Specify the webservice location as the path attribute, like so:

<location path="YourWebservice.asmx">
  <system.web>
    <webServices>
      <protocols>
        <add name="HttpGet"/>
        <add name="HttpPost"/>
      </protocols>
    </webServices>
  </system.web>
</location>

Call child method from parent

We can use refs in another way as-

We are going to create a Parent element, it will render a <Child/> component. As you can see, the component that will be rendered, you need to add the ref attribute and provide a name for it.
Then, the triggerChildAlert function, located in the parent class will access the refs property of the this context (when the triggerChildAlert function is triggered will access the child reference and it will has all the functions of the child element).

class Parent extends React.Component {
    triggerChildAlert(){
        this.refs.child.callChildMethod();
        // to get child parent returned  value-
        // this.value = this.refs.child.callChildMethod();
        // alert('Returned value- '+this.value);
    }

    render() {
        return (
            <div>
                {/* Note that you need to give a value to the ref parameter, in this case child*/}
                <Child ref="child" />
                <button onClick={this.triggerChildAlert}>Click</button>
            </div>
        );
    }
}  

Now, the child component, as theoretically designed previously, will look like:

class Child extends React.Component {
    callChildMethod() {
        alert('Hello World');
        // to return some value
        // return this.state.someValue;
    }

    render() {
        return (
            <h1>Hello</h1>
        );
    }
}

Here is the source code-
Hope will help you !

converting epoch time with milliseconds to datetime

Use datetime.datetime.fromtimestamp:

>>> import datetime
>>> s = 1236472051807 / 1000.0
>>> datetime.datetime.fromtimestamp(s).strftime('%Y-%m-%d %H:%M:%S.%f')
'2009-03-08 09:27:31.807000'

%f directive is only supported by datetime.datetime.strftime, not by time.strftime.

UPDATE Alternative using %, str.format:

>>> import time
>>> s, ms = divmod(1236472051807, 1000)  # (1236472051, 807)
>>> '%s.%03d' % (time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(s)), ms)
'2009-03-08 00:27:31.807'
>>> '{}.{:03d}'.format(time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(s)), ms)
'2009-03-08 00:27:31.807'

Adding Counter in shell script

Try this:

counter=0
while true; do
  if /home/hadoop/latest/bin/hadoop fs -ls /apps/hdtech/bds/quality-rt/dt=$DATE_YEST_FORMAT2 then
       echo "Files Present" | mailx -s "File Present"  -r [email protected] [email protected]
       break
  elif [[ "$counter" -gt 20 ]]; then
       echo "Counter limit reached, exit script."
       exit 1
  else
       let counter++
       echo "Sleeping for another half an hour" | mailx -s "Time to Sleep Now"  -r [email protected] [email protected]
       sleep 1800
  fi
done

Explanation

  • break - if files are present, it will break and allow the script to process the files.
  • [[ "$counter" -gt 20 ]] - if the counter variable is greater than 20, the script will exit.
  • let counter++ - increments the counter by 1 at each pass.

How to create a zip archive with PowerShell?

A pure PowerShell alternative that works with PowerShell 3 and .NET 4.5 (if you can use it):

function ZipFiles( $zipfilename, $sourcedir )
{
   Add-Type -Assembly System.IO.Compression.FileSystem
   $compressionLevel = [System.IO.Compression.CompressionLevel]::Optimal
   [System.IO.Compression.ZipFile]::CreateFromDirectory($sourcedir,
        $zipfilename, $compressionLevel, $false)
}

Just pass in the full path to the zip archive you would like to create and the full path to the directory containing the files you would like to zip.

How to compare dates in datetime fields in Postgresql?

When you compare update_date >= '2013-05-03' postgres casts values to the same type to compare values. So your '2013-05-03' was casted to '2013-05-03 00:00:00'.

So for update_date = '2013-05-03 14:45:00' your expression will be that:

'2013-05-03 14:45:00' >= '2013-05-03 00:00:00' AND '2013-05-03 14:45:00' <= '2013-05-03 00:00:00'

This is always false

To solve this problem cast update_date to date:

select * from table where update_date::date >= '2013-05-03' AND update_date::date <= '2013-05-03' -> Will return result

How to make an introduction page with Doxygen

Have a look at the mainpage command.

Also, have a look this answer to another thread: How to include custom files in Doxygen. It states that there are three extensions which doxygen classes as additional documentation files: .dox, .txt and .doc. Files with these extensions do not appear in the file index but can be used to include additional information into your final documentation - very useful for documentation that is necessary but that is not really appropriate to include with your source code (for example, an FAQ)

So I would recommend having a mainpage.dox (or similarly named) file in your project directory to introduce you SDK. Note that inside this file you need to put one or more C/C++ style comment blocks.

Increase permgen space

For tomcat you can increase the permGem space by using

 -XX:MaxPermSize=128m

For this you need to create (if not already exists) a file named setenv.sh in tomcat/bin folder and include following line in it

   export JAVA_OPTS="-XX:MaxPermSize=128m"

Reference : http://wiki.razuna.com/display/ecp/Adjusting+Memory+Settings+for+Tomcat

Difference between $.ajax() and $.get() and $.load()

http://api.jquery.com/jQuery.ajax/

jQuery.ajax()

Description: Perform an asynchronous HTTP (Ajax) request.

The full monty, lets you make any kind of Ajax request.


http://api.jquery.com/jQuery.get/

jQuery.get()

Description: Load data from the server using a HTTP GET request.

Only lets you make HTTP GET requests, requires a little less configuration.


http://api.jquery.com/load/

.load()

Description: Load data from the server and place the returned HTML into the matched element.

Specialized to get data and inject it into an element.

iPhone App Minus App Store?

It's worth noting that if you go the jailbroken route, it's possible (likely?) that an iPhone OS update would kill your ability to run these apps. I'd go the official route and pay the $99 to get authorized. In addition to not having to worry about your apps being clobbered, you also get the opportunity (should you choose) to release your apps on the store.

Invert "if" statement to reduce nesting

Many good reasons about how the code looks like. But what about results?

Let's take a look to some C# code and its IL compiled form:

using System;

public class Test {
    public static void Main(string[] args) {
        if (args.Length == 0) return;
        if ((args.Length+2)/3 == 5) return;
        Console.WriteLine("hey!!!");
    }
}

This simple snippet can be compiled. You can open the generated .exe file with ildasm and check what is the result. I won't post all the assembler thing but I'll describe the results.

The generated IL code does the following:

  1. If the first condition is false, jumps to the code where the second is.
  2. If it's true jumps to the last instruction. (Note: the last instruction is a return).
  3. In the second condition the same happens after the result is calculated. Compare and: got to the Console.WriteLine if false or to the end if this is true.
  4. Print the message and return.

So it seems that the code will jump to the end. What if we do a normal if with nested code?

using System;

public class Test {
    public static void Main(string[] args) {
        if (args.Length != 0 && (args.Length+2)/3 != 5) 
        {
            Console.WriteLine("hey!!!");
        }
    }
}

The results are quite similar in IL instructions. The difference is that before there were two jumps per condition: if false go to next piece of code, if true go to the end. And now the IL code flows better and has 3 jumps (the compiler optimized this a bit):

  1. First jump: when Length is 0 to a part where the code jumps again (Third jump) to the end.
  2. Second: in the middle of the second condition to avoid one instruction.
  3. Third: if the second condition is false, jump to the end.

Anyway, the program counter will always jump.

Loading PictureBox Image from resource file with path (Part 3)

The accepted answer has major drawback!
If you loaded your image that way your PictureBox will lock the image,so if you try to do any future operations on that image,you will get error message image used in another application!
This article show solution in VB

and This is C# implementation

 FileStream fs = new System.IO.FileStream(@"Images\a.bmp", FileMode.Open, FileAccess.Read);
  pictureBox1.Image = Image.FromStream(fs);
  fs.Close();

How to delete a cookie?

I had trouble deleting a cookie made via JavaScript and after I added the host it worked (scroll the code below to the right to see the location.host). After clearing the cookies on a domain try the following to see the results:

if (document.cookie.length==0)
{
 document.cookie = 'name=example; expires='+new Date((new Date()).valueOf()+1000*60*60*24*15)+'; path=/; domain='+location.host;

 if (document.cookie.length==0) {alert('Cookies disabled');}
 else
 {
  document.cookie = 'name=example; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/; domain='+location.host;

  if (document.cookie.length==0) {alert('Created AND deleted cookie successfully.');}
  else {alert('document.cookies.length = '+document.cookies.length);}
 }
}

change PATH permanently on Ubuntu

Add the following line in your .profile file in your home directory (using vi ~/.profile):

PATH=$PATH:/home/me/play
export PATH

Then, for the change to take effect, simply type in your terminal:

$ . ~/.profile

Blade if(isset) is not working Laravel

{{ $usersType or '' }} is working fine. The problem here is your foreach loop:

@foreach( $usersType as $type )
    <input type="checkbox" class='default-checkbox'> <span>{{ $type->type }}</span> &nbsp; 
@endforeach

I suggest you put this in an @if():

@if(isset($usersType))
    @foreach( $usersType as $type )
        <input type="checkbox" class='default-checkbox'> <span>{{ $type->type }}</span> &nbsp; 
    @endforeach
@endif

You can also use @forelse. Simple and easy.

@forelse ($users as $user)
   <li>{{ $user->name }}</li>
@empty
   <p>No users</p>
@endforelse

Staging Deleted files

You can use

git rm -r --cached -- "path/to/directory"

to stage a deleted directory.

UPDATE multiple tables in MySQL using LEFT JOIN

Table A 
+--------+-----------+
| A-num  | text      | 
|    1   |           |
|    2   |           |
|    3   |           |
|    4   |           |
|    5   |           |
+--------+-----------+

Table B
+------+------+--------------+
| B-num|  date        |  A-num | 
|  22  |  01.08.2003  |     2  |
|  23  |  02.08.2003  |     2  | 
|  24  |  03.08.2003  |     1  |
|  25  |  04.08.2003  |     4  |
|  26  |  05.03.2003  |     4  |

I will update field text in table A with

UPDATE `Table A`,`Table B`
SET `Table A`.`text`=concat_ws('',`Table A`.`text`,`Table B`.`B-num`," from                                           
",`Table B`.`date`,'/')
WHERE `Table A`.`A-num` = `Table B`.`A-num`

and come to this result:

Table A 
+--------+------------------------+
| A-num  | text                   | 
|    1   |  24 from 03 08 2003 /  |
|    2   |  22 from 01 08 2003 /  |       
|    3   |                        |
|    4   |  25 from 04 08 2003 /  |
|    5   |                        |
--------+-------------------------+

where only one field from Table B is accepted, but I will come to this result:

Table A 
+--------+--------------------------------------------+
| A-num  | text                                       | 
|    1   |  24 from 03 08 2003                        |
|    2   |  22 from 01 08 2003 / 23 from 02 08 2003 / |       
|    3   |                                            |
|    4   |  25 from 04 08 2003 / 26 from 05 03 2003 / |
|    5   |                                            |
+--------+--------------------------------------------+

Dialog with transparent background in Android

You can use the:

setBackgroundDrawable(null);

method.And following is the doc:

  /**
    * Set the background to a given Drawable, or remove the background. If the
    * background has padding, this View's padding is set to the background's
    * padding. However, when a background is removed, this View's padding isn't
    * touched. If setting the padding is desired, please use
    * {@link #setPadding(int, int, int, int)}.
    *
    * @param d The Drawable to use as the background, or null to remove the
    *        background
    */

How do I initialize an empty array in C#?

In .NET 4.6 the preferred way is to use a new method, Array.Empty:

String[] a = Array.Empty<string>();

The implementation is succinct, using how static members in generic classes behave in .Net:

public static T[] Empty<T>()
{
    return EmptyArray<T>.Value;
}

// Useful in number of places that return an empty byte array to avoid
// unnecessary memory allocation.
internal static class EmptyArray<T>
{
    public static readonly T[] Value = new T[0];
}

(code contract related code removed for clarity)

See also:

How to save Excel Workbook to Desktop regardless of user?

You've mentioned that they each have their own machines, but if they need to log onto a co-workers machine, and then use the file, saving it through "C:\Users\Public\Desktop\" will make it available to different usernames.

Public Sub SaveToDesktop()
    ThisWorkbook.SaveAs Filename:="C:\Users\Public\Desktop\" & ThisWorkbook.Name & "_copy", _ 
    FileFormat:=xlOpenXMLWorkbookMacroEnabled
End Sub

I'm not sure whether this would be a requirement, but may help!

What good are SQL Server schemas?

Here a good implementation example of using schemas with SQL Server. We had several ms-access applications. We wanted to convert those to a ASP.NET App portal. Every ms-access application is written as an App for that portal. Every ms-access application has its own database tables. Some of those are related, we put those in the common dbo schema of SQL Server. The rest gets its own schemas. That way if we want to know what tables belong to an App on the ASP.NET app portal that can easily be navigated, visualised and maintained.

webpack is not recognized as a internal or external command,operable program or batch file

We also experienced this problem and I like all the answers that suggest using a script defined in package.json.

For our solutions we often use the following sequence:

  1. npm install --save-dev webpack-cli (if you're using webpack v4 or later, otherwise use npm install --save-dev webpack, see webpack installation, retrieved 19 Jan 2019)
  2. npx webpack

Step 1 is a one-off. Step 2 also checks ./node_modules/.bin. You can add the second step as a npm script to package.json as well, for example:

{
   ...
   "scripts": {
      ...
      "build": "npx webpack --mode development",
      ...
   },
   ...
}

and then use npm run build to execute this script.

Tested this solution with npm version 6.5.0, webpack version 4.28.4 and webpack-cli version 3.2.1 on Windows 10, executing all commands inside of a PowerShell window. My nodejs version is/was 10.14.2. I also tested this on Ubuntu Linux version 18.04.

I'd advise against installing webpack globally, in particular if you are working with a lot of different projects each of which may require a different version of webpack. Installing webpack globally locks you down to a particular version across all projects on the same machine.

What is the best way to check for Internet connectivity using .NET?

Something like this should work.

System.Net.WebClient

public static bool CheckForInternetConnection()
{
    try
    {
        using (var client = new WebClient())
            using (client.OpenRead("http://google.com/generate_204")) 
                return true; 
    }
    catch
    {
        return false;
    }
}

Render HTML in React Native

An iOS/Android pure javascript react-native component that renders your HTML into 100% native views. It's made to be extremely customizable and easy to use and aims at being able to render anything you throw at it.

react-native-render-html

use above library to improve your app performance level and easy to use.

Install

npm install react-native-render-html --save or yarn add react-native-render-html

Basic usage

import React, { Component } from 'react';
import { ScrollView, Dimensions } from 'react-native';
import HTML from 'react-native-render-html';

const htmlContent = `
    <h1>This HTML snippet is now rendered with native components !</h1>
    <h2>Enjoy a webview-free and blazing fast application</h2>
    <img src="https://i.imgur.com/dHLmxfO.jpg?2" />
    <em style="textAlign: center;">Look at how happy this native cat is</em>
`;

export default class Demo extends Component {
    render () {
        return (
            <ScrollView style={{ flex: 1 }}>
                <HTML html={htmlContent} imagesMaxWidth={Dimensions.get('window').width} />
            </ScrollView>
        );
    }
}

PROPS

you may user it's different different types of props (see above link) for the designing and customizable also using below link refer.

Customizable render html

Limit results in jQuery UI Autocomplete

I've tried all the solutions above, but mine only worked on this way:

success: function (data) {
    response($.map(data.slice (0,10), function(item) {
    return {
    value: item.nome
    };
    }));
},

remove None value from a list without removing the 0 value

L = [0, 23, 234, 89, None, 0, 35, 9] 
result = list(filter(lambda x: x != None, L))

How can I make my string property nullable?

string type is a reference type, therefore it is nullable by default. You can only use Nullable<T> with value types.

public struct Nullable<T> where T : struct

Which means that whatever type is replaced for the generic parameter, it must be a value type.

Count number of days between two dates

(end_date - start_date)/1000/60/60/24

any one have best practice please comment below

Android LinearLayout : Add border with shadow around a LinearLayout

Ya Mahdi aj---for RelativeLayout

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape android:shape="rectangle">
            <gradient
                android:startColor="#7d000000"
                android:endColor="@android:color/transparent"
                android:angle="90" >
            </gradient>
            <corners android:radius="2dp" />
        </shape>
    </item>

    <item
        android:left="0dp"
        android:right="3dp"
        android:top="0dp"
        android:bottom="3dp">
        <shape android:shape="rectangle">
            <padding
                android:bottom="40dp"
                android:top="40dp"
                android:right="10dp"
                android:left="10dp"
                >
            </padding>
            <solid android:color="@color/Whitetransparent"/>
            <corners android:radius="2dp" />
        </shape>
    </item>
</layer-list>

Python: Finding differences between elements of a list

If you don't want to use numpy nor zip, you can use the following solution:

>>> t = [1, 3, 6]
>>> v = [t[i+1]-t[i] for i in range(len(t)-1)]
>>> v
[2, 3]

MySQL SELECT DISTINCT multiple columns

I know that the question is too old, anyway:

select a, b from mytable group by a, b

will give your all the combinations.

How to get week numbers from dates?

Actually, I think you may have discovered a bug in the week(...) function, or at least an error in the documentation. Hopefully someone will jump in and explain why I am wrong.

Looking at the code:

library(lubridate)
> week
function (x) 
yday(x)%/%7 + 1
<environment: namespace:lubridate>

The documentation states:

Weeks is the number of complete seven day periods that have occured between the date and January 1st, plus one.

But since Jan 1 is the first day of the year (not the zeroth), the first "week" will be a six day period. The code should (??) be

(yday(x)-1)%/%7 + 1

NB: You are using week(...) in the data.table package, which is the same code as lubridate::week except it coerces everything to integer rather than numeric for efficiency. So this function has the same problem (??).

Call a PHP function after onClick HTML event

There are two ways. the first is to completely refresh the page using typical form submission

//your_page.php

<?php 

$saveSuccess = null;
$saveMessage = null;

if($_SERVER['REQUEST_METHOD'] == 'POST') {
  // if form has been posted process data

  // you dont need the addContact function you jsut need to put it in a new array
  // and it doesnt make sense in this context so jsut do it here
  // then used json_decode and json_decode to read/save your json in
  // saveContact()
  $data = array(
    'fullname' = $_POST['fullname'],
    'email' => $_POST['email'],
    'phone' => $_POST['phone']
  );

  // always return true if you save the contact data ok or false if it fails
  if(($saveSuccess = saveContact($data)) {
     $saveMessage = 'Your submission has been saved!';     
  } else {
     $saveMessage = 'There was a problem saving your submission.';
  } 
}
?>

<!-- your other html -->

<?php if($saveSuccess !== null): ?>
   <p class="flash_message"><?php echo $saveMessage ?></p>
<?php endif; ?>

<form action="your_page.php" method="post">
    <fieldset>
        <legend>Add New Contact</legend>
        <input type="text" name="fullname" placeholder="First name and last name" required /> <br />
        <input type="email" name="email" placeholder="[email protected]" required /> <br />
        <input type="text" name="phone" placeholder="Personal phone number: mobile, home phone etc." required /> <br />
        <input type="submit" name="submit" class="button" value="Add Contact" onClick="" />
        <input type="button" name="cancel" class="button" value="Reset" />
    </fieldset>
</form>

<!-- the rest of your HTML -->

The second way would be to use AJAX. to do that youll want to completely seprate the form processing into a separate file:

// process.php

$response = array();

if($_SERVER['REQUEST_METHOD'] == 'POST') {
  // if form has been posted process data

  // you dont need the addContact function you jsut need to put it in a new array
  // and it doesnt make sense in this context so jsut do it here
  // then used json_decode and json_decode to read/save your json in
  // saveContact()
  $data = array(
    'fullname' => $_POST['fullname'],
    'email' => $_POST['email'],
    'phone' => $_POST['phone']
  );

  // always return true if you save the contact data ok or false if it fails
  $response['status'] = saveContact($data) ? 'success' : 'error';
  $response['message'] = $response['status']
      ? 'Your submission has been saved!'
      : 'There was a problem saving your submission.';

  header('Content-type: application/json');
  echo json_encode($response);
  exit;
}
?>

And then in your html/js

<form id="add_contact" action="process.php" method="post">
        <fieldset>
            <legend>Add New Contact</legend>
            <input type="text" name="fullname" placeholder="First name and last name" required /> <br />
            <input type="email" name="email" placeholder="[email protected]" required /> <br />
            <input type="text" name="phone" placeholder="Personal phone number: mobile, home phone etc." required /> <br />
            <input id="add_contact_submit" type="submit" name="submit" class="button" value="Add Contact" onClick="" />
            <input type="button" name="cancel" class="button" value="Reset" />
        </fieldset>
    </form>
    <script type="text/javascript">
     $(function(){
         $('#add_contact_submit').click(function(e){
            e.preventDefault();  
            $form = $(this).closest('form');

            // if you need to then wrap this ajax call in conditional logic

            $.ajax({
              url: $form.attr('action'),
              type: $form.attr('method'),
              dataType: 'json',
              success: function(responseJson) {
                 $form.before("<p>"+responseJson.message+"</p>");
              },
              error: function() {
                 $form.before("<p>There was an error processing your request.</p>");
              }
            });
         });         
     });
    </script>

How do you detect the clearing of a "search" HTML5 input?

On click of TextField cross button(X) onmousemove() gets fired, we can use this event to call any function.

<input type="search" class="actInput" id="ruleContact" onkeyup="ruleAdvanceSearch()" placeholder="Search..." onmousemove="ruleAdvanceSearch()"/>

How to check if a network port is open on linux?

In the Above,I found multiple solutions.But some solutions having a hanging issue or taking to much time in case of the port was not opened.Below solution worked for me :

import socket 

def port_check(HOST):
   s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
   s.settimeout(2) #Timeout in case of port not open
   try:
      s.connect((HOST, 22)) #Port ,Here 22 is port 
      return True
   except:
      return False

port_check("127.0.1.1")

How do I output the difference between two specific revisions in Subversion?

To compare entire revisions, it's simply:

svn diff -r 8979:11390


If you want to compare the last committed state against your currently saved working files, you can use convenience keywords:

svn diff -r PREV:HEAD

(Note, without anything specified afterwards, all files in the specified revisions are compared.)


You can compare a specific file if you add the file path afterwards:

svn diff -r 8979:HEAD /path/to/my/file.php

Is Java's assertEquals method reliable?

The JUnit assertEquals(obj1, obj2) does indeed call obj1.equals(obj2).

There's also assertSame(obj1, obj2) which does obj1 == obj2 (i.e., verifies that obj1 and obj2 are referencing the same instance), which is what you're trying to avoid.

So you're fine.

More than one file was found with OS independent path 'META-INF/LICENSE'

I was wired, but my project was already migrated to AndroidX, but after migrating to androidX again, it refactored some part of my project and the problem solved.

What is the JUnit XML format specification that Hudson supports?

Basic Structure Here is an example of a JUnit output file, showing a skip and failed result, as well as a single passed result.

<?xml version="1.0" encoding="UTF-8"?>
<testsuites>
   <testsuite name="JUnitXmlReporter" errors="0" tests="0" failures="0" time="0" timestamp="2013-05-24T10:23:58" />
   <testsuite name="JUnitXmlReporter.constructor" errors="0" skipped="1" tests="3" failures="1" time="0.006" timestamp="2013-05-24T10:23:58">
      <properties>
         <property name="java.vendor" value="Sun Microsystems Inc." />
         <property name="compiler.debug" value="on" />
         <property name="project.jdk.classpath" value="jdk.classpath.1.6" />
      </properties>
      <testcase classname="JUnitXmlReporter.constructor" name="should default path to an empty string" time="0.006">
         <failure message="test failure">Assertion failed</failure>
      </testcase>
      <testcase classname="JUnitXmlReporter.constructor" name="should default consolidate to true" time="0">
         <skipped />
      </testcase>
      <testcase classname="JUnitXmlReporter.constructor" name="should default useDotNotation to true" time="0" />
   </testsuite>
</testsuites>

Below is the documented structure of a typical JUnit XML report. Notice that a report can contain 1 or more test suite. Each test suite has a set of properties (recording environment information). Each test suite also contains 1 or more test case and each test case will either contain a skipped, failure or error node if the test did not pass. If the test case has passed, then it will not contain any nodes. For more details of which attributes are valid for each node please consult the following section "Schema".

<testsuites>        => the aggregated result of all junit testfiles
  <testsuite>       => the output from a single TestSuite
    <properties>    => the defined properties at test execution
      <property>    => name/value pair for a single property
      ...
    </properties>
    <error></error> => optional information, in place of a test case - normally if the tests in the suite could not be found etc.
    <testcase>      => the results from executing a test method
      <system-out>  => data written to System.out during the test run
      <system-err>  => data written to System.err during the test run
      <skipped/>    => test was skipped
      <failure>     => test failed
      <error>       => test encountered an error
    </testcase>
    ...
  </testsuite>
  ...
</testsuites>

Purpose of ESI & EDI registers?

In addition to the string operations (MOVS/INS/STOS/CMPS/SCASB/W/D/Q etc.) mentioned in the other answers, I wanted to add that there are also more "modern" x86 assembly instructions that implicitly use at least EDI/RDI:

The SSE2 MASKMOVDQU (and the upcoming AVX VMASKMOVDQU) instruction selectively write bytes from an XMM register to memory pointed to by EDI/RDI.

What are public, private and protected in object oriented programming?

A public item is one that is accessible from any other class. You just have to know what object it is and you can use a dot operator to access it. Protected means that a class and its subclasses have access to the variable, but not any other classes, they need to use a getter/setter to do anything with the variable. A private means that only that class has direct access to the variable, everything else needs a method/function to access or change that data. Hope this helps.

Make install, but not to default directories?

I tried the above solutions. None worked.

In the end I opened Makefile file and manually changed prefix path to desired installation path like below.

PREFIX ?= "installation path"

When I tried --prefix, "make" complained that there is not such command input. However, perhaps some packages accepts --prefix which is of course a cleaner solution.

How to store phone numbers on MySQL databases?

I suggest storing the numbers in a varchar without formatting. Then you can just reformat the numbers on the client side appropriately. Some cultures prefer to have phone numbers written differently; in France, they write phone numbers like 01-22-33-44-55.

You might also consider storing another field for the country that the phone number is for, because this can be difficult to figure out based on the number you are looking at. The UK uses 11 digit long numbers, some African countries use 7 digit long numbers.

That said, I used to work for a UK phone company, and we stored phone numbers in our database based on if they were UK or international. So, a UK phone number would be 02081234123 and an international one would be 001800300300.

How do I spool to a CSV formatted file using SQLPLUS?

prefer to use "set colsep" in sqlplus prompt instead of editing col name one by one. Use sed to edit the output file.

set colsep '","'     -- separate columns with a comma
sed 's/^/"/;s/$/"/;s/\s *"/"/g;s/"\s */"/g' $outfile > $outfile.csv

Is there an easy way to return a string repeated X number of times?

Works with strings and chars:

Strings and chars [version 1]

string.Join("", Enumerable.Repeat("text" , 2 ));    
//result: texttext

Strings [version 2]:

String.Concat(Enumerable.Repeat("text", 2));
//result: texttext

Strings and chars [version 3]

new StringBuilder().Insert(0, "text", 2).ToString(); 
//result: texttext

Chars only:

'5' * 3; 
//result: 555

Extension way:

(works FASTER - better for WEB)

public static class RepeatExtensions
{
    public static string Repeat(this string str, int times)
    {
        return (new StringBuilder()).Insert(0, str, times).ToString();
    }
}

usage:

 var a = "Hello".Repeat(3); 
 //result: HelloHelloHello

PostgreSQL: FOREIGN KEY/ON DELETE CASCADE

In my humble experience with postgres 9.6, cascade delete doesn't work in practice for tables that grow above a trivial size.

  • Even worse, while the delete cascade is going on, the tables involved are locked so those tables (and potentially your whole database) is unusable.
  • Still worse, it's hard to get postgres to tell you what it's doing during the delete cascade. If it's taking a long time, which table or tables is making it slow? Perhaps it's somewhere in the pg_stats information? It's hard to tell.

How to URL encode a string in Ruby

str = "\x12\x34\x56\x78\x9a\xbc\xde\xf1\x23\x45\x67\x89\xab\xcd\xef\x12\x34\x56\x78\x9a".force_encoding('ASCII-8BIT')
puts CGI.escape str


=> "%124Vx%9A%BC%DE%F1%23Eg%89%AB%CD%EF%124Vx%9A"

How to insert multiple rows from array using CodeIgniter framework?

$query= array(); 
foreach( $your_data as $row ) {
    $query[] = '("'.mysql_real_escape_string($row['text']).'", '.$row['category_id'].')';
}
mysql_query('INSERT INTO table (text, category) VALUES '.implode(',', $query));

How create a new deep copy (clone) of a List<T>?

You need to create new Book objects then put those in a new List:

List<Book> books_2 = books_1.Select(book => new Book(book.title)).ToList();

Update: Slightly simpler... List<T> has a method called ConvertAll that returns a new list:

List<Book> books_2 = books_1.ConvertAll(book => new Book(book.title));

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

From the man page, npm start:

runs a package's "start" script, if one was provided. If no version is specified, then it starts the "active" version.

Admittedly, that description is completely unhelpful, and that's all it says. At least it's more documented than socket.io.

Anyhow, what really happens is that npm looks in your package.json file, and if you have something like

"scripts": { "start": "coffee server.coffee" }

then it will do that. If npm can't find your start script, it defaults to:

node server.js

 

Why are the Level.FINE logging messages not showing?

Tried other variants, this can be proper

    Logger logger = Logger.getLogger(MyClass.class.getName());        
    Level level = Level.ALL;
    for(Handler h : java.util.logging.Logger.getLogger("").getHandlers())    
        h.setLevel(level);
    logger.setLevel(level);
// this must be shown
    logger.fine("fine");
    logger.info("info");

fill an array in C#

Say you want to fill with number 13.

int[] myarr = Enumerable.Range(0, 10).Select(n => 13).ToArray();

or

List<int> myarr = Enumerable.Range(0,10).Select(n => 13).ToList();

if you prefer a list.

How to preventDefault on anchor tags?

Borrowing from tennisgent's answer. I like that you don't have to create a custom directive to add on all the links. However, I couldnt get his to work in IE8. Here's what finally worked for me (using angular 1.0.6).

Notice that 'bind' allows you to use jqLite provided by angular so no need to wrap with full jQuery. Also required the stopPropogation method.

.directive('a', [
    function() {
        return {
            restrict: 'E',
            link: function(scope, elem, attrs) {

                elem.bind('click', function(e){
                    if (attrs.ngClick || attrs.href === '' || attrs.href == '#'){
                        e.preventDefault();
                        e.stopPropagation();
                    }
                })
            }
        };
    }
])

How to verify if nginx is running or not?

None of the above answers worked for me so let me share my experience. I am running nginx in a docker container that has a port mapping (hostPort:containerPort) - 80:80 The above answers are giving me strange console output. Only the good old 'nmap' is working flawlessly even catching the nginx version. The command working for me is:

 nmap -sV localhost -p 80

We are doing nmap using the -ServiceVersion switch on the localhost and port: 80. It works great for me.

What does void do in java?

You mean the tellItLikeItIs method? Yes, you have to specify void to specify that the method doesn't return anything. All methods have to have a return type specified, even if it's void.

It certainly doesn't return a string - look, there are no return statements anywhere. It's not really clear why you think it is returning a string. It's printing strings to the console, but that's not the same thing as returning one from the method.

Pandas DataFrame concat vs append

One more thing you have to keep in mind that the APPEND() method in Pandas doesn't modify the original object. Instead it creates a new one with combined data. Because of involving creation and data buffer, its performance is not well. You'd better use CONCAT() function when doing multi-APPEND operations.

How to create an empty DataFrame with a specified schema?

As of Spark 2.4.3

val df = SparkSession.builder().getOrCreate().emptyDataFrame

How do I convert from a string to an integer in Visual Basic?

Please try this, VB.NET 2010:

  1. Integer.TryParse(txtPrice.Text, decPrice)
  2. decPrice = Convert.ToInt32(txtPrice.Text)

From Mola Tshepo Kingsley (WWW.TUT.AC.ZA)

How can I list all of the files in a directory with Perl?

If you want to get content of given directory, and only it (i.e. no subdirectories), the best way is to use opendir/readdir/closedir:

opendir my $dir, "/some/path" or die "Cannot open directory: $!";
my @files = readdir $dir;
closedir $dir;

You can also use:

my @files = glob( $dir . '/*' );

But in my opinion it is not as good - mostly because glob is quite complex thing (can filter results automatically) and using it to get all elements of directory seems as a too simple task.

On the other hand, if you need to get content from all of the directories and subdirectories, there is basically one standard solution:

use File::Find;

my @content;
find( \&wanted, '/some/path');
do_something_with( @content );

exit;

sub wanted {
  push @content, $File::Find::name;
  return;
}

Find files in a folder using Java

Have a look at java.io.File.list() and FilenameFilter.

Is there a max array length limit in C++?

To summarize the responses, extend them, and to answer your question directly:

No, C++ does not impose any limits for the dimensions of an array.

But as the array has to be stored somewhere in memory, so memory-related limits imposed by other parts of the computer system apply. Note that these limits do not directly relate to the dimensions (=number of elements) of the array, but rather to its size (=amount of memory taken). Dimensions (D) and in-memory size (S) of an array is not the same, as they are related by memory taken by a single element (E): S=D * E.

Now E depends on:

  • the type of the array elements (elements can be smaller or bigger)
  • memory alignment (to increase performance, elements are placed at addresses which are multiplies of some value, which introduces
    ‘wasted space’ (padding) between elements
  • size of static parts of objects (in object-oriented programming static components of objects of the same type are only stored once, independent from the number of such same-type objects)

Also note that you generally get different memory-related limitations by allocating the array data on stack (as an automatic variable: int t[N]), or on heap (dynamic alocation with malloc()/new or using STL mechanisms), or in the static part of process memory (as a static variable: static int t[N]). Even when allocating on heap, you still need some tiny amount of memory on stack to store references to the heap-allocated blocks of memory (but this is negligible, usually).

The size of size_t type has no influence on the programmer (I assume programmer uses size_t type for indexing, as it is designed for it), as compiler provider has to typedef it to an integer type big enough to address maximal amount of memory possible for the given platform architecture.

The sources of the memory-size limitations stem from

  • amount of memory available to the process (which is limited to 2^32 bytes for 32-bit applications, even on 64-bits OS kernels),
  • the division of process memory (e.g. amount of the process memory designed for stack or heap),
  • the fragmentation of physical memory (many scattered small free memory fragments are not applicable to storing one monolithic structure),
  • amount of physical memory,
  • and the amount of virtual memory.

They can not be ‘tweaked’ at the application level, but you are free to use a different compiler (to change stack size limits), or port your application to 64-bits, or port it to another OS, or change the physical/virtual memory configuration of the (virtual? physical?) machine.

It is not uncommon (and even advisable) to treat all the above factors as external disturbances and thus as possible sources of runtime errors, and to carefully check&react to memory-allocation related errors in your program code.

So finally: while C++ does not impose any limits, you still have to check for adverse memory-related conditions when running your code... :-)

Linux: command to open URL in default browser

I think using xdg-open http://example.com is probably the best choice.

In case they don't have it installed I suppose they might have just kde-open or gnome-open (both of which take a single file/url) or some other workaround such as looping over common browser executable names until you find one which can be executed(using which). If you want a full list of workarounds/fallbacks I suggest reading xdg-open(it's a shell script which calls out to kde-open/gnome-open/etc. or some other fallback).

But since xdg-open and xdg-mime(used for one of the fallbacks,) are shell scripts I'd recommend including them in your application and if calling which xdg-open fails add them to temporary PATH variable in your subprograms environment and call out to them. If xdg-open fails, I'd recommend throwing an Exception with an error message from what it output on stderr and catching the exception and printing/displaying the error message.

I would ignore the java awt Desktop solution as the bug seems to indicate they don't plan on supporting non-gnome desktops anytime soon.

How to get video duration, dimension and size in PHP?

https://github.com/JamesHeinrich/getID3 download getid3 zip and than only getid3 named folder copy paste in project folder and use it as below show...

<?php
        require_once('/fire/scripts/lib/getid3/getid3/getid3.php');
        $getID3 = new getID3();
        $filename="/fire/My Documents/video/ferrari1.mpg";
        $fileinfo = $getID3->analyze($filename);

        $width=$fileinfo['video']['resolution_x'];
        $height=$fileinfo['video']['resolution_y'];

        echo $fileinfo['video']['resolution_x']. 'x'. $fileinfo['video']['resolution_y'];
        echo '<pre>';print_r($fileinfo);echo '</pre>';
?>

What is the Swift equivalent of respondsToSelector?

The equivalent is the ? operator:

var value: NSNumber? = myQuestionableObject?.importantMethod()

importantMethod will only be called if myQuestionableObject exists and implements it.

ojdbc14.jar vs. ojdbc6.jar

The "14" and "6" in those driver names refer to the JVM they were written for. If you're still using JDK 1.4 I'd say you have a serious problem and need to upgrade. JDK 1.4 is long past its useful support life. It didn't even have generics! JDK 6 u21 is the current production standard from Oracle/Sun. I'd recommend switching to it if you haven't already.

Setting an HTML text input box's "default" value. Revert the value when clicking ESC

This esc behavior is IE only by the way. Instead of using jQuery use good old javascript for creating the element and it works.

var element = document.createElement('input');
element.type = 'text';
element.value = 100;
document.getElementsByTagName('body')[0].appendChild(element);

http://jsfiddle.net/gGrf9/

If you want to extend this functionality to other browsers then I would use jQuery's data object to store the default. Then set it when user presses escape.

//store default value for all elements on page. set new default on blur
$('input').each( function() {
    $(this).data('default', $(this).val());
    $(this).blur( function() { $(this).data('default', $(this).val()); });
});

$('input').keyup( function(e) {
    if (e.keyCode == 27) { $(this).val($(this).data('default')); }
});

Set disable attribute based on a condition for Html.TextBoxFor

One simple approach I have used is conditional rendering:

@(Model.ExpireDate == null ? 
  @Html.TextBoxFor(m => m.ExpireDate, new { @disabled = "disabled" }) : 
  @Html.TextBoxFor(m => m.ExpireDate)
)

jQuery - Getting the text value of a table cell in the same row as a clicked element

This will also work

$(this).parent().parent().find('td').text()

jQuery.parseJSON throws “Invalid JSON” error due to escaped single quote in JSON

Striking a similar issue using CakePHP to output a JavaScript script-block using PHP's native json_encode. $contractorCompanies contains values that have single quotation marks and as explained above and expected json_encode($contractorCompanies) doesn't escape them because its valid JSON.

<?php $this->Html->scriptBlock("var contractorCompanies = jQuery.parseJSON( '".(json_encode($contractorCompanies)."' );"); ?>

By adding addslashes() around the JSON encoded string you then escape the quotation marks allowing Cake / PHP to echo the correct javascript to the browser. JS errors disappear.

<?php $this->Html->scriptBlock("var contractorCompanies = jQuery.parseJSON( '".addslashes(json_encode($contractorCompanies))."' );"); ?>

Unloading classes in java?

Yes there are ways to load classes and to "unload" them later on. The trick is to implement your own classloader which resides between high level class loader (the System class loader) and the class loaders of the app server(s), and to hope that the app server's class loaders do delegate the classloading to the upper loaders.

A class is defined by its package, its name, and the class loader it originally loaded. Program a "proxy" classloader which is the first that is loaded when starting the JVM. Workflow:

  • The program starts and the real "main"-class is loaded by this proxy classloader.
  • Every class that then is normally loaded (i.e. not through another classloader implementation which could break the hierarchy) will be delegated to this class loader.
  • The proxy classloader delegates java.x and sun.x to the system classloader (these must not be loaded through any other classloader than the system classloader).
  • For every class that is replaceable, instantiate a classloader (which really loads the class and does not delegate it to the parent classloader) and load it through this.
  • Store the package/name of the classes as keys and the classloader as values in a data structure (i.e. Hashmap).
  • Every time the proxy classloader gets a request for a class that was loaded before, it returns the class from the class loader stored before.
  • It should be enough to locate the byte array of a class by your class loader (or to "delete" the key/value pair from your data structure) and reload the class in case you want to change it.

Done right there should not come a ClassCastException or LinkageError etc.

For more informations about class loader hierarchies (yes, that's exactly what you are implementing here ;- ) look at "Server-Based Java Programming" by Ted Neward - that book helped me implementing something very similar to what you want.

JavaScript calculate the day of the year (1 - 366)

Luckily this question doesn't specify if the number of the current day is required, leaving room for this answer.
Also some answers (also on other questions) had leap-year problems or used the Date-object. Although javascript's Date object covers approximately 285616 years (100,000,000 days) on either side of January 1 1970, I was fed up with all kinds of unexpected date inconsistencies across different browsers (most notably year 0 to 99). I was also curious how to calculate it.

So I wrote a simple and above all, small algorithm to calculate the correct (Proleptic Gregorian / Astronomical / ISO 8601:2004 (clause 4.3.2.1), so year 0 exists and is a leap year and negative years are supported) day of the year based on year, month and day.
Note that in AD/BC notation, year 0 AD/BC does not exist: instead year 1 BC is the leap-year! IF you need to account for BC notation then simply subtract one year of the (otherwise positive) year-value first!!

I modified (for javascript) the short-circuit bitmask-modulo leapYear algorithm and came up with a magic number to do a bit-wise lookup of offsets (that excludes jan and feb, thus needing 10 * 3 bits (30 bits is less than 31 bits, so we can safely save another character on the bitshift instead of >>>)).

Note that neither month or day may be 0. That means that if you need this equation just for the current day (feeding it using .getMonth()) you just need to remove the -- from --m.

Note this assumes a valid date (although error-checking is just some characters more).

_x000D_
_x000D_
function dayNo(y,m,d){_x000D_
  return --m*31-(m>1?(1054267675>>m*3-6&7)-(y&3||!(y%25)&&y&15?0:1):0)+d;_x000D_
}
_x000D_
<!-- some examples for the snippet -->_x000D_
<input type=text value="(-)Y-M-D" onblur="_x000D_
  var d=this.value.match(/(-?\d+)[^\d]+(\d\d?)[^\d]+(\d\d?)/)||[];_x000D_
  this.nextSibling.innerHTML=' Day: ' + dayNo(+d[1], +d[2], +d[3]);_x000D_
" /><span></span>_x000D_
_x000D_
<br><hr><br>_x000D_
_x000D_
<button onclick="_x000D_
  var d=new Date();_x000D_
  this.nextSibling.innerHTML=dayNo(d.getFullYear(), d.getMonth()+1, d.getDate()) + ' Day(s)';_x000D_
">get current dayno:</button><span></span>
_x000D_
_x000D_
_x000D_


Here is the version with correct range-validation.

_x000D_
_x000D_
function dayNo(y,m,d){_x000D_
  return --m>=0 && m<12 && d>0 && d<29+(  _x000D_
           4*(y=y&3||!(y%25)&&y&15?0:1)+15662003>>m*2&3  _x000D_
         ) && m*31-(m>1?(1054267675>>m*3-6&7)-y:0)+d;_x000D_
}
_x000D_
<!-- some examples for the snippet -->_x000D_
<input type=text value="(-)Y-M-D" onblur="_x000D_
  var d=this.value.match(/(-?\d+)[^\d]+(\d\d?)[^\d]+(\d\d?)/)||[];_x000D_
  this.nextSibling.innerHTML=' Day: ' + dayNo(+d[1], +d[2], +d[3]);_x000D_
" /><span></span>
_x000D_
_x000D_
_x000D_

Again, one line, but I split it into 3 lines for readability (and following explanation).

The last line is identical to the function above, however the (identical) leapYear algorithm is moved to a previous short-circuit section (before the day-number calculation), because it is also needed to know how much days a month has in a given (leap) year.

The middle line calculates the correct offset number (for max number of days) for a given month in a given (leap)year using another magic number: since 31-28=3 and 3 is just 2 bits, then 12*2=24 bits, we can store all 12 months. Since addition can be faster then subtraction, we add the offset (instead of subtract it from 31). To avoid a leap-year decision-branch for February, we modify that magic lookup-number on the fly.

That leaves us with the (pretty obvious) first line: it checks that month and date are within valid bounds and ensures us with a false return value on range error (note that this function also should not be able to return 0, because 1 jan 0000 is still day 1.), providing easy error-checking: if(r=dayNo(/*y, m, d*/)){}.
If used this way (where month and day may not be 0), then one can change --m>=0 && m<12 to m>0 && --m<12 (saving another char).
The reason I typed the snippet in it's current form is that for 0-based month values, one just needs to remove the -- from --m.

Extra:
Note, don't use this day's per month algorithm if you need just max day's per month. In that case there is a more efficient algorithm (because we only need leepYear when the month is February) I posted as answer this question: What is the best way to determine the number of days in a month with javascript?.

IF/ELSE Stored Procedure

Nick is right. The next error is the else should be else if (you currently have a boolean expression in your else which makes no sense). Here is what it should be

ELSE IF(@Trans_type = 'subscr_cancel')
    BEGIN
    SET @tmpType = 'basic'
    END

You currently have the following (which is wrong):

ELSE(@Trans_type = 'subscr_cancel')
    BEGIN
    SET @tmpType = 'basic'
    END

Here's a tip for the future- double click on the error and SQL Server management Studio will go to the line where the error resides. If you think SQL Server gives cryptic errors (which I don't think it does), then you haven't worked with Oracle!

Best way to run scheduled tasks

Why reinvent the wheel, use the Threading and the Timer class.

    protected void Application_Start()
    {
        Thread thread = new Thread(new ThreadStart(ThreadFunc));
        thread.IsBackground = true;
        thread.Name = "ThreadFunc";
        thread.Start();
    }

    protected void ThreadFunc()
    {
        System.Timers.Timer t = new System.Timers.Timer();
        t.Elapsed += new System.Timers.ElapsedEventHandler(TimerWorker);
        t.Interval = 10000;
        t.Enabled = true;
        t.AutoReset = true;
        t.Start();
    }

    protected void TimerWorker(object sender, System.Timers.ElapsedEventArgs e)
    {
        //work args
    }

How to unapply a migration in ASP.NET Core with EF Core

Use:

CLI

> dotnet ef database update <previous-migration-name>

Package Manager Console

PM> Update-Database <previous-migration-name>

Example:

PM> Update-Database MyInitialMigration

Then try to remove last migration.

Removing migration without database update doesn't work because you applied changes to database.

If using PMC, Try: PM> update-database 0 This will wipe the database and allow you to remove the Migration Snapshot on your Solution

Java Class that implements Map and keeps insertion order?

I suggest a LinkedHashMap or a TreeMap. A LinkedHashMap keeps the keys in the order they were inserted, while a TreeMap is kept sorted via a Comparator or the natural Comparable ordering of the elements.

Since it doesn't have to keep the elements sorted, LinkedHashMap should be faster for most cases; TreeMap has O(log n) performance for containsKey, get, put, and remove, according to the Javadocs, while LinkedHashMap is O(1) for each.

If your API that only expects a predictable sort order, as opposed to a specific sort order, consider using the interfaces these two classes implement, NavigableMap or SortedMap. This will allow you not to leak specific implementations into your API and switch to either of those specific classes or a completely different implementation at will afterwards.

SVN checkout the contents of a folder, not the folder itself

Provide the directory on the command line:

svn checkout file:///home/landonwinters/svn/waterproject/trunk public_html

How to kill a child process after a given timeout in Bash?

Assuming you have (or can easily make) a pid file for tracking the child's pid, you could then create a script that checks the modtime of the pid file and kills/respawns the process as needed. Then just put the script in crontab to run at approximately the period you need.

Let me know if you need more details. If that doesn't sound like it'd suit your needs, what about upstart?

How to remove symbols from a string with Python?

One way, using regular expressions:

>>> s = "how much for the maple syrup? $20.99? That's ridiculous!!!"
>>> re.sub(r'[^\w]', ' ', s)
'how much for the maple syrup   20 99  That s ridiculous   '
  • \w will match alphanumeric characters and underscores

  • [^\w] will match anything that's not alphanumeric or underscore

Center the nav in Twitter Bootstrap

For anyone needing this for Bootstrap 3, it is now much easier.

The new nav-justified class can be used to center all of the navbar links..

http://www.bootply.com/g3g125MLGr

<div class="navbar">
  <ul class="nav nav-justified" id="myNav">
    <li><a href="#">Home</a></li>
    <li><a href="#">Link</a></li>
    <li><a href="#">Link</a></li>
    <li><a href="#">Link</a></li>
    <li><a href="#">Link</a></li>
    <li><a href="#">Link</a></li>
    <li><a href="#">Link</a></li>
  </ul>
</div>

Or with a little CSS you can center just the brand/logo, and keep the left/right links separate..

http://www.bootply.com/3iSOTAyumP

How can I count the number of characters in a Bash variable

${#str_var}  

where str_var is your string.

Is there a native jQuery function to switch elements?

if nodeA and nodeB are siblings, likes two <tr> in the same <tbody>, you can just use $(trA).insertAfter($(trB)) or $(trA).insertBefore($(trB)) to swap them, it works for me. and you don't need to call $(trA).remove() before, else you need to re-bind some click events on $(trA)

How does PHP 'foreach' actually work?

As per the documentation provided by PHP manual.

On each iteration, the value of the current element is assigned to $v and the internal
array pointer is advanced by one (so on the next iteration, you'll be looking at the next element).

So as per your first example:

$array = ['foo'=>1];
foreach($array as $k=>&$v)
{
   $array['bar']=2;
   echo($v);
}

$array have only single element, so as per the foreach execution, 1 assign to $v and it don't have any other element to move pointer

But in your second example:

$array = ['foo'=>1, 'bar'=>2];
foreach($array as $k=>&$v)
{
   $array['baz']=3;
   echo($v);
}

$array have two element, so now $array evaluate the zero indices and move the pointer by one. For first iteration of loop, added $array['baz']=3; as pass by reference.

How to convert an integer (time) to HH:MM:SS::00 in SQL Server 2008?

Convert the integer into a string and then you can use the STUFF function to insert in your colons into time string. Once you've done that you can convert the string into a time datatype.

SELECT CAST(STUFF(STUFF(STUFF(cast(23421155 as varchar),3,0,':'),6,0,':'),9,0,'.') AS TIME)

That should be the simplest way to convert it to a time without doing anything to crazy.

In your example you also had an int where the leading zeros are not there. In that case you can simple do something like this:

SELECT CAST(STUFF(STUFF(STUFF(RIGHT('00000000' + CAST(421151 AS VARCHAR),8),3,0,':'),6,0,':'),9,0,'.') AS TIME)

How to get a list of programs running with nohup

If you have standart output redirect to "nohup.out" just see who use this file

lsof | grep nohup.out

How are cookies passed in the HTTP protocol?

create example script as resp :

#!/bin/bash

http_code=200
mime=text/html

echo -e "HTTP/1.1 $http_code OK\r"
echo "Content-type: $mime"
echo
echo "Set-Cookie: name=F"

then make executable and execute like this.

./resp | nc -l -p 12346

open browser and browse URL: http://localhost:1236 you will see Cookie value which is sent by Browser

    [aaa@bbbbbbbb ]$ ./resp | nc -l -p 12346
    GET / HTTP/1.1
    Host: xxx.xxx.xxx.xxx:12346
    Connection: keep-alive
    Cache-Control: max-age=0
    Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
    Upgrade-Insecure-Requests: 1
    User-Agent: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.112 Safari/537.36
    Accept-Encoding: gzip, deflate, sdch
    Accept-Language: en-US,en;q=0.8,ru;q=0.6
    Cookie: name=F

How to get the indexpath.row when an element is activated?

Use an extension to UITableView to fetch the cell that contains any view:


@Paulw11's answer of setting up a custom cell type with a delegate property that sends messages to the table view is a good way to go, but it requires a certain amount of work to set up.

I think walking the table view cell's view hierarchy looking for the cell is a bad idea. It is fragile - if you later enclose your button in a view for layout purposes, that code is likely to break.

Using view tags is also fragile. You have to remember to set up the tags when you create the cell, and if you use that approach in a view controller that uses view tags for another purpose you can have duplicate tag numbers and your code can fail to work as expected.

I have created an extension to UITableView that lets you get the indexPath for any view that is contained in a table view cell. It returns an Optional that will be nil if the view passed in actually does not fall within a table view cell. Below is the extension source file in it's entirety. You can simply put this file in your project and then use the included indexPathForView(_:) method to find the indexPath that contains any view.

//
//  UITableView+indexPathForView.swift
//  TableViewExtension
//
//  Created by Duncan Champney on 12/23/16.
//  Copyright © 2016-2017 Duncan Champney.
//  May be used freely in for any purpose as long as this 
//  copyright notice is included.

import UIKit

public extension UITableView {
  
  /**
  This method returns the indexPath of the cell that contains the specified view
   
   - Parameter view: The view to find.
   
   - Returns: The indexPath of the cell containing the view, or nil if it can't be found
   
  */
  
    func indexPathForView(_ view: UIView) -> IndexPath? {
        let center = view.center
        let viewCenter = self.convert(center, from: view.superview)
        let indexPath = self.indexPathForRow(at: viewCenter)
        return indexPath
    }
}

To use it, you can simply call the method in the IBAction for a button that's contained in a cell:

func buttonTapped(_ button: UIButton) {
  if let indexPath = self.tableView.indexPathForView(button) {
    print("Button tapped at indexPath \(indexPath)")
  }
  else {
    print("Button indexPath not found")
  }
}

(Note that the indexPathForView(_:) function will only work if the view object it's passed is contained by a cell that's currently on-screen. That's reasonable, since a view that is not on-screen doesn't actually belong to a specific indexPath; it's likely to be assigned to a different indexPath when it's containing cell is recycled.)

EDIT:

You can download a working demo project that uses the above extension from Github: TableViewExtension.git

Angularjs - Pass argument to directive

Controller code

myApp.controller('mainController', ['$scope', '$log', function($scope, $log) {
    $scope.person = {
        name:"sangeetha PH",
       address:"first Block"
    }
}]);

Directive Code

myApp.directive('searchResult',function(){
   return{
       restrict:'AECM',
       templateUrl:'directives/search.html',
       replace: true,
       scope:{
           personName:"@",
           personAddress:"@"
       }
   } 
});

USAGE

File :directives/search.html
content:

<h1>{{personName}} </h1>
<h2>{{personAddress}}</h2>

the File where we use directive

<search-result person-name="{{person.name}}" person-address="{{person.address}}"></search-result>

Base64 Decoding in iOS 7+

Swift 3+

let plainString = "foo"

Encoding

let plainData = plainString.data(using: .utf8)
let base64String = plainData?.base64EncodedString()
print(base64String!) // Zm9v

Decoding

if let decodedData = Data(base64Encoded: base64String!),
   let decodedString = String(data: decodedData, encoding: .utf8) {
  print(decodedString) // foo
}

Swift < 3

let plainString = "foo"

Encoding

let plainData = plainString.dataUsingEncoding(NSUTF8StringEncoding)
let base64String = plainData?.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0))
print(base64String!) // Zm9v

Decoding

let decodedData = NSData(base64EncodedString: base64String!, options: NSDataBase64DecodingOptions(rawValue: 0))
let decodedString = NSString(data: decodedData, encoding: NSUTF8StringEncoding)
print(decodedString) // foo

Objective-C

NSString *plainString = @"foo";

Encoding

NSData *plainData = [plainString dataUsingEncoding:NSUTF8StringEncoding];
NSString *base64String = [plainData base64EncodedStringWithOptions:0];
NSLog(@"%@", base64String); // Zm9v

Decoding

NSData *decodedData = [[NSData alloc] initWithBase64EncodedString:base64String options:0];
NSString *decodedString = [[NSString alloc] initWithData:decodedData encoding:NSUTF8StringEncoding];
NSLog(@"%@", decodedString); // foo 

Hadoop: «ERROR : JAVA_HOME is not set»

I tried the above solutions but the following worked on me

export JAVA_HOME=/usr/java/default

Types in Objective-C on iOS

Update for the new 64bit arch

Ranges:
CHAR_MIN:   -128
CHAR_MAX:   127
SHRT_MIN:   -32768
SHRT_MAX:   32767
INT_MIN:    -2147483648
INT_MAX:    2147483647
LONG_MIN:   -9223372036854775808
LONG_MAX:   9223372036854775807
ULONG_MAX:  18446744073709551615
LLONG_MIN:  -9223372036854775808
LLONG_MAX:  9223372036854775807
ULLONG_MAX: 18446744073709551615

javax.naming.NoInitialContextException - Java

We need to specify the INITIAL_CONTEXT_FACTORY, PROVIDER_URL, USERNAME, PASSWORD etc. of JNDI to create an InitialContext.

In a standalone application, you can specify that as below

Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY, 
    "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, "ldap://ldap.wiz.com:389");
env.put(Context.SECURITY_PRINCIPAL, "joeuser");
env.put(Context.SECURITY_CREDENTIALS, "joepassword");

Context ctx = new InitialContext(env);

But if you are running your code in a Java EE container, these values will be fetched by the container and used to create an InitialContext as below

System.getProperty(Context.PROVIDER_URL);

and

these values will be set while starting the container as JVM arguments. So if you are running the code in a container, the following will work

InitialContext ctx = new InitialContext();

typeof operator in C

Since typeof is a compiler extension, there is not really a definition for it, but in the tradition of C it would be an operator, e.g sizeof and _Alignof are also seen as an operators.

And you are mistaken, C has dynamic types that are only determined at run time: variable modified (VM) types.

size_t n = strtoull(argv[1], 0, 0);
double A[n][n];
typeof(A) B;

can only be determined at run time.

Creating a DateTime in a specific Time Zone in c#

You'll have to create a custom object for that. Your custom object will contain two values:

Not sure if there already is a CLR-provided data type that has that, but at least the TimeZone component is already available.

How to make use of ng-if , ng-else in angularJS

Use ng-switch with expression and ng-switch-when for matching expression value:

<div ng-switch="data.id">
  <div ng-switch-when="5">...</div>
  <div ng-switch-default>...</div>
</div>

Example is here

Angular2 example

Is it possible to use Visual Studio on macOS?

There is no native version of Visual Studio for Mac OS X.

Almost all versions of Visual Studio have a Garbage rating on Wine's application database, so Wine isn't an option either, sadly.

How do I determine if my python shell is executing in 32bit or 64bit?

On Windows OS

Open the cmd termial and start python interpreter by typing >python as shown in the below image

Img

If the interpreter info at start contains AMD64, it's 64-bit, otherwise, 32-bit bit.

Convert date to another timezone in JavaScript

Most browsers support the toLocaleString function with arguments, older browsers usually ignore the arguments.

_x000D_
_x000D_
const str = new Date().toLocaleString('en-US', { timeZone: 'Asia/Jakarta' });
console.log(str);
_x000D_
_x000D_
_x000D_

Using colors with printf

#include <stdio.h>

//fonts color
#define FBLACK      "\033[30;"
#define FRED        "\033[31;"
#define FGREEN      "\033[32;"
#define FYELLOW     "\033[33;"
#define FBLUE       "\033[34;"
#define FPURPLE     "\033[35;"
#define D_FGREEN    "\033[6;"
#define FWHITE      "\033[7;"
#define FCYAN       "\x1b[36m"

//background color
#define BBLACK      "40m"
#define BRED        "41m"
#define BGREEN      "42m"
#define BYELLOW     "43m"
#define BBLUE       "44m"
#define BPURPLE     "45m"
#define D_BGREEN    "46m"
#define BWHITE      "47m"

//end color
#define NONE        "\033[0m"

int main(int argc, char *argv[])
{
    printf(D_FGREEN BBLUE"Change color!\n"NONE);

    return 0;
}

I have created a table in hive, I would like to know which directory my table is created in?

There are three ways to describe a table in Hive.

1) To see table primary info of Hive table, use describe table_name; command

2) To see more detailed information about the table, use describe extended table_name; command

3) To see code in a clean manner use describe formatted table_name; command to see all information. also describe all details in a clean manner.

Resource: Hive interview tips

Securely storing passwords for use in python script

the secure way is encrypt your sensitive data by AES and the encryption key is derivation by password-based key derivation function (PBE), the master password used to encrypt/decrypt the encrypt key for AES.

master password -> secure key-> encrypt data by the key

You can use pbkdf2

from PBKDF2 import PBKDF2
from Crypto.Cipher import AES
import os
salt = os.urandom(8)    # 64-bit salt
key = PBKDF2("This passphrase is a secret.", salt).read(32) # 256-bit key
iv = os.urandom(16)     # 128-bit IV
cipher = AES.new(key, AES.MODE_CBC, iv)

make sure to store the salt/iv/passphrase , and decrypt using same salt/iv/passphase

Weblogic used similar approach to protect passwords in config files

Disable F5 and browser refresh using JavaScript

You can directly use hotkey from rich faces if you are using JSF.

<rich:hotKey key="backspace" onkeydown="if (event.keyCode == 8) return false;" handler="return false;" disableInInput="true" />
<rich:hotKey key="f5" onkeydown="if (event.keyCode == 116) return false;" handler="return false;" disableInInput="true" />
<rich:hotKey key="ctrl+R" onkeydown="if (event.keyCode == 123) return false;" handler="return false;" disableInInput="true" />
<rich:hotKey key="ctrl+f5" onkeydown="if (event.keyCode == 154) return false;" handler="return false;" disableInInput="true" /> 

Mocking Extension Methods with Moq

I like to use the wrapper (adapter pattern) when I am wrapping the object itself. I'm not sure I'd use that for wrapping an extension method, which is not part of the object.

I use an internal Lazy Injectable Property of either type Action, Func, Predicate, or delegate and allow for injecting (swapping out) the method during a unit test.

    internal Func<IMyObject, string, object> DoWorkMethod
    {
        [ExcludeFromCodeCoverage]
        get { return _DoWorkMethod ?? (_DoWorkMethod = (obj, val) => { return obj.DoWork(val); }); }
        set { _DoWorkMethod = value; }
    } private Func<IMyObject, string, object> _DoWorkMethod;

Then you call the Func instead of the actual method.

    public object SomeFunction()
    {
        var val = "doesn't matter for this example";
        return DoWorkMethod.Invoke(MyObjectProperty, val);
    }

For a more complete example, check out http://www.rhyous.com/2016/08/11/unit-testing-calls-to-complex-extension-methods/

How to disable logging on the standard error stream in Python?

You can use:

logging.basicConfig(level=your_level)

where your_level is one of those:

'debug': logging.DEBUG,
'info': logging.INFO,
'warning': logging.WARNING,
'error': logging.ERROR,
'critical': logging.CRITICAL

So, if you set your_level to logging.CRITICAL, you will get only critical messages sent by:

logging.critical('This is a critical error message')

Setting your_level to logging.DEBUG will show all levels of logging.

For more details, please take a look at logging examples.

In the same manner to change level for each Handler use Handler.setLevel() function.

import logging
import logging.handlers

LOG_FILENAME = '/tmp/logging_rotatingfile_example.out'

# Set up a specific logger with our desired output level
my_logger = logging.getLogger('MyLogger')
my_logger.setLevel(logging.DEBUG)

# Add the log message handler to the logger
handler = logging.handlers.RotatingFileHandler(
          LOG_FILENAME, maxBytes=20, backupCount=5)

handler.setLevel(logging.CRITICAL)

my_logger.addHandler(handler)

Import Excel Spreadsheet Data to an EXISTING sql table?

If you would like a software tool to do this, you might like to check out this step-by-step guide:

"How to Validate and Import Excel spreadsheet to SQL Server database"

http://leansoftware.net/forum/en-us/help/excel-database-tasks/worked-examples/how-to-import-excel-spreadsheet-to-sql-server-data.aspx

What’s the best RESTful method to return total number of items in an object?

Sometimes frameworks (like $resource/AngularJS) require an array as a query result, and you can't really have a response like {count:10,items:[...]} in this case I store "count" in responseHeaders.

P. S. Actually you can do that with $resource/AngularJS, but it needs some tweaks.

Pandas index column title or name

df.index.name should do the trick.

Python has a dir function that let's you query object attributes. dir(df.index) was helpful here.

Extract a single (unsigned) integer from a string

You can use following function:

function extract_numbers($string)
{
   preg_match_all('/([\d]+)/', $string, $match);

   return $match[0];
}

Update ViewPager dynamically?

for those who still face the same problem which i faced before when i have a ViewPager with 7 fragments. the default for these fragments to load the English content from API service but the problem here that i want to change the language from settings activity and after finish settings activity i want ViewPager in main activity to refresh the fragments to match the language selection from the user and load the Arabic content if user chooses Arabic here what i did to work from the first time

1- You must use FragmentStatePagerAdapter as mentioned above.

2- on mainActivity i override the onResume and did the following

if (!(mPagerAdapter == null)) {
    mPagerAdapter.notifyDataSetChanged();
}

3-i overrided the getItemPosition() in mPagerAdapter and make it return POSITION_NONE.

@Override
public int getItemPosition(Object object) {
    return POSITION_NONE;
}

works like charm

Typescript: React event types

The problem is not with the Event type, but that the EventTarget interface in typescript only has 3 methods:

interface EventTarget {
    addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
    dispatchEvent(evt: Event): boolean;
    removeEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
}

interface SyntheticEvent {
    bubbles: boolean;
    cancelable: boolean;
    currentTarget: EventTarget;
    defaultPrevented: boolean;
    eventPhase: number;
    isTrusted: boolean;
    nativeEvent: Event;
    preventDefault(): void;
    stopPropagation(): void;
    target: EventTarget;
    timeStamp: Date;
    type: string;
}

So it is correct that name and value don't exist on EventTarget. What you need to do is to cast the target to the specific element type with the properties you need. In this case it will be HTMLInputElement.

update = (e: React.SyntheticEvent): void => {
    let target = e.target as HTMLInputElement;
    this.props.login[target.name] = target.value;
}

Also for events instead of React.SyntheticEvent, you can also type them as following: Event, MouseEvent, KeyboardEvent...etc, depends on the use case of the handler.

The best way to see all these type definitions is to checkout the .d.ts files from both typescript & react.

Also check out the following link for more explanations: Why is Event.target not Element in Typescript?

How to set the image from drawable dynamically in android?

imageView.setImageResource(R.drawable.picname);

How to Change Font Size in drawString Java

All you need to do is this: click on (window) on the dropdown manue on top of your screen. click on (Editor). click on (zoom in) as many times as you need to.

Bootstrap - 5 column layout

That's better, you can use any div count.

_x000D_
_x000D_
.col-xs-2{_x000D_
    background:#00f;_x000D_
    color:#FFF;_x000D_
}_x000D_
_x000D_
.col_item {_x000D_
    margin-left:4.166666667%_x000D_
}_x000D_
.col_item:first-child,_x000D_
.col_item:nth-child(5n+1) {_x000D_
    margin-left: 0;_x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<div class="container">_x000D_
    <div class="row" style="border: 1px solid red">_x000D_
        <div class="col-xs-2 col_item" id="p1">One</div>_x000D_
        <div class="col-xs-2 col_item" id="p2">Two</div>_x000D_
        <div class="col-xs-2 col_item" id="p3">Three</div>_x000D_
        <div class="col-xs-2 col_item" id="p4">Four</div>_x000D_
        <div class="col-xs-2 col_item" id="p5">Five</div>_x000D_
        <div class="col-xs-2 col_item" id="p5">One</div>_x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Encoding conversion in java

It is a whole lot easier if you think of unicode as a character set (which it actually is - it is very basically the numbered set of all known characters). You can encode it as UTF-8 (1-3 bytes per character depending) or maybe UTF-16 (2 bytes per character or 4 bytes using surrogate pairs).

Back in the mist of time Java used to use UCS-2 to encode the unicode character set. This could only handle 2 bytes per character and is now obsolete. It was a fairly obvious hack to add surrogate pairs and move up to UTF-16.

A lot of people think they should have used UTF-8 in the first place. When Java was originally written unicode had far more than 65535 characters anyway...

How do I set the maximum line length in PyCharm?

Here is screenshot of my Pycharm. Required settings is in following path: File -> Settings -> Editor -> Code Style -> General: Right margin (columns)

Pycharm 4 Settings Screenshot

Why check both isset() and !empty()

if we use same page to add/edit via submit button like below

<input type="hidden" value="<?echo $_GET['edit_id'];?>" name="edit_id">

then we should not use

isset($_POST['edit_id'])

bcoz edit_id is set all the time whether it is add or edit page , instead we should use check below condition

!empty($_POST['edit_id'])

What is the difference between Multiple R-squared and Adjusted R-squared in a single-variate least squares regression?

Note that, in addition to number of predictive variables, the Adjusted R-squared formula above also adjusts for sample size. A small sample will give a deceptively large R-squared.

Ping Yin & Xitao Fan, J. of Experimental Education 69(2): 203-224, "Estimating R-squared shrinkage in multiple regression", compares different methods for adjusting r-squared and concludes that the commonly-used ones quoted above are not good. They recommend the Olkin & Pratt formula.

However, I've seen some indication that population size has a much larger effect than any of these formulas indicate. I am not convinced that any of these formulas are good enough to allow you to compare regressions done with very different sample sizes (e.g., 2,000 vs. 200,000 samples; the standard formulas would make almost no sample-size-based adjustment). I would do some cross-validation to check the r-squared on each sample.

How to implement the ReLU function in Numpy

EDIT As jirassimok has mentioned below my function will change the data in place, after that it runs a lot faster in timeit. This causes the good results. It's some kind of cheating. Sorry for your inconvenience.

I found a faster method for ReLU with numpy. You can use the fancy index feature of numpy as well.

fancy index:

20.3 ms ± 272 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

>>> x = np.random.random((5,5)) - 0.5 
>>> x
array([[-0.21444316, -0.05676216,  0.43956365, -0.30788116, -0.19952038],
       [-0.43062223,  0.12144647, -0.05698369, -0.32187085,  0.24901568],
       [ 0.06785385, -0.43476031, -0.0735933 ,  0.3736868 ,  0.24832288],
       [ 0.47085262, -0.06379623,  0.46904916, -0.29421609, -0.15091168],
       [ 0.08381359, -0.25068492, -0.25733763, -0.1852205 , -0.42816953]])
>>> x[x<0]=0
>>> x
array([[ 0.        ,  0.        ,  0.43956365,  0.        ,  0.        ],
       [ 0.        ,  0.12144647,  0.        ,  0.        ,  0.24901568],
       [ 0.06785385,  0.        ,  0.        ,  0.3736868 ,  0.24832288],
       [ 0.47085262,  0.        ,  0.46904916,  0.        ,  0.        ],
       [ 0.08381359,  0.        ,  0.        ,  0.        ,  0.        ]])

Here is my benchmark:

import numpy as np
x = np.random.random((5000, 5000)) - 0.5
print("max method:")
%timeit -n10 np.maximum(x, 0)
print("max inplace method:")
%timeit -n10 np.maximum(x, 0,x)
print("multiplication method:")
%timeit -n10 x * (x > 0)
print("abs method:")
%timeit -n10 (abs(x) + x) / 2
print("fancy index:")
%timeit -n10 x[x<0] =0

max method:
241 ms ± 3.53 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
max inplace method:
38.5 ms ± 4 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
multiplication method:
162 ms ± 3.1 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
abs method:
181 ms ± 4.18 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
fancy index:
20.3 ms ± 272 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

How can I stream webcam video with C#?

If you want a "capture/streamer in a box" component, there are several out there as others have mentioned.

If you want to get down to the low-level control over it all, you'll need to use DirectShow as thealliedhacker points out. The best way to use DirectShow in C# is through the DirectShow.Net library - it wraps all of the DirectShow COM APIs and includes many useful shortcut functions for you.

In addition to capturing and streaming, you can also do recording, audio and video format conversions, audio and video live filters, and a whole lot of stuff.

Microsoft claims DirectShow is going away, but they have yet to release a new library or API that does everything that DirectShow provides. I suspect many of the latest things they have released are still DirectShow under the hood. Because of its status at Microsoft, there aren't a whole lot of books or references on it other than MSDN and what you can find on forums. Last year when we started a project using it, the best book on the subject - Programming Microsoft DirectShow - was out of print and going for around $350 for a used copy!

Add objects to an array of objects in Powershell

To append to an array, just use the += operator.

$Target += $TargetObject

Also, you need to declare $Target = @() before your loop because otherwise, it will empty the array every loop.

What is the difference between "JPG" / "JPEG" / "PNG" / "BMP" / "GIF" / "TIFF" Image?

Generally these are either:

Lossless compression Lossless compression algorithms reduce file size without losing image quality, though they are not compressed into as small a file as a lossy compression file. When image quality is valued above file size, lossless algorithms are typically chosen.

Lossy compression Lossy compression algorithms take advantage of the inherent limitations of the human eye and discard invisible information. Most lossy compression algorithms allow for variable quality levels (compression) and as these levels are increased, file size is reduced. At the highest compression levels, image deterioration becomes noticeable as "compression artifacting". The images below demonstrate the noticeable artifacting of lossy compression algorithms; select the thumbnail image to view the full size version.

Each format is different as described below:

JPEG JPEG (Joint Photographic Experts Group) files are (in most cases) a lossy format; the DOS filename extension is JPG (other OS might use JPEG). Nearly every digital camera can save images in the JPEG format, which supports 8 bits per color (red, green, blue) for a 24-bit total, producing relatively small files. When not too great, the compression does not noticeably detract from the image's quality, but JPEG files suffer generational degradation when repeatedly edited and saved. Photographic images may be better stored in a lossless non-JPEG format if they will be re-edited, or if small "artifacts" (blemishes caused by the JPEG's compression algorithm) are unacceptable. The JPEG format also is used as the image compression algorithm in many Adobe PDF files.

TIFF The TIFF (Tagged Image File Format) is a flexible format that normally saves 8 bits or 16 bits per color (red, green, blue) for 24-bit and 48-bit totals, respectively, using either the TIFF or the TIF filenames. The TIFF's flexibility is both blessing and curse, because no single reader reads every type of TIFF file. TIFFs are lossy and lossless; some offer relatively good lossless compression for bi-level (black&white) images. Some digital cameras can save in TIFF format, using the LZW compression algorithm for lossless storage. The TIFF image format is not widely supported by web browsers. TIFF remains widely accepted as a photograph file standard in the printing business. The TIFF can handle device-specific colour spaces, such as the CMYK defined by a particular set of printing press inks.

PNG The PNG (Portable Network Graphics) file format was created as the free, open-source successor to the GIF. The PNG file format supports truecolor (16 million colours) while the GIF supports only 256 colours. The PNG file excels when the image has large, uniformly coloured areas. The lossless PNG format is best suited for editing pictures, and the lossy formats, like JPG, are best for the final distribution of photographic images, because JPG files are smaller than PNG files. Many older browsers currently do not support the PNG file format, however, with Internet Explorer 7, all contemporary web browsers fully support the PNG format. The Adam7-interlacing allows an early preview, even when only a small percentage of the image data has been transmitted.

GIF GIF (Graphics Interchange Format) is limited to an 8-bit palette, or 256 colors. This makes the GIF format suitable for storing graphics with relatively few colors such as simple diagrams, shapes, logos and cartoon style images. The GIF format supports animation and is still widely used to provide image animation effects. It also uses a lossless compression that is more effective when large areas have a single color, and ineffective for detailed images or dithered images.

BMP The BMP file format (Windows bitmap) handles graphics files within the Microsoft Windows OS. Typically, BMP files are uncompressed, hence they are large; the advantage is their simplicity, wide acceptance, and use in Windows programs.

Use for Web Pages / Web Applications

The following is a brief summary for these image formats when using them with a web page / application.

  • PNG is great for IE6 and up (will require a small CSS patch to get transparency working well). Great for illustrations and photos.
  • JPG is great for photos online
  • GIF is good for illustrations when you do not wish to move to PNG
  • BMP shouldn't be used online within web pages - wastes bandwidth


  • Source: Image File Formats

    Optional query string parameters in ASP.NET Web API

    This issue has been fixed in the regular release of MVC4. Now you can do:

    public string GetFindBooks(string author="", string title="", string isbn="", string  somethingelse="", DateTime? date= null) 
    {
        // ...
    }
    

    and everything will work out of the box.

    Changing datagridview cell color based on condition

    Surprised no one mentioned a simple if statement can make sure your loop only gets executed once per format (on the first column, of the first row).

        private void dgv_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            // once per format
            if (e.ColumnIndex == 0 && e.RowIndex == 0)
            {
                foreach (DataGridViewRow row in dgv.Rows)
                    if (row != null)
                        row.DefaultCellStyle.BackColor = Color.Red;
            }
        }
    

    How to control border height?

    I want to control the height of the border. How could I do this?

    You can't. CSS borders will always span across the full height / width of the element.

    One workaround idea would be to use absolute positioning (which can accept percent values) to place the border-carrying element inside one of the two divs. For that, you would have to make the element position: relative.

    git - Server host key not cached

    The message means that the host key of origin is not present in your trusted hosts file.

    To get around this, open a plain SSH connection to origin and SSH will ask you if you want to trust the remote host (from the Git console):

    $ ssh 127.0.0.1
    The authenticity of host '127.0.0.1 (127.0.0.1)' can't be established.
    RSA key fingerprint is <FINGERPRINT>.
    Are you sure you want to continue connecting (yes/no)?
    

    If you trust the remote host (i.e. type yes), SSH will add its key to the list of known hosts.

    After that, you should be able to do your git push origin.

    As an alternative, you could also manually add the key of origin to .ssh/known_hosts but this requires that you adhere to the format of the known_hosts file as described in the man page of sshd (Section AUTHORIZED_KEYS FILE FORMAT).

    How to execute UNION without sorting? (SQL)

    SELECT *, 1 AS sort_order
      FROM table1
     EXCEPT 
    SELECT *, 1 AS sort_order
      FROM table2
    UNION
    SELECT *, 1 AS sort_order
      FROM table1
     INTERSECT 
    SELECT *, 1 AS sort_order
      FROM table2
    UNION
    SELECT *, 2 AS sort_order
      FROM table2
     EXCEPT 
    SELECT *, 2 AS sort_order
      FROM table1
    ORDER BY sort_order;
    

    But the real answer is: other than the ORDER BY clause, the sort order will by arbitrary and not guaranteed.

    jQuery UI Color Picker

    Make sure you have jQuery UI base and the color picker widget included on your page (as well as a copy of jQuery 1.3):

    <link rel="stylesheet" href="http://dev.jquery.com/view/tags/ui/latest/themes/flora/flora.all.css" type="text/css" media="screen" title="Flora (Default)">
    
    <script type="text/javascript" src="http://dev.jquery.com/view/tags/ui/latest/ui/ui.core.js"></script>
    
    <script type="text/javascript" src="http://dev.jquery.com/view/tags/ui/latest/ui/ui.colorpicker.js"></script>
    

    If you have those included, try posting your source so we can see what's going on.

    How to add spacing between columns?

    You can achieve spacing between columns using the col-xs-* classes,within in a col-xs-* div coded below. The spacing is consistent so that all of your columns line up correctly. To get even spacing and column size I would do the following:

    <div class="container">
        <div class="col-md-3 ">
            <div class="col-md-12 well">
                Some Content..
            </div>
        </div>
        <div class="col-md-3 ">
            <div class="col-md-12 well">
                Some Second Content..
            </div>
        </div>
        <div class="col-md-3 ">
            <div class="col-md-12 well">
                Some Second Content..
            </div>
        </div>
        <div class="col-md-3 ">
            <div class="col-md-12 well">
                Some Second Content..
            </div>
        </div>
        <div class="col-md-3 ">
            <div class="col-md-12 well">
                Some Second Content..
            </div>
        </div>
        <div class="col-md-3 ">
            <div class="col-md-12 well">
                Some Second Content..
            </div>
        </div>
        <div class="col-md-3 ">
            <div class="col-md-12 well">
                Some Second Content..
            </div>
        </div>
        <div class="col-md-3 ">
            <div class="col-md-12 well">
                Some Second Content..
            </div>
        </div>
    </div>
    

    Can not deserialize instance of java.util.ArrayList out of VALUE_STRING

    This is the solution for my old question:

    I implemented my own ContextResolver in order to enable the DeserializationConfig.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY feature.

    package org.lig.hadas.services.mapper;
    
    import javax.ws.rs.Produces;
    import javax.ws.rs.core.MediaType;
    import javax.ws.rs.ext.ContextResolver;
    import javax.ws.rs.ext.Provider;
    
    import org.codehaus.jackson.map.DeserializationConfig;
    import org.codehaus.jackson.map.ObjectMapper;
    
    @Produces(MediaType.APPLICATION_JSON)
    @Provider
    public class ObjectMapperProvider implements ContextResolver<ObjectMapper>
    {
       ObjectMapper mapper;
    
       public ObjectMapperProvider(){
           mapper = new ObjectMapper();
           mapper.configure(DeserializationConfig.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
       }
       @Override
       public ObjectMapper getContext(Class<?> type) {
           return mapper;
       }
    }
    

    And in the web.xml I registered my package into the servlet definition...

    <servlet>
        <servlet-name>...</servlet-name>
        <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
        <init-param>
            <param-name>com.sun.jersey.config.property.packages</param-name>
            <param-value>...;org.lig.hadas.services.mapper</param-value>        
        </init-param>
        ...
    </servlet>
    

    ... all the rest is transparently done by jersey/jackson.

    What is the difference between linear regression and logistic regression?

    In linear regression, the outcome (dependent variable) is continuous. It can have any one of an infinite number of possible values. In logistic regression, the outcome (dependent variable) has only a limited number of possible values.

    For instance, if X contains the area in square feet of houses, and Y contains the corresponding sale price of those houses, you could use linear regression to predict selling price as a function of house size. While the possible selling price may not actually be any, there are so many possible values that a linear regression model would be chosen.

    If, instead, you wanted to predict, based on size, whether a house would sell for more than $200K, you would use logistic regression. The possible outputs are either Yes, the house will sell for more than $200K, or No, the house will not.

    Programmatically go back to the previous fragment in the backstack

    Try below code:

    @Override
        public void onBackPressed() {
            Fragment myFragment = getSupportFragmentManager().findFragmentById(R.id.container);
            if (myFragment != null && myFragment instanceof StepOneFragment) {
                finish();
            } else {
                if (getSupportFragmentManager().getBackStackEntryCount() > 0) {
                    getSupportFragmentManager().popBackStack();
                } else {
                    super.onBackPressed();
                }
            }
        }
    

    How to dump only specific tables from MySQL?

    If you're in local machine then use this command

    /usr/local/mysql/bin/mysqldump -h127.0.0.1 --port = 3306 -u [username] -p [password] --databases [db_name] --tables [tablename] > /to/path/tablename.sql;
    

    For remote machine, use below one

    /usr/local/mysql/bin/mysqldump -h [remoteip] --port = 3306 -u [username] -p [password] --databases [db_name] --tables [tablename] > /to/path/tablename.sql;
    

    C# Telnet Library

    I ended up finding MinimalistTelnet and adapted it to my uses. I ended up needing to be able to heavily modify the code due to the unique** device that I am attempting to attach to.

    ** Unique in this instance can be validly interpreted as brain-dead.

    Check if a value is in an array or not with Excel VBA

    You want to check whether Examples exists in Range("A1").Value If it fails then to check Example right? I think mycode will work perfect. Please check.

    Sub test()
    Dim string1 As String, string2 As String
    string1 = "Examples"
    string2 = "Example"
    If InStr(1, Range("A1").Value, string1) > 0 Then
        x = 1
    ElseIf InStr(1, Range("A1").Value, string2) > 0 Then
        x = 2
    End If
    

    End Sub

    Your content must have a ListView whose id attribute is 'android.R.id.list'

    Rename the id of your ListView like this,

    <ListView android:id="@android:id/list"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"/>
    

    Since you are using ListActivity your xml file must specify the keyword android while mentioning to a ID.

    If you need a custom ListView then instead of Extending a ListActivity, you have to simply extend an Activity and should have the same id without the keyword android.

    PHP Regex to check date is in YYYY-MM-DD format

    It's probably better to use another mechanism for this.

    The modern solution, with DateTime:

    $dt = DateTime::createFromFormat("Y-m-d", $date);
    return $dt !== false && !array_sum($dt::getLastErrors());
    

    This validates the input too: $dt !== false ensures that the date can be parsed with the specified format and the array_sum trick is a terse way of ensuring that PHP did not do "month shifting" (e.g. consider that January 32 is February 1). See DateTime::getLastErrors() for more information.

    Old-school solution with explode and checkdate:

    list($y, $m, $d) = array_pad(explode('-', $date, 3), 3, 0);
    return ctype_digit("$y$m$d") && checkdate($m, $d, $y);
    

    This validates that the input is a valid date as well. You can do that with a regex of course, but it's going to be more fuss -- and February 29 cannot be validated with a regex at all.

    The drawback of this approach is that you have to be very careful to reject all possible "bad" inputs while not emitting a notice under any circumstances. Here's how:

    • explode is limited to return 3 tokens (so that if the input is "1-2-3-4", $d will become "3-4")
    • ctype_digit is used to make sure that the input does not contain any non-numeric characters (apart from the dashes)
    • array_pad is used (with a default value that will cause checkdate to fail) to make sure that enough elements are returned so that if the input is "1-2" list() will not emit a notice

    CORS: Cannot use wildcard in Access-Control-Allow-Origin when credentials flag is true

    If you want to allow all origins and keep credentials true, this worked for me:

    app.use(cors({
      origin: function(origin, callback){
        return callback(null, true);
      },
      optionsSuccessStatus: 200,
      credentials: true
    }));
    

    Is there a naming convention for git repositories?

    If you plan to create a PHP package you most likely want to put in on Packagist to make it available for other with composer. Composer has the as naming-convention to use vendorname/package-name-is-lowercase-with-hyphens.

    If you plan to create a JS package you probably want to use npm. One of their naming conventions is to not permit upper case letters in the middle of your package name.

    Therefore, I would recommend for PHP and JS packages to use lowercase-with-hyphens and name your packages in composer or npm identically to your package on GitHub.

    How to select date from datetime column?

    simple and best way to use date function

    example

    SELECT * FROM 
    data 
    WHERE date(datetime) = '2009-10-20' 
    

    OR

    SELECT * FROM 
    data 
    WHERE date(datetime ) >=   '2009-10-20'  && date(datetime )  <= '2009-10-20'
    

    Parsing Query String in node.js

    There's also the QueryString module's parse() method:

    var http = require('http'),
        queryString = require('querystring');
    
    http.createServer(function (oRequest, oResponse) {
    
        var oQueryParams;
    
        // get query params as object
        if (oRequest.url.indexOf('?') >= 0) {
            oQueryParams = queryString.parse(oRequest.url.replace(/^.*\?/, ''));
    
            // do stuff
            console.log(oQueryParams);
        }
    
        oResponse.writeHead(200, {'Content-Type': 'text/plain'});
        oResponse.end('Hello world.');
    
    }).listen(1337, '127.0.0.1');
    

    "Continue" (to next iteration) on VBScript

    Implement the iteration as a recursive function.

    Function Iterate( i , N )
      If i == N Then
          Exit Function
      End If
      [Code]
      If Condition1 Then
         Call Iterate( i+1, N );
         Exit Function
      End If
    
      [Code]
      If Condition2 Then
         Call Iterate( i+1, N );
         Exit Function
      End If
      Call Iterate( i+1, N );
    End Function
    

    Start with a call to Iterate( 1, N )