Programs & Examples On #Didreceivememorywarning

didReceiveMemoryWarning is a method called by the iOS system to tell your app to deallocate recreate-able assets when device memory reaches a critical level.

Command failed due to signal: Segmentation fault: 11

I got this error when getting a value from NSUserDefaults. The following gives error:

let arr = defaults.objectForKey("myArray")

What fixed the error was to cast the type to the correct type stored in NSUserDefaults. The following gives no error:

let arr = defaults.objectForKey("myArray") as! Array<String>

How to allow user to pick the image with Swift?

If you just want let the user choose image with UIImagePickerController use this code:

import UIKit


class ViewController: UIViewController, UINavigationControllerDelegate, UIImagePickerControllerDelegate {

    @IBOutlet var imageView: UIImageView!
    @IBOutlet var chooseBuuton: UIButton!
    var imagePicker = UIImagePickerController()

    @IBAction func btnClicked() {

        if UIImagePickerController.isSourceTypeAvailable(.savedPhotosAlbum){
            print("Button capture")

            imagePicker.delegate = self
            imagePicker.sourceType = .savedPhotosAlbum
            imagePicker.allowsEditing = false

            present(imagePicker, animated: true, completion: nil)
        }
    }

    func imagePickerController(picker: UIImagePickerController!, didFinishPickingImage image: UIImage!, editingInfo: NSDictionary!){
        self.dismiss(animated: true, completion: { () -> Void in

        })

        imageView.image = image
    }
}

Xcode error - Thread 1: signal SIGABRT

You are trying to load a XIB named DetailViewController, but no such XIB exists or it's not member of your current target.

Connection attempt failed with "ECONNREFUSED - Connection refused by server"

Use port number 22 (for sftp) instead of 21 (normal ftp). Solved this problem for me.

How to sum a variable by group

Several years later, just to add another simple base R solution that isn't present here for some reason- xtabs

xtabs(Frequency ~ Category, df)
# Category
# First Second  Third 
#    30      5     34 

Or if you want a data.frame back

as.data.frame(xtabs(Frequency ~ Category, df))
#   Category Freq
# 1    First   30
# 2   Second    5
# 3    Third   34

Add swipe to delete UITableViewCell

It's new feature in iOS11 and Swift 4.

Reference link :

Trailing Swipe :

@available(iOS 11.0, *)
override func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
    let delete = UIContextualAction(style: .destructive, title: "Delete") { (action, sourceView, completionHandler) in
        print("index path of delete: \(indexPath)")
        completionHandler(true)
    }

    let rename = UIContextualAction(style: .normal, title: "Edit") { (action, sourceView, completionHandler) in
        print("index path of edit: \(indexPath)")
        completionHandler(true)
    }
    let swipeActionConfig = UISwipeActionsConfiguration(actions: [rename, delete])
    swipeActionConfig.performsFirstActionWithFullSwipe = false
    return swipeActionConfig
}

enter image description here

Which port(s) does XMPP use?

The official ports (TCP:5222 and TCP:5269) are listed in RFC 6120. Contrary to the claims of a previous answer, XEP-0174 does not specify a port. Thus TCP:5298 might be customary for Link-Local XMPP, but is not official.

You can use other ports than the reserved ones, though: You can make your DNS SRV record point to any machine and port you like.

File transfers (XEP-0234) are these days handled using Jingle (XEP-0166). The same goes for RTP sessions (XEP-0167). They do not specify ports, though, since Jingle negotiates the creation of the data stream between the XMPP clients, but the actual data is then transferred by other means (e.g. RTP) through that stream (i.e. not usually through the XMPP server, even though in-band transfers are possible). Beware that Jingle is comprised of several XEPs, so make sure to have a look at the whole list of XMPP extensions.

How to call stopservice() method of Service class from the calling activity class

That looks like it should stop the service when you uncheck the checkbox. Are there any exceptions in the log? stopService returns a boolean indicating whether or not it was able to stop the service.

If you are starting your service by Intents, then you may want to extend IntentService instead of Service. That class will stop the service on its own when it has no more work to do.

AutoService

class AutoService extends IntentService {
     private static final String TAG = "AutoService";
     private Timer timer;    
     private TimerTask task;

     public onCreate() {
          timer = new Timer();
          timer = new TimerTask() {
            public void run() 
            {
                System.out.println("done");
            }
          }
     }

     protected void onHandleIntent(Intent i) {
        Log.d(TAG, "onHandleIntent");     

        int delay = 5000; // delay for 5 sec.
        int period = 5000; // repeat every sec.


        timer.scheduleAtFixedRate(timerTask, delay, period);
     }

     public boolean stopService(Intent name) {
        // TODO Auto-generated method stub
        timer.cancel();
        task.cancel();
        return super.stopService(name);
    }

}

Working around MySQL error "Deadlock found when trying to get lock; try restarting transaction"

Note that if you use SELECT FOR UPDATE to perform a uniqueness check before an insert, you will get a deadlock for every race condition unless you enable the innodb_locks_unsafe_for_binlog option. A deadlock-free method to check uniqueness is to blindly insert a row into a table with a unique index using INSERT IGNORE, then to check the affected row count.

add below line to my.cnf file

innodb_locks_unsafe_for_binlog = 1

#

1 - ON
0 - OFF

#

Setting Windows PowerShell environment variables

If, some time during a PowerShell session, you need to append to the PATH environment variable temporarily, you can do it this way:

$env:Path += ";C:\Program Files\GnuWin32\bin"

How to get a div to resize its height to fit container?

Simple Way

You can achieve this with setting both the top and bottom attributes of the nav to 0 and the position: absolute. Set the container to position: relative.

See how this is done

Modern Way (Flexbox)

IE11+ and all modern browsers support flexbox.

.container {
  display: flex;
  flex-direction: column;
}

.child {
  flex-grow: 1;
}

Bootstrap 3 - 100% height of custom div inside column

The original question is about Bootstrap 3 and that supports IE8 and 9 so Flexbox would be the best option but it's not part of my answer due the lack of support, see http://caniuse.com/#feat=flexbox and toggle the IE box. Pretty bad, eh?

2 ways:

1. Display-table: You can muck around with turning the row into a display:table and the col- into display:table-cell. It works buuuut the limitations of tables are there, among those limitations are the push and pull and offsets won't work. Plus, I don't know where you're using this -- at what breakpoint. You should make the image full width and wrap it inside another container to put the padding on there. Also, you need to figure out the design on mobile, this is for 768px and up. When I use this, I redeclare the sizes and sometimes I stick importants on them because tables take on the width of the content inside them so having the widths declared again helps this. You will need to play around. I also use a script but you have to change the less files to use it or it won't work responsively.


DEMO: http://jsbin.com/EtUBujI/2

  .row.table-row > [class*="col-"].custom {
    background-color: lightgrey;
    text-align: center;
  }


@media (min-width: 768px) {
  
  img.img-fluid {width:100%;}

  .row.table-row {display:table;width:100%;margin:0 auto;}

  .row.table-row > [class*="col-"] {
    float:none;
    float:none;
    display:table-cell;
    vertical-align:top;
  }

  .row.table-row > .col-sm-11 {
    width: 91.66666666666666%;
  }
  .row.table-row > .col-sm-10 {
    width: 83.33333333333334%;
  }
  .row.table-row > .col-sm-9 {
    width: 75%;
  }
  .row.table-row > .col-sm-8 {
    width: 66.66666666666666%;
  }
  .row.table-row > .col-sm-7 {
    width: 58.333333333333336%;
  }
  .row.table-row > .col-sm-6 {
    width: 50%;
  }
  .col-sm-5 {
    width: 41.66666666666667%;
  }
  .col-sm-4 {
    width: 33.33333333333333%;
  }
  .row.table-row > .col-sm-3 {
    width: 25%;
  }
  .row.table-row > .col-sm-2 {
    width: 16.666666666666664%;
  }
  .row.table-row > .col-sm-1 {
    width: 8.333333333333332%;
  }


}

HTML

<div class="container">
    <div class="row table-row">
        <div class="col-sm-4 custom">
                100% height to make equal to ->
        </div>
        <div class="col-sm-8 image-col">
            <img src="http://placehold.it/600x400/B7AF90/FFFFFF&text=image+1" class="img-fluid">
        </div>
    </div>
</div>

2. Absolute bg div

DEMO: http://jsbin.com/aVEsUmig/2/edit

DEMO with content above and below: http://jsbin.com/aVEsUmig/3


.content {
        text-align: center;
        padding: 10px;
        background: #ccc;

}


@media (min-width:768px) { 
    .my-row {
        position: relative;
        height: 100%;
        border: 1px solid red;
        overflow: hidden;
    }
    .img-fluid {
        width: 100%
    }
    .row.my-row > [class*="col-"] {
        position: relative
    }
    .background {
        position: absolute;
        padding-top: 200%;
        left: 0;
        top: 0;
        width: 100%;
        background: #ccc;
    }
    .content {
        position: relative;
        z-index: 1;
        width: 100%;
        text-align: center;
        padding: 10px;
    }

}

HTML

<div class="container">
  
    <div class="row my-row">
      
        <div class="col-sm-6">
          
        <div class="content">
          This is inside a relative positioned z-index: 1 div
          </div>

         <div class="background"><!--empty bg-div--></div>
        </div>
      
        <div class="col-sm-6 image-col">
            <img src="http://placehold.it/200x400/777777/FFFFFF&text=image+1" class="img-fluid">
        </div>
      
    </div>
   
</div>
  

How to insert image in mysql database(table)?

I have three answers to this question:

  1. It is against user experience UX best practice to use BLOB and CLOB data types in string and retrieving binary data from an SQL database thus it is advised that you use the technique that involves storing the URL for the image( or any Binary file in the database). This URL will help the user application to retrieve and use this binary file.

  2. Second the BLOB and CLOB data types are only available to a number of SQL versions thus functions such as LOAD_FILE or the datatypes themselves could miss in some versions.

  3. Third DON'T USE BLOB OR CLOB. Store the URL; let the user application access the binary file from a folder in the project directory.

Change onClick attribute with javascript

Well, just do this and your problem is solved :

document.getElementById('buttonLED'+id).setAttribute('onclick','writeLED(1,1)')

Have a nice day XD

Is it ok to use `any?` to check if an array is not empty?

any? isn't the same as not empty? in some cases.

>> [nil, 1].any?
=> true
>> [nil, nil].any?
=> false

From the documentation:

If the block is not given, Ruby adds an implicit block of {|obj| obj} (that is any? will return true if at least one of the collection members is not false or nil).

Installed Ruby 1.9.3 with RVM but command line doesn't show ruby -v

I ran into a similar issue today - my ruby version didn't match my rvm installs.

> ruby -v
ruby 2.0.0p481

> rvm list
rvm rubies
   ruby-2.1.2 [ x86_64 ]
=* ruby-2.2.1 [ x86_64 ]
   ruby-2.2.3 [ x86_64 ]

Also, rvm current failed.

> rvm current
Warning! PATH is not properly set up, '/Users/randallreed/.rvm/gems/ruby-2.2.1/bin' is not at first place...

The error message recommended this useful command, which resolved the issue for me:

> rvm get stable --auto-dotfiles

PHP max_input_vars

Yes, add it to the php.ini, restart apache and it should work.

You can test it on the fly if you want to with ini_set("max_input_vars",100)

C++ terminate called without an active exception

How to reproduce that error:

#include <iostream>
#include <stdlib.h>
#include <string>
#include <thread>
using namespace std;
void task1(std::string msg){
  cout << "task1 says: " << msg;
}
int main() { 
  std::thread t1(task1, "hello"); 
  return 0;
}

Compile and run:

el@defiant ~/foo4/39_threading $ g++ -o s s.cpp -pthread -std=c++11
el@defiant ~/foo4/39_threading $ ./s
terminate called without an active exception
Aborted (core dumped)

You get that error because you didn't join or detach your thread.

One way to fix it, join the thread like this:

#include <iostream>
#include <stdlib.h>
#include <string>
#include <thread>
using namespace std;
void task1(std::string msg){
  cout << "task1 says: " << msg;
}
int main() { 
  std::thread t1(task1, "hello"); 
  t1.join();
  return 0;
}

Then compile and run:

el@defiant ~/foo4/39_threading $ g++ -o s s.cpp -pthread -std=c++11
el@defiant ~/foo4/39_threading $ ./s
task1 says: hello

The other way to fix it, detach it like this:

#include <iostream>
#include <stdlib.h>
#include <string>
#include <unistd.h>
#include <thread>
using namespace std;
void task1(std::string msg){
  cout << "task1 says: " << msg;
}
int main() 
{ 
     {

        std::thread t1(task1, "hello"); 
        t1.detach();

     } //thread handle is destroyed here, as goes out of scope!

     usleep(1000000); //wait so that hello can be printed.
}

Compile and run:

el@defiant ~/foo4/39_threading $ g++ -o s s.cpp -pthread -std=c++11
el@defiant ~/foo4/39_threading $ ./s
task1 says: hello

Read up on detaching C++ threads and joining C++ threads.

Using ping in c#

private async void Ping_Click(object sender, RoutedEventArgs e)
{
    Ping pingSender = new Ping();
    string host = @"stackoverflow.com";
    await Task.Run(() =>{
         PingReply reply = pingSender.Send(host);
         if (reply.Status == IPStatus.Success)
         {
            Console.WriteLine("Address: {0}", reply.Address.ToString());
            Console.WriteLine("RoundTrip time: {0}", reply.RoundtripTime);
            Console.WriteLine("Time to live: {0}", reply.Options.Ttl);
            Console.WriteLine("Don't fragment: {0}", reply.Options.DontFragment);
            Console.WriteLine("Buffer size: {0}", reply.Buffer.Length);
         }
         else
         {
            Console.WriteLine("Address: {0}", reply.Status);
         }
   });           
}

Move view with keyboard using Swift

The validated answer doesn't take in account the textfield position and has some bug (double displacement, never come back the primary position, displacement even if the texfield is on top of the view...)

The idea is :

  • to get the focus TextField absolute Y position
  • to get the keyboard height
  • to get the ScreenHeight
  • Then calculate the distance between keyboard position and textfield (if < 0 -> move up the view)
  • to use UIView.transform instead of UIView.frame.origin.y -= .., cause it's easier to come back to original position with UIView.transform = .identity

then we will be able to move the view only if necessary and of the specific displacement in oder to have the focused texField just over the keyboard

Here is the code :

Swift 4

class ViewController: UIViewController, UITextFieldDelegate {

var textFieldRealYPosition: CGFloat = 0.0

override func viewDidLoad() {
    super.viewDidLoad()

    NotificationCenter.default.addObserver(self, selector: #selector(VehiculeViewController.keyboardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(VehiculeViewController.keyboardWillHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil)

  // Delegate all textfields

}


@objc func keyboardWillShow(notification: NSNotification) {
    if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
        let distanceBetweenTextfielAndKeyboard = self.view.frame.height - textFieldRealYPosition - keyboardSize.height
        if distanceBetweenTextfielAndKeyboard < 0 {
            UIView.animate(withDuration: 0.4) {
                self.view.transform = CGAffineTransform(translationX: 0.0, y: distanceBetweenTextfielAndKeyboard)
            }
        }
    }
}


@objc func keyboardWillHide(notification: NSNotification) {
    UIView.animate(withDuration: 0.4) {
        self.view.transform = .identity
    }
}


func textFieldDidBeginEditing(_ textField: UITextField) {
  textFieldRealYPosition = textField.frame.origin.y + textField.frame.height
  //take in account all superviews from textfield and potential contentOffset if you are using tableview to calculate the real position
}

}

Match multiline text using regular expression

str.matches(regex) behaves like Pattern.matches(regex, str) which attempts to match the entire input sequence against the pattern and returns

true if, and only if, the entire input sequence matches this matcher's pattern

Whereas matcher.find() attempts to find the next subsequence of the input sequence that matches the pattern and returns

true if, and only if, a subsequence of the input sequence matches this matcher's pattern

Thus the problem is with the regex. Try the following.

String test = "User Comments: This is \t a\ta \ntest\n\n message \n";

String pattern1 = "User Comments: [\\s\\S]*^test$[\\s\\S]*";
Pattern p = Pattern.compile(pattern1, Pattern.MULTILINE);
System.out.println(p.matcher(test).find());  //true

String pattern2 = "(?m)User Comments: [\\s\\S]*^test$[\\s\\S]*";
System.out.println(test.matches(pattern2));  //true

Thus in short, the (\\W)*(\\S)* portion in your first regex matches an empty string as * means zero or more occurrences and the real matched string is User Comments: and not the whole string as you'd expect. The second one fails as it tries to match the whole string but it can't as \\W matches a non word character, ie [^a-zA-Z0-9_] and the first character is T, a word character.

how to generate web service out of wsdl

step-1

open -> Visual Studio 2017 Developer Command Prompt

step-2

WSDL.exe  /OUT:myFile.cs WSDLURL  /Language:CS /serverInterface
  • /serverInterface (this to create interface from wsdl file)
  • WSDL.exe (this use to create class from wsdl. this comes with .net
  • /OUT: (output file name)

step-2

create new "Web service Project"

step-3

add -> web service

step-4

copy all code from myFile.cs (generated above) except "using classes" eg:

 /// <remarks/>
    [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.6.1055.0")]
    [System.Web.Services.WebServiceBindingAttribute(Name="calculoterServiceSoap",Namespace="http://tempuri.org/")]

public interface ICalculoterServiceSoap {

    /// <remarks/>
    [System.Web.Services.WebMethodAttribute()]
    [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://tempuri.org/addition", RequestNamespace="http://tempuri.org/", ResponseNamespace="http://tempuri.org/", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
    string addition(int firtNo, int secNo);
}

step-4

past it into your webService.asmx.cs (inside of namespace) created above in step-2

step-5

inherit the interface class with your web service class eg:

public class WebService2 : ICalculoterServiceSoap

grep for special characters in Unix

You could try removing any alphanumeric characters and space. And then use -n will give you the line number. Try following:

grep -vn "^[a-zA-Z0-9 ]*$" application.log

SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified

We got the same issue recently. We found out that the code is looking for the connection string named "LocalSqlServer" in the machine.confg file. We added this line and it is working fine.

Array functions in jQuery

There's a plugin for jQuery called 'rich array' discussed in Rich Array jQuery plugin .

How to execute INSERT statement using JdbcTemplate class from Spring Framework

If you use spring-boot, you don't need to create a DataSource class, just specify the data url/username/password/driver in application.properties, then you can simply @Autowired it.

@Repository
public class JdbcRepository {

    private final JdbcTemplate jdbcTemplate;

    @Autowired
    public DynamicRepository(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    public void insert() {
        jdbcTemplate.update("INSERT INTO BOOK (name, description) VALUES ('book name', 'book description')");
    }
}

Example of application.properties:

#Basic Spring Boot Config for Oracle
spring.datasource.url=jdbc:oracle:thin:@(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=YourHostIP)(PORT=YourPort))(CONNECT_DATA=(SERVER=dedicated)(SERVICE_NAME=YourServiceName)))
spring.datasource.username=username
spring.datasource.password=password
spring.datasource.driver-class-name=oracle.jdbc.OracleDriver

#hibernate config
spring.jpa.database-platform=org.hibernate.dialect.Oracle10gDialect

Then add the driver and connection pool dependencies in pom.xml

<dependency>
    <groupId>com.oracle</groupId>
    <artifactId>ojdbc7</artifactId>
    <version>12.1.0.1</version>
</dependency>

<!-- HikariCP connection pool -->
<dependency>
    <groupId>com.zaxxer</groupId>
    <artifactId>HikariCP</artifactId>
    <version>2.6.0</version>
</dependency>

See the official doc for more details.

How do you get/set media volume (not ringtone volume) in Android?

Instead of AudioManager.STREAM_RING you shoul use AudioManager.STREAM_MUSIC This question has already discussed here.

Group array items using object

This gives you unique colors, if you do not want duplicate values for color

_x000D_
_x000D_
var arr = [_x000D_
  {group: "one", color: "red"},_x000D_
  {group: "two", color: "blue"},_x000D_
  {group: "one", color: "red"},_x000D_
  {group: "two", color: "blue"},_x000D_
  {group: "one", color: "green"},_x000D_
  {group: "one", color: "black"}_x000D_
]_x000D_
_x000D_
var arra = [...new Set(arr.map(x => x.group))]_x000D_
_x000D_
let reformattedArray = arra.map(obj => {_x000D_
   let rObj = {}_x000D_
   rObj['color'] = [...new Set(arr.map(x => x.group == obj ? x.color:false ))]_x000D_
       .filter(x => x != false)_x000D_
   rObj['group'] = obj_x000D_
   return rObj_x000D_
})_x000D_
console.log(reformattedArray)
_x000D_
_x000D_
_x000D_

Android ListView Text Color

  1. Create a styles file, for example: my_styles.xml and save it in res/values.
  2. Add the following code:

    <?xml version="1.0" encoding="utf-8"?>
    <resources>
    
    <style name="ListFont" parent="@android:style/Widget.ListView">
        <item name="android:textColor">#FF0000</item>
        <item name="android:typeface">sans</item>
    </style>
    
    </resources>
    
  3. Add your style to your Activity definition in your AndroidManifest.xml as an android:theme attribute, and assign as value the name of the style you created. For example:

    <activity android:name="your.activityClass" android:theme="@style/ListFont">
    

NOTE: the Widget.ListView comes from here. Also check this.

Django, creating a custom 500/404 error page

Under your main views.py add your own custom implementation of the following two views, and just set up the templates 404.html and 500.html with what you want to display.

With this solution, no custom code needs to be added to urls.py

Here's the code:

from django.shortcuts import render_to_response
from django.template import RequestContext


def handler404(request, *args, **argv):
    response = render_to_response('404.html', {},
                                  context_instance=RequestContext(request))
    response.status_code = 404
    return response


def handler500(request, *args, **argv):
    response = render_to_response('500.html', {},
                                  context_instance=RequestContext(request))
    response.status_code = 500
    return response

Update

handler404 and handler500 are exported Django string configuration variables found in django/conf/urls/__init__.py. That is why the above config works.

To get the above config to work, you should define the following variables in your urls.py file and point the exported Django variables to the string Python path of where these Django functional views are defined, like so:

# project/urls.py

handler404 = 'my_app.views.handler404'
handler500 = 'my_app.views.handler500'

Update for Django 2.0

Signatures for handler views were changed in Django 2.0: https://docs.djangoproject.com/en/2.0/ref/views/#error-views

If you use views as above, handler404 will fail with message:

"handler404() got an unexpected keyword argument 'exception'"

In such case modify your views like this:

def handler404(request, exception, template_name="404.html"):
    response = render_to_response(template_name)
    response.status_code = 404
    return response

Can I have an IF block in DOS batch file?

I ran across this article in the results returned by a search related to the IF command in a batch file, and I couldn't resist the opportunity to correct the misconception that IF blocks are limited to single commands. Following is a portion of a production Windows NT command script that runs daily on the machine on which I am composing this reply.

    if "%COPYTOOL%" equ "R" (
    WWLOGGER.exe "%APPDATA%\WizardWrx\%~n0.LOG" "Using RoboCopy to make a backup of %USERPROFILE%\My Documents\Outlook Files\*"
    %TOOLPATH% %SRCEPATH% %DESTPATH% /copyall %RCLOGSTR% /m /np /r:0 /tee
    C:\BIN\ExitCodeMapper.exe C:\BIN\ExitCodeMapper.INI[Robocopy] %TEMP%\%~n0.TMP %ERRORLEVEL%
) else (
    WWLOGGER.exe "%APPDATA%\WizardWrx\%~n0.LOG" "Using XCopy to make a backup of %USERPROFILE%\My Documents\Outlook Files\*"
    call %TOOLPATH%  "%USERPROFILE%\My Documents\Outlook Files\*" "%USERPROFILE%\My Documents\Outlook Files\_backups" /f /m /v /y
    C:\BIN\ExitCodeMapper.exe C:\BIN\ExitCodeMapper.INI[Xcopy] %TEMP%\%~n0.TMP %ERRORLEVEL%
)

Perhaps blocks of two or more lines applies exclusively to Windows NT command scripts (.CMD files), because a search of the production scripts directory of an application that is restricted to old school batch (.BAT) files, revealed only one-command blocks. Since the application has gone into extended maintenance (meaning that I am not actively involved in supporting it), I can't say whether that is because I didn't need more than one line, or that I couldn't make them work.

Regardless, if the latter is true, there is a simple workaround; move the multiple lines into either a separate batch file or a batch file subroutine. I know that the latter works in both kinds of scripts.

How to use concerns in Rails 4

I felt most of the examples here demonstrated the power of module rather than how ActiveSupport::Concern adds value to module.

Example 1: More readable modules.

So without concerns this how a typical module will be.

module M
  def self.included(base)
    base.extend ClassMethods
    base.class_eval do
      scope :disabled, -> { where(disabled: true) }
    end
  end

  def instance_method
    ...
  end

  module ClassMethods
    ...
  end
end

After refactoring with ActiveSupport::Concern.

require 'active_support/concern'

module M
  extend ActiveSupport::Concern

  included do
    scope :disabled, -> { where(disabled: true) }
  end

  class_methods do
    ...
  end

  def instance_method
    ...
  end
end

You see instance methods, class methods and included block are less messy. Concerns will inject them appropriately for you. That's one advantage of using ActiveSupport::Concern.


Example 2: Handle module dependencies gracefully.

module Foo
  def self.included(base)
    base.class_eval do
      def self.method_injected_by_foo_to_host_klass
        ...
      end
    end
  end
end

module Bar
  def self.included(base)
    base.method_injected_by_foo_to_host_klass
  end
end

class Host
  include Foo # We need to include this dependency for Bar
  include Bar # Bar is the module that Host really needs
end

In this example Bar is the module that Host really needs. But since Bar has dependency with Foo the Host class have to include Foo (but wait why does Host want to know about Foo? Can it be avoided?).

So Bar adds dependency everywhere it goes. And order of inclusion also matters here. This adds lot of complexity/dependency to huge code base.

After refactoring with ActiveSupport::Concern

require 'active_support/concern'

module Foo
  extend ActiveSupport::Concern
  included do
    def self.method_injected_by_foo_to_host_klass
      ...
    end
  end
end

module Bar
  extend ActiveSupport::Concern
  include Foo

  included do
    self.method_injected_by_foo_to_host_klass
  end
end

class Host
  include Bar # It works, now Bar takes care of its dependencies
end

Now it looks simple.

If you are thinking why can't we add Foo dependency in Bar module itself? That won't work since method_injected_by_foo_to_host_klass have to be injected in a class that's including Bar not on Bar module itself.

Source: Rails ActiveSupport::Concern

Convert ArrayList to String array in Android

Well in general:

List<String> names = new ArrayList<String>();
names.add("john");
names.add("ann");

String[] namesArr = new String[names.size()];
for (int i = 0; i < names.size(); i++) {
    namesArr[i] = names.get(i);  
}

Or better yet, using built in:

List<String> names = new ArrayList<String>();
String[] namesArr = names.toArray(new String[names.size()]);

Use sed to replace all backslashes with forward slashes

$ echo "C:\Windows\Folder\File.txt" | sed -e 's/\\/\//g'
C:/Windows/Folder/File.txt

The sed command in this case is 's/OLD_TEXT/NEW_TEXT/g'.

The leading 's' just tells it to search for OLD_TEXT and replace it with NEW_TEXT.

The trailing 'g' just says to replace all occurrences on a given line, not just the first.

And of course you need to separate the 's', the 'g', the old, and the new from each other. This is where you must use forward slashes as separators.

For your case OLD_TEXT == '\' and NEW_TEXT == '/'. But you can't just go around typing slashes and expecting things to work as expected be taken literally while using them as separators at the same time. In general slashes are quite special and must be handled as such. They must be 'escaped' (i.e. preceded) by a backslash.

So for you, OLD_TEXT == '\\' and NEW_TEXT == '\/'. Putting these inside the 's/OLD_TEXT/NEW_TEXT/g' paradigm you get
's/\\/\//g'. That reads as
's / \\ / \/ / g' and after escapes is
's / \ / / / g' which will replace all backslashes with forward slashes.

How to hide a div after some time period?

setTimeout('$("#someDivId").hide()',1500);

What is the difference between association, aggregation and composition?

I think this link will do your homework: http://ootips.org/uml-hasa.html

To understand the terms I remember an example in my early programming days:

If you have a 'chess board' object that contains 'box' objects that is composition because if the 'chess board' is deleted there is no reason for the boxes to exist anymore.

If you have a 'square' object that have a 'color' object and the square gets deleted the 'color' object may still exist, that is aggregation

Both of them are associations, the main difference is conceptual

How can I create a temp file with a specific extension with .NET?

You can also alternatively use System.CodeDom.Compiler.TempFileCollection.

string tempDirectory = @"c:\\temp";
TempFileCollection coll = new TempFileCollection(tempDirectory, true);
string filename = coll.AddExtension("txt", true);
File.WriteAllText(Path.Combine(tempDirectory,filename),"Hello World");

Here I used a txt extension but you can specify whatever you want. I also set the keep flag to true so that the temp file is kept around after use. Unfortunately, TempFileCollection creates one random file per extension. If you need more temp files, you can create multiple instances of TempFileCollection.

Swipe to Delete and the "More" button (like in Mail app on iOS 7)

You need to subclass UITableViewCell and subclass method willTransitionToState:(UITableViewCellStateMask)state which is called whenever user swipes the cell. The state flags will let you know if the Delete button is showing, and show/hide your More button there.

Unfortunately this method gives you neither the width of the Delete button nor the animation time. So you need to observer & hard-code your More button's frame and animation time into your code (I personally think Apple needs to do something about this).

RegEx match open tags except XHTML self-contained tags

The OP doesn't seem to say what he needs to do with the tags. For example, does he need to extract inner text, or just examine the tags?

I'm firmly in the camp that says a regular expression is not the be-all, end-all text parser. I've written a large amount of text-parsing code including this code to parse HTML tags.

While it's true I'm not all that great with regular expressions, I consider regular expressions just too rigid and hard to maintain for this sort of parsing.

How to add jQuery to an HTML page?

You need to wrap this in script tags:

<script type='text/javascript'> ... your code ... </script>

That being said, it's important WHEN you execute this code. If you put this in the page BEFORE the HTML elements that it is hooking into then the script will run BEFORE the HTML is actually rendered in the page, so it will fail.

It is common practice to wrap this type of code in a "document ready" block, like so:

<script type='text/javascript'>
$(document).ready(function() {

... your code...

}}
</script>

This ensures that the entire page has rendered in the browser BEFORE your code is executed. It is also a best practice to put the code in the <head> section of your page.

JavaScript inside an <img title="<a href='#' onClick='alert('Hello World!')>The Link</a>" /> possible?

When you click on the image you'll get the alert:

<img src="logo1.jpg" onClick='alert("Hello World!")'/>

if this is what you want.

How should I unit test multithreaded code?

The following article suggests 2 solutions. Wrapping a semaphore (CountDownLatch) and adds functionality like externalize data from internal thread. Another way of achieving this purpose is to use Thread Pool (see Points of Interest).

Sprinkler - Advanced synchronization object

React prevent event bubbling in nested components on click

This is an easy way to prevent the click event from moving forward to the next component and then call your yourFunction.

<Button onClick={(e)=> {e.stopPropagation(); yourFunction(someParam)}}>Delete</Button>

How to change the scrollbar color using css

You can use the following attributes for webkit, which reach into the shadow DOM:

::-webkit-scrollbar              { /* 1 */ }
::-webkit-scrollbar-button       { /* 2 */ }
::-webkit-scrollbar-track        { /* 3 */ }
::-webkit-scrollbar-track-piece  { /* 4 */ }
::-webkit-scrollbar-thumb        { /* 5 */ }
::-webkit-scrollbar-corner       { /* 6 */ }
::-webkit-resizer                { /* 7 */ }

Here's a working fiddle with a red scrollbar, based on code from this page explaining the issues.

http://jsfiddle.net/hmartiro/Xck2A/1/

Using this and your solution, you can handle all browsers except Firefox, which at this point I think still requires a javascript solution.

Delete/Reset all entries in Core Data?

here my swift3 version for delete all records. 'Users' is entity name

@IBAction func btnDelAll_touchupinside(_ sender: Any) {

    let appDelegate = UIApplication.shared.delegate as! AppDelegate
    let managedObjectContext = appDelegate.persistentContainer.viewContext

    let fetchReq = NSFetchRequest<NSFetchRequestResult>(entityName: "Users")
    let req = NSBatchDeleteRequest(fetchRequest: fetchReq)

    do {
        try managedObjectContext.execute(req)

    } catch {
        // Error Handling
    }   
}

Spark dataframe: collect () vs select ()

To answer the questions directly:

Will collect() behave the same way if called on a dataframe?

Yes, spark.DataFrame.collect is functionally the same as spark.RDD.collect. They serve the same purpose on these different objects.

What about the select() method?

There is no such thing as spark.RDD.select, so it cannot be the same as spark.DataFrame.select.

Does it also work the same way as collect() if called on a dataframe?

The only thing that is similar between select and collect is that they are both functions on a DataFrame. They have absolutely zero overlap in functionality.

Here's my own description: collect is the opposite of sc.parallelize. select is the same as the SELECT in any SQL statement.

If you are still having trouble understanding what collect actually does (for either RDD or DataFrame), then you need to look up some articles about what spark is doing behind the scenes. e.g.:

Integrating MySQL with Python in Windows

upvoted itsadok's answer because it led me to the installation for python 2.7 as well, which is located here: http://www.codegood.com/archives/129

How do I convert a dictionary to a JSON String in C#?

Json.NET probably serializes C# dictionaries adequately now, but when the OP originally posted this question, many MVC developers may have been using the JavaScriptSerializer class because that was the default option out of the box.

If you're working on a legacy project (MVC 1 or MVC 2), and you can't use Json.NET, I recommend that you use a List<KeyValuePair<K,V>> instead of a Dictionary<K,V>>. The legacy JavaScriptSerializer class will serialize this type just fine, but it will have problems with a dictionary.

Documentation: Serializing Collections with Json.NET

The view didn't return an HttpResponse object. It returned None instead

Python is very sensitive to indentation, with the code below I got the same error:

    except IntegrityError as e:
        if 'unique constraint' in e.args:
            return render(request, "calender.html")

The correct indentation is:

    except IntegrityError as e:
        if 'unique constraint' in e.args:
        return render(request, "calender.html")

Is it possible to wait until all javascript files are loaded before executing javascript code?

You can use

$(window).on('load', function() {
    // your code here
});

Which will wait until the page is loaded. $(document).ready() waits until the DOM is loaded.

In plain JS:

window.addEventListener('load', function() {
    // your code here
})

Start index for iterating Python list

Why are people using list slicing (slow because it copies to a new list), importing a library function, or trying to rotate an array for this?

Use a normal for-loop with range(start, stop, step) (where start and step are optional arguments).

For example, looping through an array starting at index 1:

for i in range(1, len(arr)):
    print(arr[i])

R Apply() function on specific dataframe columns

I think what you want is mapply. You could apply the function to all columns, and then just drop the columns you don't want. However, if you are applying different functions to different columns, it seems likely what you want is mutate, from the dplyr package.

How to retrieve value from elements in array using jQuery?

Use: http://jsfiddle.net/xH79d/

var n = $("input[name^='card']").length;
var array = $("input[name^='card']");

for(i=0; i < n; i++) {

   // use .eq() within a jQuery object to navigate it by Index

   card_value = array.eq(i).attr('name'); // I'm assuming you wanted -name-
   // otherwise it'd be .eq(i).val(); (if you wanted the text value)
   alert(card_value);
}

?

For each row in an R dataframe

You can try this, using apply() function

> d
  name plate value1 value2
1    A    P1      1    100
2    B    P2      2    200
3    C    P3      3    300

> f <- function(x, output) {
 wellName <- x[1]
 plateName <- x[2]
 wellID <- 1
 print(paste(wellID, x[3], x[4], sep=","))
 cat(paste(wellID, x[3], x[4], sep=","), file= output, append = T, fill = T)
}

> apply(d, 1, f, output = 'outputfile')

How can I wrap text in a label using WPF?

You can put a TextBlock inside the label:

<Label> 
  <TextBlock Text="Long Text . . . ." TextWrapping="Wrap" /> 
</Label> 

How to get max value of a column using Entity Framework?

Maybe help, if you want to add some filter:

context.Persons
.Where(c => c.state == myState)
.Select(c => c.age)
.DefaultIfEmpty(0)
.Max();

Spring JPA @Query with LIKE

Another way: instead CONCAT function we can use double pipe: :lastname || '%'

@Query("select c from Customer c where c.lastName LIKE :lastname||'%'")
List<Customer> findCustomByLastName( @Param("lastname") String lastName);

You can put anywhere, prefix, suffix or both

:lastname ||'%'  
'%' || :lastname  
'%' || :lastname || '%'  

Using GPU from a docker container?

Goal:

My goal was to make a CUDA enabled docker image without using nvidia/cuda as base image. Because I have some custom jupyter image, and I want to base from that.

Prerequisite:

The host machine had nvidia driver, CUDA toolkit, and nvidia-container-toolkit already installed. Please refer to the official docs, and to Rohit's answer.

Test that nvidia driver and CUDA toolkit is installed correctly with: nvidia-smi on the host machine, which should display correct "Driver Version" and "CUDA Version" and shows GPUs info.

Test that nvidia-container-toolkit is installed correctly with: docker run --rm --gpus all nvidia/cuda:latest nvidia-smi

Dockerfile

I found what I assume to be the official Dockerfile for nvidia/cuda here I "flattened" it, appended the contents to my Dockerfile and tested it to be working nicely:

FROM sidazhou/scipy-notebook:latest
# FROM ubuntu:18.04 

###########################################################################
# See https://gitlab.com/nvidia/container-images/cuda/-/blob/master/dist/10.1/ubuntu18.04-x86_64/base/Dockerfile
# See https://sarus.readthedocs.io/en/stable/user/custom-cuda-images.html
###########################################################################
USER root

###########################################################################
# base
RUN apt-get update && apt-get install -y --no-install-recommends \
    gnupg2 curl ca-certificates && \
    curl -fsSL https://developer.download.nvidia.com/compute/cuda/repos/ubuntu1804/x86_64/7fa2af80.pub | apt-key add - && \
    echo "deb https://developer.download.nvidia.com/compute/cuda/repos/ubuntu1804/x86_64 /" > /etc/apt/sources.list.d/cuda.list && \
    echo "deb https://developer.download.nvidia.com/compute/machine-learning/repos/ubuntu1804/x86_64 /" > /etc/apt/sources.list.d/nvidia-ml.list && \
    apt-get purge --autoremove -y curl \
    && rm -rf /var/lib/apt/lists/*

ENV CUDA_VERSION 10.1.243
ENV CUDA_PKG_VERSION 10-1=$CUDA_VERSION-1

# For libraries in the cuda-compat-* package: https://docs.nvidia.com/cuda/eula/index.html#attachment-a
RUN apt-get update && apt-get install -y --no-install-recommends \
    cuda-cudart-$CUDA_PKG_VERSION \
    cuda-compat-10-1 \
    && ln -s cuda-10.1 /usr/local/cuda && \
    rm -rf /var/lib/apt/lists/*

# Required for nvidia-docker v1
RUN echo "/usr/local/nvidia/lib" >> /etc/ld.so.conf.d/nvidia.conf && \
    echo "/usr/local/nvidia/lib64" >> /etc/ld.so.conf.d/nvidia.conf

ENV PATH /usr/local/nvidia/bin:/usr/local/cuda/bin:${PATH}
ENV LD_LIBRARY_PATH /usr/local/nvidia/lib:/usr/local/nvidia/lib64


###########################################################################
#runtime next
ENV NCCL_VERSION 2.7.8

RUN apt-get update && apt-get install -y --no-install-recommends \
    cuda-libraries-$CUDA_PKG_VERSION \
    cuda-npp-$CUDA_PKG_VERSION \
    cuda-nvtx-$CUDA_PKG_VERSION \
    libcublas10=10.2.1.243-1 \
    libnccl2=$NCCL_VERSION-1+cuda10.1 \
    && apt-mark hold libnccl2 \
    && rm -rf /var/lib/apt/lists/*

# apt from auto upgrading the cublas package. See https://gitlab.com/nvidia/container-images/cuda/-/issues/88
RUN apt-mark hold libcublas10


###########################################################################
#cudnn7 (not cudnn8) next

ENV CUDNN_VERSION 7.6.5.32

RUN apt-get update && apt-get install -y --no-install-recommends \
    libcudnn7=$CUDNN_VERSION-1+cuda10.1 \
    && apt-mark hold libcudnn7 && \
    rm -rf /var/lib/apt/lists/*


ENV NVIDIA_VISIBLE_DEVICES all
ENV NVIDIA_DRIVER_CAPABILITIES all
ENV NVIDIA_REQUIRE_CUDA "cuda>=10.1"


###########################################################################
#docker build -t sidazhou/scipy-notebook-gpu:latest .

#docker run -itd -gpus all\
#  -p 8888:8888 \
#  -p 6006:6006 \
#  --user root \
#  -e NB_UID=$(id -u) \
#  -e NB_GID=$(id -g) \
#  -e GRANT_SUDO=yes \
#  -v ~/workspace:/home/jovyan/work \
#  --name sidazhou-jupyter-gpu \
#  sidazhou/scipy-notebook-gpu:latest

#docker exec sidazhou-jupyter-gpu python -c "import tensorflow as tf; print(tf.config.experimental.list_physical_devices('GPU'))"

How to get script of SQL Server data?

From the SQL Server Management Studio you can right click on your database and select:

Tasks -> Generate Scripts

Then simply proceed through the wizard. Make sure to set 'Script Data' to TRUE when prompted to choose the script options.

SQL Server 2008 R2

alt text

Further reading:

Plotting in a non-blocking way with Matplotlib


A simple trick that works for me is the following:

  1. Use the block = False argument inside show: plt.show(block = False)
  2. Use another plt.show() at the end of the .py script.

Example:

import matplotlib.pyplot as plt

plt.imshow(add_something)
plt.xlabel("x")
plt.ylabel("y")

plt.show(block=False)

#more code here (e.g. do calculations and use print to see them on the screen

plt.show()

Note: plt.show() is the last line of my script.

Optional args in MATLAB functions

A good way of going about this is not to use nargin, but to check whether the variables have been set using exist('opt', 'var').

Example:

function [a] = train(x, y, opt)
    if (~exist('opt', 'var'))
        opt = true;
    end
end

See this answer for pros of doing it this way: How to check whether an argument is supplied in function call?

How to resolve the error on 'react-native start'

All mentioned comments above are great, sharing the path that worked with me for this Blacklist file that need to be edited:

"Your project name\node_modules\metro-bundler\src" File name "blacklist.js"

In JavaScript, why is "0" equal to false, but when tested by 'if' it is not false by itself?

The "if" expression tests for truthiness, while the double-equal tests for type-independent equivalency. A string is always truthy, as others here have pointed out. If the double-equal were testing both of its operands for truthiness and then comparing the results, then you'd get the outcome you were intuitively assuming, i.e. ("0" == true) === true. As Doug Crockford says in his excellent JavaScript: the Good Parts, "the rules by which [== coerces the types of its operands] are complicated and unmemorable.... The lack of transitivity is alarming." It suffices to say that one of the operands is type-coerced to match the other, and that "0" ends up being interpreted as a numeric zero, which is in turn equivalent to false when coerced to boolean (or false is equivalent to zero when coerced to a number).

How do I convert Int/Decimal to float in C#?

You can just do a cast

int val1 = 1;
float val2 = (float)val1;

or

decimal val3 = 3;
float val4 = (float)val3;

Run JavaScript in Visual Studio Code

I am surprised this has not been mentioned yet:

Simply open the .js file in question in VS Code, switch to the 'Debug Console' tab, hit the debug button in the left nav bar, and click the run icon (play button)!

Requires nodejs to be installed!

Conversion failed when converting date and/or time from character string in SQL SERVER 2008

If you're trying to insert in to last_accessed_on, which is a DateTime2, then your issue is with the fact that you are converting it to a varchar in a format that SQL doesn't understand.

If you modify your code to this, it should work, note the format of your date has been changed to: YYYY-MM-DD hh:mm:ss:

UPDATE  student_queues 
SET  Deleted=0, 
     last_accessed_by='raja', 
     last_accessed_on=CONVERT(datetime2,'2014-07-23 09:37:00')
WHERE std_id IN ('2144-384-11564') AND reject_details='REJECT'

Or if you want to use CAST, replace with:

CAST('2014-07-23 09:37:00.000' AS datetime2)

This is using the SQL ISO Date Format.

jQuery/JavaScript: accessing contents of an iframe

Use

iframe.contentWindow.document

instead of

iframe.contentDocument

Why does Path.Combine not properly concatenate filenames that start with Path.DirectorySeparatorChar?

I used aggregate function to force paths combine as below:

public class MyPath    
{
    public static string ForceCombine(params string[] paths)
    {
        return paths.Aggregate((x, y) => Path.Combine(x, y.TrimStart('\\')));
    }
}

No module named serial

Serial is not included with Python. It is a package that you'll need to install separately.

Since you have pip installed you can install serial from the command line with:

pip install pyserial

Or, you can use a Windows installer from here. It looks like you're using Python 3 so click the installer for Python 3.

Then you should be able to import serial as you tried before.

Simple conversion between java.util.Date and XMLGregorianCalendar

You can use the this customization to change the default mapping to java.util.Date

<xsd:annotation>
<xsd:appinfo>
    <jaxb:globalBindings>
        <jaxb:javaType name="java.util.Date" xmlType="xsd:dateTime"
                 parseMethod="org.apache.cxf.xjc.runtime.DataTypeAdapter.parseDateTime"
                 printMethod="org.apache.cxf.xjc.runtime.DataTypeAdapter.printDateTime"/>
    </jaxb:globalBindings>
</xsd:appinfo>

Changing date format in R

nzd$date <- format(as.Date(nzd$date), "%Y/%m/%d")

In the above piece of code, there are two mistakes. First of all, when you are reading nzd$date inside as.Date you are not mentioning in what format you are feeding it the date. So, it tries it's default set format to read it. If you see the help doc, ?as.Date you will see

format
A character string. If not specified, it will try "%Y-%m-%d" then "%Y/%m/%d" on the first non-NA element, and give an error if neither works. Otherwise, the processing is via strptime

The second mistake is: even though you would like to read it in %Y-%m-%d format, inside format you wrote "%Y/%m/%d".

Now, the correct way of doing it is:

> nzd <- data.frame(date=c("31/08/2011", "31/07/2011", "30/06/2011"), 
+                                       mid=c(0.8378,0.8457,0.8147))
> nzd
        date    mid
1 31/08/2011 0.8378
2 31/07/2011 0.8457
3 30/06/2011 0.8147
> nzd$date <- format(as.Date(nzd$date, format = "%d/%m/%Y"), "%Y-%m-%d")
> head(nzd)
        date    mid
1 2011-08-31 0.8378
2 2011-07-31 0.8457
3 2011-06-30 0.8147

/usr/lib/libstdc++.so.6: version `GLIBCXX_3.4.15' not found

I'm compiling gcc 4.6 from source, and apparently

sudo make install 

didn't catch this one. I dug around and found

gcc/trunk/x86_64-unknown-linux-gnu/libstdc++-v3/src/.libs/libstdc++.so.6.0.15

I copied it in to /usr/lib and redirected libstdc++.so.6 to point to the new one, and now everything works.

Scope 'session' is not active for the current thread; IllegalStateException: No thread-bound request found

If anyone else stuck on same point, following solved my problem.

In web.xml

 <listener>
            <listener-class>
                    org.springframework.web.context.request.RequestContextListener 
            </listener-class>
  </listener>

In Session component

@Component
@Scope(value = "session",  proxyMode = ScopedProxyMode.TARGET_CLASS)

In pom.xml

    <dependency>
        <groupId>cglib</groupId>
        <artifactId>cglib</artifactId>
        <version>3.1</version>
    </dependency>

Permissions for /var/www/html

I have just been in a similar position with regards to setting the 777 permissions on the apache website hosting directory. After a little bit of tinkering it seems that changing the group ownership of the folder to the "apache" group allowed access to the folder based on the user group.

1) make sure that the group ownership of the folder is set to the group apache used / generates for use. (check /etc/groups, mine was www-data on Ubuntu)

2) set the folder permissions to 774 to stop "everyone" from having any change access, but allowing the owner and group permissions required.

3) add your user account to the group that has permission on the folder (mine was www-data).

Match exact string

Use the start and end delimiters: ^abc$

Using Excel VBA to export data to MS Access table

is it possible to export without looping through all records

For a range in Excel with a large number of rows you may see some performance improvement if you create an Access.Application object in Excel and then use it to import the Excel data into Access. The code below is in a VBA module in the same Excel document that contains the following test data

SampleData.png

Option Explicit

Sub AccImport()
    Dim acc As New Access.Application
    acc.OpenCurrentDatabase "C:\Users\Public\Database1.accdb"
    acc.DoCmd.TransferSpreadsheet _
            TransferType:=acImport, _
            SpreadSheetType:=acSpreadsheetTypeExcel12Xml, _
            TableName:="tblExcelImport", _
            Filename:=Application.ActiveWorkbook.FullName, _
            HasFieldNames:=True, _
            Range:="Folio_Data_original$A1:B10"
    acc.CloseCurrentDatabase
    acc.Quit
    Set acc = Nothing
End Sub

Xcode 10 Error: Multiple commands produce

In my case, Build archive error vs Xcode10

-1: Multiple commands produce '/Users/kk/Library/Developer/Xcode/DerivedData/react_carday_app-hjahojxsbvmmiyaklrhhuqljdfwv/Build/Intermediates.noindex/ArchiveIntermediates/react_carday_app/IntermediateBuildFilesPath/UninstalledProducts/iphoneos/libyoga.a': 1) Target 'yoga' has a command with output '/Users/kk/Library/Developer/Xcode/DerivedData/react_carday_app-hjahojxsbvmmiyaklrhhuqljdfwv/Build/Intermediates.noindex/ArchiveIntermediates/react_carday_app/IntermediateBuildFilesPath/UninstalledProducts/iphoneos/libyoga.a' 2) Target 'yoga' has a command with output '/Users/kk/Library/Developer/Xcode/DerivedData/react_carday_app-hjahojxsbvmmiyaklrhhuqljdfwv/Build/Intermediates.noindex/ArchiveIntermediates/react_carday_app/IntermediateBuildFilesPath/UninstalledProducts/iphoneos/libyoga.a'

There should something like bellow in your Podfile

post_install do |installer|
  installer.pods_project.targets.each do |target|
    if target.name == "React"
      target.remove_from_project
    end

    if target.name == "yoga"
      target.remove_from_project
    end
  end
end

and then run pod install

Convert date to UTC using moment.js

As of : moment.js version 2.24.0

let's say you have a local date input, this is the proper way to convert your dateTime or Time input to UTC :

var utcStart = new moment("09:00", "HH:mm").utc();

or in case you specify a date

var utcStart = new moment("2019-06-24T09:00", "YYYY-MM-DDTHH:mm").utc();

As you can see the result output will be returned in UTC :

//You can call the format() that will return your UTC date in a string 
 utcStart.format(); 
//Result : 2019-06-24T13:00:00 

But if you do this as below, it will not convert to UTC :

var myTime = new moment.utc("09:00", "HH:mm"); 

You're only setting your input to utc time, it's as if your mentioning that myTime is in UTC, ....the output will be 9:00

What is std::move(), and when should it be used?

Here is a full example, using std::move for a (simple) custom vector

Expected output:

 c: [10][11]
 copy ctor called
 copy of c: [10][11]
 move ctor called
 moved c: [10][11]

Compile as:

  g++ -std=c++2a -O2 -Wall -pedantic foo.cpp

Code:

#include <iostream>
#include <algorithm>

template<class T> class MyVector {
private:
    T *data;
    size_t maxlen;
    size_t currlen;
public:
    MyVector<T> () : data (nullptr), maxlen(0), currlen(0) { }
    MyVector<T> (int maxlen) : data (new T [maxlen]), maxlen(maxlen), currlen(0) { }

    MyVector<T> (const MyVector& o) {
        std::cout << "copy ctor called" << std::endl;
        data = new T [o.maxlen];
        maxlen = o.maxlen;
        currlen = o.currlen;
        std::copy(o.data, o.data + o.maxlen, data);
    }

    MyVector<T> (const MyVector<T>&& o) {
        std::cout << "move ctor called" << std::endl;
        data = o.data;
        maxlen = o.maxlen;
        currlen = o.currlen;
    }

    void push_back (const T& i) {
        if (currlen >= maxlen) {
            maxlen *= 2;
            auto newdata = new T [maxlen];
            std::copy(data, data + currlen, newdata);
            if (data) {
                delete[] data;
            }
            data = newdata;
        }
        data[currlen++] = i;
    }

    friend std::ostream& operator<<(std::ostream &os, const MyVector<T>& o) {
        auto s = o.data;
        auto e = o.data + o.currlen;;
        while (s < e) {
            os << "[" << *s << "]";
            s++;
        }
        return os;
    }
};

int main() {
    auto c = new MyVector<int>(1);
    c->push_back(10);
    c->push_back(11);
    std::cout << "c: " << *c << std::endl;
    auto d = *c;
    std::cout << "copy of c: " << d << std::endl;
    auto e = std::move(*c);
    delete c;
    std::cout << "moved c: " << e << std::endl;
}

div background color, to change onhover

There is no need to put anchor. To change style of div on hover then Change background color of div on hover.

<div class="div_hover"> Change div background color on hover</div>

In .css page

.div_hover { background-color: #FFFFFF; }

.div_hover:hover { background-color: #000000; }

How to create a localhost server to run an AngularJS project

If you are a java guy simple place your angular folder in web content folder of your web application and deploy to your tomcat server. Super easy !

Spring boot Security Disable security

As previously multiple solutions mentioned to disable security through commenting of

@EnableWebSecurity

annotation and other is through properties in application.properties or yml. But those properties are showing as deprecated in latest spring boot version.

So, I would like to share another approach to configure default username and password in your application-dev.properties or application-dev.yml and use them to login into swagger and etc in development environment.

spring.security.user.name=admin
spring.security.user.password=admin

So, this approach will also provides you some kind of security as well and you can share this information with your development team. You can also configure user roles as well, but its not required in development level.

Javascript to set hidden form value on drop down change

Here you can set hidden's value at onchange event of dropdown list :

$('#myDropDown').bind('change', function () {
  $('#myHidden').val('setted value');
});

your hidden and drop down list :

<input type="hidden" id="myHidden" />

<select id="myDropDown">
   <option value="opt 1">Option 1</option>
   <option value="opt 2">Option 2</option>
   <option value="opt 3">Option 3</option>
</ select>

Set language for syntax highlighting in Visual Studio Code

Syntax Highlighting for custom file extension

Any custom file extension can be associated with standard syntax highlighting with custom files association in User Settings as follows.

Changing File Association settings for permanent Syntax Highlighting

Note that this will be a permanent setting. In order to set for the current session alone, type in the preferred language in Select Language Mode box (without changing file association settings)

Installing new Syntax Package

If the required syntax package is not available by default, you can add them via the Extension Marketplace (Ctrl+Shift+X) and search for the language package.

You can further reproduce the above steps to map the file extensions with the new syntax package.

How can I start InternetExplorerDriver using Selenium WebDriver

Below steps are worked for me, Hope this will work for you as well,

  1. Open internet explorer.
  2. Navigate to Tools->Option
  3. Navigate to Security Tab
  4. Click on "Reset All Zones to Default level" button
  5. Now for all option like Internet,Intranet,Trusted Sites and Restricted Site enable "Enable Protected" mode check-box.
  6. Set IE zoom level to 100%
  7. then write below code in a java file and run

    System.setProperty("webdriver.ie.driver","path of your IE driver exe\IEDriverServer.exe");
    InternetExplorerDriver driver=new InternetExplorerDriver();
    driver.manage().window().maximize();
    Thread.Sleep(10100);
    driver.get("http://www.Google.com");
    Thread.Sleep(10000);
    

Singleton design pattern vs Singleton beans in Spring container

Let's take the simplest example: you have an application and you just use the default classloader. You have a class which, for whatever reason, you decide that it should not have more than one instance in the application. (Think of a scenario where several people work on pieces of the application).

If you are not using the Spring framework, the Singleton pattern ensures that there will not be more than one instance of a class in your application. That is because you cannot instantiate instances of the class by doing 'new' because the constructor is private. The only way to get an instance of the class is to call some static method of the class (usually called 'getInstance') which always returns the same instance.

Saying that you are using the Spring framework in your application, just means that in addition to the regular ways of obtaining an instance of the class (new or static methods that return an instance of the class), you can also ask Spring to get you an instance of that class and Spring will ensure that whenever you ask it for an instance of that class it will always return the same instance, even if you didn't write the class using the Singleton pattern. In other words, even if the class has a public constructor, if you always ask Spring for an instance of that class, Spring will only call that constructor once during the life of your application.

Normally if you are using Spring, you should only use Spring to create instances, and you can have a public constructor for the class. But if your constructor is not private you are not really preventing anyone from creating new instances of the class directly, by bypassing Spring.

If you truly want a single instance of the class, even if you use Spring in your application and define the class in Spring to be a singleton, the only way to ensure that is also implement the class using the Singleton pattern. That ensures that there will be a single instance, whether people use Spring to get an instance or bypass Spring.

How to subtract n days from current date in java?

for future use find day of the week ,deduct day and display the deducted day using date.

public static void main(String args[]) throws ParseException {

String[] days = { "Sunday", "Monday", "Tuesday", "Wednesday",
        "Thursday", "Friday", "Saturday" };
SimpleDateFormat format1 = new SimpleDateFormat("dd/MM/yyyy");
Date dt1 = format1.parse("20/10/2013");

Calendar c = Calendar.getInstance();
c.setTime(dt1);
int dayOfWeek = c.get(Calendar.DAY_OF_WEEK);
long diff = Calendar.getInstance().getTime().getTime() ;
System.out.println(dayOfWeek);

switch (dayOfWeek) {

case 6:
    System.out.println(days[dayOfWeek - 1]);
    break;
case 5:

    System.out.println(days[dayOfWeek - 1]);
    break;      
case 4:
    System.out.println(days[dayOfWeek - 1]);
    break;
case 3:

    System.out.println(days[dayOfWeek - 1]);
    break;
case 2:
    System.out.println(days[dayOfWeek - 1]);
    break;
case 1:

    System.out.println(days[dayOfWeek - 1]);

     diff = diff -(dt1.getTime()- 3 );
     long valuebefore = dt1.getTime();
     long valueafetr = dt1.getTime()-2;
     System.out.println("DATE IS befor subtraction :"+valuebefore);
     System.out.println("DATE IS after subtraction :"+valueafetr);

     long x= dt1.getTime()-(2 * 24 * 3600 * 1000);
     System.out.println("Deducted date to find firday is - 2 days form Sunday :"+new Date((dt1.getTime()-(2*24*3600*1000))));
     System.out.println("DIffrence from now on is :"+diff);
        if(diff > 0) {

            diff = diff / (1000 * 60 * 60 * 24);
            System.out.println("Diff"+diff);
            System.out.println("Date is Expired!"+(dt1.getTime() -(long)2));
        }

    break;
}
}

Download a div in a HTML page as pdf using javascript

Content inside a <div class='html-content'>....</div> can be downloaded as pdf with styles using jspdf & html2canvas.

You need to refer both js libraries,

<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.5.3/jspdf.min.js"></script>
<script type="text/javascript" src="https://html2canvas.hertzen.com/dist/html2canvas.js"></script>

Then call below function,

//Create PDf from HTML...
function CreatePDFfromHTML() {
    var HTML_Width = $(".html-content").width();
    var HTML_Height = $(".html-content").height();
    var top_left_margin = 15;
    var PDF_Width = HTML_Width + (top_left_margin * 2);
    var PDF_Height = (PDF_Width * 1.5) + (top_left_margin * 2);
    var canvas_image_width = HTML_Width;
    var canvas_image_height = HTML_Height;

    var totalPDFPages = Math.ceil(HTML_Height / PDF_Height) - 1;

    html2canvas($(".html-content")[0]).then(function (canvas) {
        var imgData = canvas.toDataURL("image/jpeg", 1.0);
        var pdf = new jsPDF('p', 'pt', [PDF_Width, PDF_Height]);
        pdf.addImage(imgData, 'JPG', top_left_margin, top_left_margin, canvas_image_width, canvas_image_height);
        for (var i = 1; i <= totalPDFPages; i++) { 
            pdf.addPage(PDF_Width, PDF_Height);
            pdf.addImage(imgData, 'JPG', top_left_margin, -(PDF_Height*i)+(top_left_margin*4),canvas_image_width,canvas_image_height);
        }
        pdf.save("Your_PDF_Name.pdf");
        $(".html-content").hide();
    });
}

Ref: pdf genration from html canvas and jspdf.

May be this will help someone.

MongoDB query multiple collections at once

One solution: add isAdmin: 0/1 flag to your post collection document.

Other solution: use DBrefs

Could not load file or assembly 'System.Data.SQLite'

Another way to get around this is just to upgrade your application to ELMAH 1.2 rather than 1.1.

Open another application from your own (intent)

Alternatively you can also open the intent from your app in the other app with:

Intent intent = new Intent(Intent.ACTION_VIEW, uri);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);

where uri is the deeplink to the other app

Rails: select unique values from a column

Model.uniq.pluck(:rating)

# SELECT DISTINCT "models"."rating" FROM "models"

This has the advantages of not using sql strings and not instantiating models

Solving sslv3 alert handshake failure when trying to use a client certificate

Not a definite answer but too much to fit in comments:

I hypothesize they gave you a cert that either has a wrong issuer (although their server could use a more specific alert code for that) or a wrong subject. We know the cert matches your privatekey -- because both curl and openssl client paired them without complaining about a mismatch; but we don't actually know it matches their desired CA(s) -- because your curl uses openssl and openssl SSL client does NOT enforce that a configured client cert matches certreq.CAs.

Do openssl x509 <clientcert.pem -noout -subject -issuer and the same on the cert from the test P12 that works. Do openssl s_client (or check the one you did) and look under Acceptable client certificate CA names; the name there or one of them should match (exactly!) the issuer(s) of your certs. If not, that's most likely your problem and you need to check with them you submitted your CSR to the correct place and in the correct way. Perhaps they have different regimes in different regions, or business lines, or test vs prod, or active vs pending, etc.

If the issuer of your cert does match desiredCAs, compare its subject to the working (test-P12) one: are they in similar format? are there any components in the working one not present in yours? If they allow it, try generating and submitting a new CSR with a subject name exactly the same as the test-P12 one, or as close as you can get, and see if that produces a cert that works better. (You don't have to generate a new key to do this, but if you choose to, keep track of which certs match which keys so you don't get them mixed up.) If that doesn't help look at the certificate extensions with openssl x509 <cert -noout -text for any difference(s) that might reasonably be related to subject authorization, like KeyUsage, ExtendedKeyUsage, maybe Policy, maybe Constraints, maybe even something nonstandard.

If all else fails, ask the server operator(s) what their logs say about the problem, or if you have access look at the logs yourself.

@Autowired - No qualifying bean of type found for dependency at least 1 bean

Missing the 'implements' keyword in the impl classes might also be the issue

Store output of subprocess.Popen call in a string

This was perfect for me. You will get the return code, stdout and stderr in a tuple.

from subprocess import Popen, PIPE

def console(cmd):
    p = Popen(cmd, shell=True, stdout=PIPE)
    out, err = p.communicate()
    return (p.returncode, out, err)

For Example:

result = console('ls -l')
print 'returncode: %s' % result[0]
print 'output: %s' % result[1]
print 'error: %s' % result[2]

Configuring angularjs with eclipse IDE

Netbeans 8.0 (beta at the time of this post) has Angular support as well as HTML5 support.

Check out this Oracle article: https://blogs.oracle.com/geertjan/entry/integrated_angularjs_development

How to add form validation pattern in Angular 2?

Without make validation patterns, You can easily trim begin and end spaces using these modules.Try this.

https://www.npmjs.com/package/ngx-trim-directive https://www.npmjs.com/package/ng2-trim-directive

Thank you.

What are the differences between WCF and ASMX web services?

There's a lot of talks going on regarding the simplicity of asmx web services over WCF. Let me clarify few points here.

  • Its true that novice web service developers will get started easily in asmx web services. Visual Studio does all the work for them and readily creates a Hello World project.
  • But if you can learn WCF (which off course wont take much time) then you can get to see that WCF is also quite simple, and you can go ahead easily.
  • Its important to remember that these said complexities in WCF are actually attributed to the beautiful features that it brings along with it. There are addressing, bindings, contracts and endpoints, services & clients all mentioned in the config file. The beauty is your business logic is segregated and maintained safely. Tomorrow if you need to change the binding from basicHttpBinding to netTcpBinding you can easily create a binding in config file and use it. So all the changes related to clients, communication channels, bindings etc are to be done in the configuration leaving the business logic safe & intact, which makes real good sense.
  • WCF "web services" are part of a much broader spectrum of remote communication enabled through WCF. You will get a much higher degree of flexibility and portability doing things in WCF than through traditional ASMX because WCF is designed, from the ground up, to summarize all of the different distributed programming infrastructures offered by Microsoft. An endpoint in WCF can be communicated with just as easily over SOAP/XML as it can over TCP/binary and to change this medium is simply a configuration file mod. In theory, this reduces the amount of new code needed when porting or changing business needs, targets, etc.
  • Web Services can be accessed only over HTTP & it works in stateless environment, where WCF is flexible because its services can be hosted in different types of applications. You can host your WCF services in Console, Windows Services, IIS & WAS, which are again different ways of creating new projects in Visual Studio.
  • ASMX is older than WCF, and anything ASMX can do so can WCF (and more). Basically you can see WCF as trying to logically group together all the different ways of getting two apps to communicate in the world of Microsoft; ASMX was just one of these many ways and so is now grouped under the WCF umbrella of capabilities.
  • You will always like to use Visual Studio for NET 4.0 or 4.5 as it makes life easy while creating WCF services.
  • The major difference is that Web Services Use XmlSerializer. But WCF Uses DataContractSerializer which is better in Performance as compared to XmlSerializer. That's why WCF performs way better than other communication technology counterparts from .NET like asmx, .NET remoting etc.

Not to forget that I was one of those guys who liked asmx services more than WCF, but that time I was not well aware of WCF services and its capabilities. I was scared of the WCF configurations. But I dared and and tried writing few WCF services of my own, and when I learnt more of WCF, now I have no inhibitions about WCF and I recommend them to anyone & everyone. Happy coding!!!

Differences between strong and weak in Objective-C

Strong: Basically Used With Properties we used to get or send data from/into another classes. Weak: Usually all outlets, connections are of Weak type from Interface.

Nonatomic: Such type of properties are used in conditions when we don't want to share our outlet or object into different simultaneous Threads. In other words, Nonatomic instance make our properties to deal with one thread at a time. Hopefully it helpful for you.

SDK Location not found Android Studio + Gradle

I clone libgdx demo, can't import project. it also reminds like this.

Env:

Eclipse(Android-ADT)

window 7

so I create local.properties file at the project root, like following

sdk.dir = D:/adt-bundle-windows-x86/sdk

I hope this can help others!

How do I get logs from all pods of a Kubernetes replication controller?

You can get help from kubectl logs -h and according the info,

kubectl logs -f deployment/myapp -c myapp --tail 100

-c is the container name and --tail will show the latest num lines,but this will choose one pod of the deployment, not all pods. This is something you have to bear in mind.

kubectl logs -l app=myapp -c myapp --tail 100

If you want to show logs of all pods, you can use -l and specify a lable, but at the same time -f won't be used.

Regexp Java for password validation

You should not use overly complex Regex (if you can avoid them) because they are

  • hard to read (at least for everyone but yourself)
  • hard to extend
  • hard to debug

Although there might be a small performance overhead in using many small regular expressions, the points above outweight it easily.

I would implement like this:

bool matchesPolicy(pwd) {
    if (pwd.length < 8) return false;
    if (not pwd =~ /[0-9]/) return false;
    if (not pwd =~ /[a-z]/) return false;
    if (not pwd =~ /[A-Z]/) return false;
    if (not pwd =~ /[%@$^]/) return false;
    if (pwd =~ /\s/) return false;
    return true;
}

IsNullOrEmpty with Object

The following code is perfectly fine and the right way (most exact, concise, and clear) to check if an object is null:

object obj = null;

//...

if (obj == null)
{
    // Do something
}

String.IsNullOrEmpty is a method existing for convenience so that you don't have to write the comparison code yourself:

private bool IsNullOrEmpty(string input)
{
    return input == null || input == string.Empty;
}

Additionally, there is a String.IsNullOrWhiteSpace method checking for null and whitespace characters, such as spaces, tabs etc.

Ascii/Hex convert in bash

With bash :

a=abcdefghij    
for ((i=0;i<${#a};i++));do printf %02X \'${a:$i:1};done

6162636465666768696A

How to check if a column exists in a datatable

Base on accepted answer, I made an extension method to check column exist in table as

I shared for whom concern.

 public static class DatatableHelper
 {
        public static bool ContainColumn(this DataTable table, string columnName)
        {
            DataColumnCollection columns = table.Columns;
            if (columns.Contains(columnName))
            {
                return true;
            }

            return false;
        }
}

And use as dtTagData.ContainColumn("SystemName")

"Undefined reference to" template class constructor

You will have to define the functions inside your header file.
You cannot separate definition of template functions in to the source file and declarations in to header file.

When a template is used in a way that triggers its intstantation, a compiler needs to see that particular templates definition. This is the reason templates are often defined in the header file in which they are declared.

Reference:
C++03 standard, § 14.7.2.4:

The definition of a non-exported function template, a non-exported member function template, or a non-exported member function or static data member of a class template shall be present in every translation unit in which it is explicitly instantiated.

EDIT:
To clarify the discussion on the comments:
Technically, there are three ways to get around this linking problem:

  • To move the definition to the .h file
  • Add explicit instantiations in the .cpp file.
  • #include the .cpp file defining the template at the .cpp file using the template.

Each of them have their pros and cons,

Moving the defintions to header files may increase the code size(modern day compilers can avoid this) but will increase the compilation time for sure.

Using the explicit instantiation approach is moving back on to traditional macro like approach.Another disadvantage is that it is necessary to know which template types are needed by the program. For a simple program this is easy but for complicated program this becomes difficult to determine in advance.

While including cpp files is confusing at the same time shares the problems of both above approaches.

I find first method the easiest to follow and implement and hence advocte using it.

Loading a .json file into c# program

See Microsofts JavaScriptSerializer

The JavaScriptSerializer class is used internally by the asynchronous communication layer to serialize and deserialize the data that is passed between the browser and the Web server. You cannot access that instance of the serializer. However, this class exposes a public API. Therefore, you can use the class when you want to work with JavaScript Object Notation (JSON) in managed code.

Namespace: System.Web.Script.Serialization

Assembly: System.Web.Extensions (in System.Web.Extensions.dll)

Change New Google Recaptcha (v2) Width

You can use parameter from reCaptcha. By default it uses normal value on data-size, You just have to use compact to fit this on small devices or some-kind small width layouts.

example:

<div class="g-recaptcha" data-size="compact"></div>

AES Encryption for an NSString on the iPhone

Please use the below mentioned URL to encrypt string using AES excryption with 
key and IV values.

https://github.com/muneebahmad/AESiOSObjC

Pass element ID to Javascript function

The problem for me was as simple as just not knowing Javascript well. I was trying to pass the name of the id using double quotes, when I should have been using single. And it worked fine.

This worked:

validateSelectizeDropdown('#PartCondition')

This did not:

validateSelectizeDropdown("#PartCondition")

And the function:

    function validateSelectizeDropdown(name) {
    if ($(name).val() === "") {
         //do something
    }
}

Fitting polynomial model to data in R

The easiest way to find the best fit in R is to code the model as:

lm.1 <- lm(y ~ x + I(x^2) + I(x^3) + I(x^4) + ...)

After using step down AIC regression

lm.s <- step(lm.1)

How do I convert a Swift Array to a String?

for any Element type

extension Array {

    func joined(glue:()->Element)->[Element]{
        var result:[Element] = [];
        result.reserveCapacity(count * 2);
        let last = count - 1;
        for (ix,item) in enumerated() {
            result.append(item);
            guard ix < last else{ continue }
            result.append(glue());
        }
        return result;
    }
}

"unadd" a file to svn before commit

Use svn revert --recursive folder_name


Warning

svn revert is inherently dangerous, since its entire purpose is to throw away data — namely, your uncommitted changes. Once you've reverted, Subversion provides no way to get back those uncommitted changes.

http://svnbook.red-bean.com/en/1.7/svn.ref.svn.c.revert.html

Java "?" Operator for checking null - What is it? (Not Ternary!)

This syntax does not exist in Java, nor is it slated to be included in any of the upcoming versions that I know of.

TSQL How do you output PRINT in a user defined function?

Tip: generate error.

declare @Day int, @Config_Node varchar(50)

    set @Config_Node = 'value to trace'

    set @Day = @Config_Node

You will get this message:

Conversion failed when converting the varchar value 'value to trace' to data type int.

Could not load file or assembly 'System.Web.Mvc'

Quick & Simple Solution: I faced this problem with Microsoft.AspNet.Mvc -Version 5.2.3 and after going through all these threads I found a simplest solution.

Just follow steps:

  1. Open NuGet Package Manager in Visual studio for your project
  2. Search for Microsoft.AspNet.Mvc
  3. When found, change action to Uninstall and Uninstall it
  4. Once done, install it again and try it now

This will automatically fix all issues with references. See image below:

enter image description here

How to check if a String contains another String in a case insensitive manner in Java?

One problem with the answer by Dave L. is when s2 contains regex markup such as \d, etc.

You want to call Pattern.quote() on s2:

Pattern.compile(Pattern.quote(s2), Pattern.CASE_INSENSITIVE).matcher(s1).find();

Can you remove elements from a std::list while iterating through it?

Removal invalidates only the iterators that point to the elements that are removed.

So in this case after removing *i , i is invalidated and you cannot do increment on it.

What you can do is first save the iterator of element that is to be removed , then increment the iterator and then remove the saved one.

Querying data by joining two tables in two database on different servers

Try this:

SELECT tab2.column_name  
FROM  [DB1.mdf].[dbo].[table_name_1] tab1 INNER JOIN [DB2.mdf].[dbo].[table_name_2]  tab2   
    ON tab1.col_name = tab2.col_name

What is the difference between a heuristic and an algorithm?

Actually I don't think that there is a lot in common between them. Some algorithm use heuristics in their logic (often to make fewer calculations or get faster results). Usually heuristics are used in the so called greedy algorithms.

Heuristics is some "knowledge" that we assume is good to use in order to get the best choice in our algorithm (when a choice should be taken). For example ... a heuristics in chess could be (always take the opponents' queen if you can, since you know this is the stronger figure). Heuristics do not guarantee you that will lead you to the correct answer, but (if the assumptions is correct) often get answer which are close to the best in much shorter time.

C++ Cout & Cin & System "Ambiguous"

This kind of thing doesn't just magically happen on its own; you changed something! In industry we use version control to make regular savepoints, so when something goes wrong we can trace back the specific changes we made that resulted in that problem.

Since you haven't done that here, we can only really guess. In Visual Studio, Intellisense (the technology that gives you auto-complete dropdowns and those squiggly red lines) works separately from the actual C++ compiler under the bonnet, and sometimes gets things a bit wrong.

In this case I'd ask why you're including both cstdlib and stdlib.h; you should only use one of them, and I recommend the former. They are basically the same header, a C header, but cstdlib puts them in the namespace std in order to "C++-ise" them. In theory, including both wouldn't conflict but, well, this is Microsoft we're talking about. Their C++ toolchain sometimes leaves something to be desired. Any time the Intellisense disagrees with the compiler has to be considered a bug, whichever way you look at it!

Anyway, your use of using namespace std (which I would recommend against, in future) means that std::system from cstdlib now conflicts with system from stdlib.h. I can't explain what's going on with std::cout and std::cin.

Try removing #include <stdlib.h> and see what happens.

If your program is building successfully then you don't need to worry too much about this, but I can imagine the false positives being annoying when you're working in your IDE.

Why is this jQuery click function not working?

You are supposed to add the javascript code in a $(document).ready(function() {}); block.

i.e.

$(document).ready(function() {
  $("#clicker").click(function () {
    alert("Hello!");
    $(".hide_div").hide();
  });
});

As jQuery documentation states: "A page can't be manipulated safely until the document is "ready." jQuery detects this state of readiness for you. Code included inside $( document ).ready() will only run once the page Document Object Model (DOM) is ready for JavaScript code to execute"

Can't use WAMP , port 80 is used by IIS 7.5

Left Click on wamp go to apache> select http.config Listen [::0]:8080

What is the difference between a 'closure' and a 'lambda'?

A lambda is just an anonymous function - a function defined with no name. In some languages, such as Scheme, they are equivalent to named functions. In fact, the function definition is re-written as binding a lambda to a variable internally. In other languages, like Python, there are some (rather needless) distinctions between them, but they behave the same way otherwise.

A closure is any function which closes over the environment in which it was defined. This means that it can access variables not in its parameter list. Examples:

def func(): return h
def anotherfunc(h):
   return func()

This will cause an error, because func does not close over the environment in anotherfunc - h is undefined. func only closes over the global environment. This will work:

def anotherfunc(h):
    def func(): return h
    return func()

Because here, func is defined in anotherfunc, and in python 2.3 and greater (or some number like this) when they almost got closures correct (mutation still doesn't work), this means that it closes over anotherfunc's environment and can access variables inside of it. In Python 3.1+, mutation works too when using the nonlocal keyword.

Another important point - func will continue to close over anotherfunc's environment even when it's no longer being evaluated in anotherfunc. This code will also work:

def anotherfunc(h):
    def func(): return h
    return func

print anotherfunc(10)()

This will print 10.

This, as you notice, has nothing to do with lambdas - they are two different (although related) concepts.

How can I use a C++ library from node.js?

Becareful with swig and C++: http://www.swig.org/Doc1.3/SWIG.html#SWIG_nn8

Running SWIG on C++ source files (what would appear in a .C or .cxx file) is not recommended. Even though SWIG can parse C++ class declarations, it ignores declarations that are decoupled from their original class definition (the declarations are parsed, but a lot of warning messages may be generated). For example:

/* Not supported by SWIG */
int foo::bar(int) {
    ... whatever ...
}

It's rarely to have a C++ class limited to only one .h file.

Also, the versions of swig supporting JavaScript is swig-3.0.1 or later.

class method generates "TypeError: ... got multiple values for keyword argument ..."

I want to add one more answer :

It happens when you try to pass positional parameter with wrong position order along with keyword argument in calling function.

there is difference between parameter and argument you can read in detail about here Arguments and Parameter in python

def hello(a,b=1, *args):
   print(a, b, *args)


hello(1, 2, 3, 4,a=12)

since we have three parameters :

a is positional parameter

b=1 is keyword and default parameter

*args is variable length parameter

so we first assign a as positional parameter , means we have to provide value to positional argument in its position order, here order matter. but we are passing argument 1 at the place of a in calling function and then we are also providing value to a , treating as keyword argument. now a have two values :

one is positional value: a=1

second is keyworded value which is a=12

Solution

We have to change hello(1, 2, 3, 4,a=12) to hello(1, 2, 3, 4,12) so now a will get only one positional value which is 1 and b will get value 2 and rest of values will get *args (variable length parameter)

additional information

if we want that *args should get 2,3,4 and a should get 1 and b should get 12

then we can do like this
def hello(a,*args,b=1): pass hello(1, 2, 3, 4,b=12)

Something more :

def hello(a,*c,b=1,**kwargs):
    print(b)
    print(c)
    print(a)
    print(kwargs)

hello(1,2,1,2,8,9,c=12)

output :

1

(2, 1, 2, 8, 9)

1

{'c': 12}

location.host vs location.hostname and cross-browser compatibility?

MDN: https://developer.mozilla.org/en/DOM/window.location

It seems that you will get the same result for both, but hostname contains clear host name without brackets or port number.

Add a link to an image in a css style sheet

You can not do that...

via css the URL you put on the background-image is just for the image.

Via HTML you have to add the href for your hyperlink in this way:

<a href="http://home.com" id="logo">Your logo</a>

With text-indent and some other css you can adjust your a element to show just the image and clicking on it you will go to your link.


EDIT:

I'm here again to show you and explain why my solution is much better:

<a href="http://home.com" id="logo">Your logo name</a>

This block of HTML is SEO friendly because you have some text inside your link!

How to style it with css:

#logo {
  background-image: url(images/logo.png);
  display: block;
  margin: 0 auto;
  text-indent: -9999px;
  width: 981px;
  height: 180px;
}

Then if you don't care about SEO good to choose the other answer.

Error: fix the version conflict (google-services plugin)

You must use only one version for all 3 libs

compile 'com.google.firebase:firebase-messaging:11.0.4'
compile 'com.google.android.gms:play-services-maps:11.0.4'
compile 'com.google.android.gms:play-services-location:11.0.4'

OR only use only 10.0.1 for 3 libs

what is Ljava.lang.String;@

I also met this problem when I've made ListView for android app:

Map<String, Object> m;

for(int i=0; i < dates.length; i++){
    m = new HashMap<String, Object>();
    m.put(ATTR_DATES, dates[i]);
    m.put(ATTR_SQUATS, squats[i]);
    m.put(ATTR_BP, benchpress[i]);
    m.put(ATTR_ROW, row[i]);
    data.add(m);
}

The problem was that I've forgotten to use the [i] index inside the loop

How to specify an element after which to wrap in css flexbox?

Setting a min-width on child elements will also create a breakpoint. For example breaking every 3 elements,

flex-grow: 1;
min-width: 33%; 

If there are 4 elements, this will have the 4th element wrap taking the full 100%. If there are 5 elements, the 4th and 5th elements will wrap and take each 50%.

Make sure to have parent element with,

flex-wrap: wrap

Android: Expand/collapse animation

I took @LenaYan 's solution that didn't work properly to me (because it was transforming the View to a 0 height view before collapsing and/or expanding) and made some changes.

Now it works great, by taking the View's previous height and start expanding with this size. Collapsing is the same.

You can simply copy and paste the code below:

public static void expand(final View v, int duration, int targetHeight) {

    int prevHeight  = v.getHeight();

    v.setVisibility(View.VISIBLE);
    ValueAnimator valueAnimator = ValueAnimator.ofInt(prevHeight, targetHeight);
    valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
        @Override
        public void onAnimationUpdate(ValueAnimator animation) {
            v.getLayoutParams().height = (int) animation.getAnimatedValue();
            v.requestLayout();
        }
    });
    valueAnimator.setInterpolator(new DecelerateInterpolator());
    valueAnimator.setDuration(duration);
    valueAnimator.start();
}

public static void collapse(final View v, int duration, int targetHeight) {
    int prevHeight  = v.getHeight();
    ValueAnimator valueAnimator = ValueAnimator.ofInt(prevHeight, targetHeight);
    valueAnimator.setInterpolator(new DecelerateInterpolator());
    valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
        @Override
        public void onAnimationUpdate(ValueAnimator animation) {
            v.getLayoutParams().height = (int) animation.getAnimatedValue();
            v.requestLayout();
        }
    });
    valueAnimator.setInterpolator(new DecelerateInterpolator());
    valueAnimator.setDuration(duration);
    valueAnimator.start();
}

Usage:

//Expanding the View
   expand(yourView, 2000, 200);

// Collapsing the View     
   collapse(yourView, 2000, 100);

Easy enough!

Thanks LenaYan for the initial code!

What does ENABLE_BITCODE do in xcode 7?

Bitcode refers to to the type of code: "LLVM Bitcode" that is sent to iTunes Connect. This allows Apple to use certain calculations to re-optimize apps further (e.g: possibly downsize executable sizes). If Apple needs to alter your executable then they can do this without a new build being uploaded.

This differs from: Slicing which is the process of Apple optimizing your app for a user's device based on the device's resolution and architecture. Slicing does not require Bitcode. (Ex: only including @2x images on a 5s)

App Thinning is the combination of slicing, bitcode, and on-demand resources

Bitcode is an intermediate representation of a compiled program. Apps you upload to iTunes Connect that contain bitcode will be compiled and linked on the App Store. Including bitcode will allow Apple to re-optimize your app binary in the future without the need to submit a new version of your app to the store.

Apple Documentation on App Thinning

Copying an array of objects into another array in javascript

I suggest using concat() if you are using nodeJS. In all other cases, I have found that slice(0) works fine.

Cannot find "Package Explorer" view in Eclipse

Try this

Window > Show View > Package Explorer

it will display the hidden 'Package Explorer' on your eclipse IDE.

• 'Window' is in your Eclipse' menubar.

Why can't Python parse this JSON data?

"Ultra JSON" or simply "ujson" can handle having [] in your JSON file input. If you're reading a JSON input file into your program as a list of JSON elements; such as, [{[{}]}, {}, [], etc...] ujson can handle any arbitrary order of lists of dictionaries, dictionaries of lists.

You can find ujson in the Python package index and the API is almost identical to Python's built-in json library.

ujson is also much faster if you're loading larger JSON files. You can see the performance details in comparison to other Python JSON libraries in the same link provided.

Google Script to see if text contains a value

Google Apps Script is javascript, you can use all the string methods...

var grade = itemResponse.getResponse();
if(grade.indexOf("9th")>-1){do something }

You can find doc on many sites, this one for example.

PHP - remove <img> tag from string

$this->load->helper('security');
$h=mysql_real_escape_string(strip_image_tags($comment));

If user inputs

<img src="#">

In the database table just insert character this #

Works for me

'printf' vs. 'cout' in C++

I would like say that extensibility lack of printf is not entirely true:
In C, it is true. But in C, there are no real classes.
In C++, it is possible to overload cast operator, so, overloading a char* operator and using printf like this:

Foo bar;
...;
printf("%s",bar);

can be possible, if Foo overload the good operator. Or if you made a good method. In short, printf is as extensible as cout for me.

Technical argument I can see for C++ streams (in general... not only cout.) are:

  • Typesafety. (And, by the way, if I want to print a single '\n' I use putchar('\n')... I will not use a nuke-bomb to kill an insect.).

  • Simpler to learn. (no "complicated" parameters to learn, just to use << and >> operators)

  • Work natively with std::string (for printf there is std::string::c_str(), but for scanf?)

For printf I see:

  • Easier, or at least shorter (in term of characters written) complex formatting. Far more readable, for me (matter of taste I guess).

  • Better control of what the function made (Return how many characters where written and there is the %n formatter: "Nothing printed. The argument must be a pointer to a signed int, where the number of characters written so far is stored." (from printf - C++ Reference)

  • Better debugging possibilities. For same reason as last argument.

My personal preferences go to printf (and scanf) functions, mainly because I love short lines, and because I don't think type problems on printing text are really hard to avoid. The only thing I deplore with C-style functions is that std::string is not supported. We have to go through a char* before giving it to printf (with the std::string::c_str() if we want to read, but how to write?)

MVC Calling a view from a different controller

I'm not really sure if I got your question right. Maybe something like

public class CommentsController : Controller
{
    [HttpPost]
    public ActionResult WriteComment(CommentModel comment)
    {
        // Do the basic model validation and other stuff
        try
        {
            if (ModelState.IsValid )
            {
                 // Insert the model to database like:
                 db.Comments.Add(comment);
                 db.SaveChanges();

                 // Pass the comment's article id to the read action
                 return RedirectToAction("Read", "Articles", new {id = comment.ArticleID});
            }
        }
        catch ( Exception e )
        {
             throw e;
        }
        // Something went wrong
        return View(comment);

    }
}


public class ArticlesController : Controller
{
    // id is the id of the article
    public ActionResult Read(int id)
    {
        // Get the article from database by id
        var model = db.Articles.Find(id);
        // Return the view
        return View(model);
    }
}

Javascript swap array elements

If you don't want to use temp variable in ES5, this is one way to swap array elements.

var swapArrayElements = function (a, x, y) {
  if (a.length === 1) return a;
  a.splice(y, 1, a.splice(x, 1, a[y])[0]);
  return a;
};

swapArrayElements([1, 2, 3, 4, 5], 1, 3); //=> [ 1, 4, 3, 2, 5 ]

IF function with 3 conditions

=if([Logical Test 1],[Action 1],if([Logical Test 2],[Action 1],if([Logical Test 3],[Action 3],[Value if all logical tests return false])))

Replace the components in the square brackets as necessary.

Object creation on the stack/heap?

  1. Object* o; o = new Object();

  2. Object* o = new Object();

Both these statement creates the object in the heap memory since you are creating the object using "new".

To be able to make the object creation happen in the stack, you need to follow this:

Object o;
Object *p = &o;

Java check to see if a variable has been initialized

Instance variables or fields, along with static variables, are assigned default values based on the variable type:

  • int: 0
  • char: \u0000 or 0
  • double: 0.0
  • boolean: false
  • reference: null

Just want to clarify that local variables (ie. declared in block, eg. method, for loop, while loop, try-catch, etc.) are not initialized to default values and must be explicitly initialized.

How to make sure you don't get WCF Faulted state exception?

If the transfer mode is Buffered then make sure that the values of MaxReceivedMessageSize and MaxBufferSize is same. I just resolved the faulted state issue this way after grappling with it for hours and thought i'll post it here if it helps someone.

How to prevent 'query timeout expired'? (SQLNCLI11 error '80040e31')

Turns out that the post (or rather the whole table) was locked by the very same connection that I tried to update the post with.

I had a opened record set of the post that was created by:

Set RecSet = Conn.Execute()

This type of recordset is supposed to be read-only and when I was using MS Access as database it did not lock anything. But apparently this type of record set did lock something on MS SQL Server 2012 because when I added these lines of code before executing the UPDATE SQL statement...

RecSet.Close
Set RecSet = Nothing

...everything worked just fine.

So bottom line is to be careful with opened record sets - even if they are read-only they could lock your table from updates.

LINK : fatal error LNK1561: entry point must be defined ERROR IN VC++

You can get this error if you define a project as an .exe but intent to create a .lib or a .dll

Enum "Inheritance"

Enums are not actual classes, even if they look like it. Internally, they are treated just like their underlying type (by default Int32). Therefore, you can only do this by "copying" single values from one enum to another and casting them to their integer number to compare them for equality.

Rounding to 2 decimal places in SQL

Try using the COLUMN command with the FORMAT option for that:

COLUMN COLUMN_NAME FORMAT 99.99
SELECT COLUMN_NAME FROM ....

Has Facebook sharer.php changed to no longer accept detailed parameters?

Your problem is caused by the lack of markers OpenGraph, as you say it is not possible that you implement for some reason.

For you, the only solution is to use the PHP Facebook API.

  1. First you must create the application in your facebook account.
  2. When creating the application you will have two key data for your code:

    YOUR_APP_ID 
    YOUR_APP_SECRET
    
  3. Download the Facebook PHP SDK from here.

  4. You can start with this code for share content from your site:

    <?php
      // Remember to copy files from the SDK's src/ directory to a
      // directory in your application on the server, such as php-sdk/
      require_once('php-sdk/facebook.php');
    
      $config = array(
        'appId' => 'YOUR_APP_ID',
        'secret' => 'YOUR_APP_SECRET',
        'allowSignedRequest' => false // optional but should be set to false for non-canvas apps
      );
    
      $facebook = new Facebook($config);
      $user_id = $facebook->getUser();
    ?>
    <html>
      <head></head>
      <body>
    
      <?php
        if($user_id) {
    
          // We have a user ID, so probably a logged in user.
          // If not, we'll get an exception, which we handle below.
          try {
            $ret_obj = $facebook->api('/me/feed', 'POST',
                                        array(
                                          'link' => 'www.example.com',
                                          'message' => 'Posting with the PHP SDK!'
                                     ));
            echo '<pre>Post ID: ' . $ret_obj['id'] . '</pre>';
    
            // Give the user a logout link 
            echo '<br /><a href="' . $facebook->getLogoutUrl() . '">logout</a>';
          } catch(FacebookApiException $e) {
            // If the user is logged out, you can have a 
            // user ID even though the access token is invalid.
            // In this case, we'll get an exception, so we'll
            // just ask the user to login again here.
            $login_url = $facebook->getLoginUrl( array(
                           'scope' => 'publish_stream'
                           )); 
            echo 'Please <a href="' . $login_url . '">login.</a>';
            error_log($e->getType());
            error_log($e->getMessage());
          }   
        } else {
    
          // No user, so print a link for the user to login
          // To post to a user's wall, we need publish_stream permission
          // We'll use the current URL as the redirect_uri, so we don't
          // need to specify it here.
          $login_url = $facebook->getLoginUrl( array( 'scope' => 'publish_stream' ) );
          echo 'Please <a href="' . $login_url . '">login.</a>';
    
        } 
    
      ?>      
    
      </body> 
    </html>
    

You can find more examples in the Facebook Developers site:

https://developers.facebook.com/docs/reference/php

Back to previous page with header( "Location: " ); in PHP

Just try this in Javascript:

 $previous = "javascript:history.go(-1)";

Or you can try it in PHP:

if(isset($_SERVER['HTTP_REFERER'])) {
    $previous = $_SERVER['HTTP_REFERER'];
}

Simple export and import of a SQLite database on Android

If you want this in kotlin . And perfectly working

 private fun exportDbFile() {

    try {

        //Existing DB Path
        val DB_PATH = "/data/packagename/databases/mydb.db"
        val DATA_DIRECTORY = Environment.getDataDirectory()
        val INITIAL_DB_PATH = File(DATA_DIRECTORY, DB_PATH)

        //COPY DB PATH
        val EXTERNAL_DIRECTORY: File = Environment.getExternalStorageDirectory()
        val COPY_DB = "/mynewfolder/mydb.db"
        val COPY_DB_PATH = File(EXTERNAL_DIRECTORY, COPY_DB)

        File(COPY_DB_PATH.parent!!).mkdirs()
        val srcChannel = FileInputStream(INITIAL_DB_PATH).channel

        val dstChannel = FileOutputStream(COPY_DB_PATH).channel
        dstChannel.transferFrom(srcChannel,0,srcChannel.size())
        srcChannel.close()
        dstChannel.close()

    } catch (excep: Exception) {
        Toast.makeText(this,"ERROR IN COPY $excep",Toast.LENGTH_LONG).show()
        Log.e("FILECOPYERROR>>>>",excep.toString())
        excep.printStackTrace()
    }

}

How to display loading image while actual image is downloading

Instead of just doing this quoted method from https://stackoverflow.com/a/4635440/3787376,

You can do something like this:

// show loading image
$('#loader_img').show();

// main image loaded ?
$('#main_img').on('load', function(){
  // hide/remove the loading image
  $('#loader_img').hide();
});

You assign load event to the image which fires when image has finished loading. Before that, you can show your loader image.

you can use a different jQuery function to make the loading image fade away, then be hidden:

// Show the loading image.
$('#loader_img').show();

// When main image loads:
$('#main_img').on('load', function(){
  // Fade out and hide the loading image.
  $('#loader_img').fadeOut(100); // Time in milliseconds.
});

"Once the opacity reaches 0, the display style property is set to none." http://api.jquery.com/fadeOut/

Or you could not use the jQuery library because there are already simple cross-browser JavaScript methods.

Class file has wrong version 52.0, should be 50.0

In your IntelliJ idea find tools.jar replace it with tools.jar from yout JDK8

Django template how to look up a dictionary value with a variable

You can't by default. The dot is the separator / trigger for attribute lookup / key lookup / slice.

Dots have a special meaning in template rendering. A dot in a variable name signifies a lookup. Specifically, when the template system encounters a dot in a variable name, it tries the following lookups, in this order:

  • Dictionary lookup. Example: foo["bar"]
  • Attribute lookup. Example: foo.bar
  • List-index lookup. Example: foo[bar]

But you can make a filter which lets you pass in an argument:

https://docs.djangoproject.com/en/dev/howto/custom-template-tags/#writing-custom-template-filters

@register.filter(name='lookup')
def lookup(value, arg):
    return value[arg]

{{ mydict|lookup:item.name }}

Force "git push" to overwrite remote files

You want to force push

What you basically want to do is to force push your local branch, in order to overwrite the remote one.

If you want a more detailed explanation of each of the following commands, then see my details section below. You basically have 4 different options for force pushing with Git:

git push <remote> <branch> -f
git push origin master -f # Example

git push <remote> -f
git push origin -f # Example

git push -f

git push <remote> <branch> --force-with-lease

If you want a more detailed explanation of each command, then see my long answers section below.

Warning: force pushing will overwrite the remote branch with the state of the branch that you're pushing. Make sure that this is what you really want to do before you use it, otherwise you may overwrite commits that you actually want to keep.

Force pushing details

Specifying the remote and branch

You can completely specify specific branches and a remote. The -f flag is the short version of --force

git push <remote> <branch> --force
git push <remote> <branch> -f

Omitting the branch

When the branch to push branch is omitted, Git will figure it out based on your config settings. In Git versions after 2.0, a new repo will have default settings to push the currently checked-out branch:

git push <remote> --force

while prior to 2.0, new repos will have default settings to push multiple local branches. The settings in question are the remote.<remote>.push and push.default settings (see below).

Omitting the remote and the branch

When both the remote and the branch are omitted, the behavior of just git push --force is determined by your push.default Git config settings:

git push --force
  • As of Git 2.0, the default setting, simple, will basically just push your current branch to its upstream remote counter-part. The remote is determined by the branch's branch.<remote>.remote setting, and defaults to the origin repo otherwise.

  • Before Git version 2.0, the default setting, matching, basically just pushes all of your local branches to branches with the same name on the remote (which defaults to origin).

You can read more push.default settings by reading git help config or an online version of the git-config(1) Manual Page.

Force pushing more safely with --force-with-lease

Force pushing with a "lease" allows the force push to fail if there are new commits on the remote that you didn't expect (technically, if you haven't fetched them into your remote-tracking branch yet), which is useful if you don't want to accidentally overwrite someone else's commits that you didn't even know about yet, and you just want to overwrite your own:

git push <remote> <branch> --force-with-lease

You can learn more details about how to use --force-with-lease by reading any of the following:

Command to find information about CPUs on a UNIX machine

The nproc command shows the number of processing units available:
$ nproc

Sample outputs: 4

lscpu gathers CPU architecture information form /proc/cpuinfon in human-read-able format:
$ lscpu

Sample outputs:

Architecture: x86_64
CPU op-mode(s): 32-bit, 64-bit
Byte Order: Little Endian
CPU(s): 8
On-line CPU(s) list: 0-7
Thread(s) per core: 1
Core(s) per socket: 4
CPU socket(s): 2
NUMA node(s): 1
Vendor ID: GenuineIntel
CPU family: 6
Model: 15
Stepping: 7
CPU MHz: 1866.669
BogoMIPS: 3732.83
Virtualization: VT-x
L1d cache: 32K
L1i cache: 32K
L2 cache: 4096K
NUMA node0 CPU(s): 0-7

Getting Image from URL (Java)

Directly calling a URL to get an image may concern with major security issues. You need to ensure that you have sufficient rights to access that resource. However You can use ByteOutputStream to read image file. This is an example (Its just an example, you need to do necessary changes as per your requirement.)

ByteArrayOutputStream bis = new ByteArrayOutputStream();
InputStream is = null;
try {
  is = url.openStream ();
  byte[] bytebuff = new byte[4096]; 
  int n;

  while ( (n = is.read(bytebuff)) > 0 ) {
    bis.write(bytebuff, 0, n);
  }
}

Best way to convert pdf files to tiff files

I like PDFTIFF.com to convert PDF to TIFF, it can handle unlimited pages

iOS 7 status bar back to iOS 6 default style in iPhone app?

If you're using Interface builder, try this:

In your xib file:

1) Select the main view, set the background color to black (or whatever color you want the status bar to be

2) Make sure the background is a self contained subview positioned as a top level child of the controller's view.
Move your background to become a direct child of the controller's view. Check the autosizing panel to be sure that you've locked all frame edges, activated both flexibility axes, and if this is a UIImageView, set the content mode to Scale to fill. Programmatically this translates to contentMode set to UIViewContentModeScaleToFill and has its auto resizing mask set to (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight).

3) Now move everything that is locked to the top - down by 20 pts and set a iOS 6/7 delta Y to -20.
All top level children that are locked to the top frame in the autosizing panel need to be moved down by 20pts and have their iOS 6/7 delta Y set to -20. (Cmd select all of those, and click down arrow 20 times - is there a better way anyone?)

4) Adjust the iOS 6/7 delta height of all of the above items that had a flexible height. Any of the items that were locked to the frame top and bottom and had flexible height enabled in the autosizing panel must also have their iOS 6/7 delta height set to 20. That includes the background view mentioned above. This may seem anti-intuitive, but due to the order in which these are applied, it is necessary. The frame height is set first (based on device), then the deltas are applied, and finally the autosizing masks are applied based upon the offset positions of all of the child frames - think it through for a bit, it will make sense.

5) Finally, items that were locked to the bottom frame but not the top frame need no deltas at all.

That will give you the identical status bar in iOS7 and iOS6.

On the other hand, if you want iOS7 styling while maintaining iOS6 compatibility, then set the delta Y / delta height values to 0 for the background view.

To see more iOS7 migration info read the full post: http://uncompiled.blogspot.com/2013/09/legacy-compatible-offsets-in-ios7.html

How to list files and folder in a dir (PHP)

If you have problems with accessing to the path, maybe you need to put this:

$root = $_SERVER['DOCUMENT_ROOT'];
$path = "/cv/"; 

// Open the folder
 $dir_handle = @opendir($root . $path) or die("Unable to open $path");

Delete files older than 15 days using PowerShell

If you are having problems with the above examples on a Windows 10 box, try replacing .CreationTime with .LastwriteTime. This worked for me.

dir C:\locationOfFiles -ErrorAction SilentlyContinue | Where { ((Get-Date)-$_.LastWriteTime).days -gt 15 } | Remove-Item -Force

List of Java class file format major version numbers?

If you're having some problem about "error compiler of class file", it's possible to resolve this by changing the project's JRE to its correspondent through Eclipse.

  1. Build path
  2. Configure build path
  3. Change library to correspondent of table that friend shows last.
  4. Create "jar file" and compile and execute.

I did that and it worked.

Virtualbox shared folder permissions

After adding the user to the vboxsf group, you might need to completely log out of the gnome/xfce/??? session, because someone long ago decided that group affiliation should be cached at first login to the window system.

Or go old school:

% newgrp vboxsf

in any shell you want to use to access the folder. Luckily, newgrp looks up the group list for itself and doesn't used the cached values. You'll still need to log out and back in to access the folder from something other than a shell.

Remove sensitive files and their commits from Git history

You can use git forget-blob.

The usage is pretty simple git forget-blob file-to-forget. You can get more info here

https://ownyourbits.com/2017/01/18/completely-remove-a-file-from-a-git-repository-with-git-forget-blob/

It will disappear from all the commits in your history, reflog, tags and so on

I run into the same problem every now and then, and everytime I have to come back to this post and others, that's why I automated the process.

Credits to contributors from Stack Overflow that allowed me to put this together

SQL Group By with an Order By

I don't know about MySQL, but in MS SQL, you can use the column index in the order by clause. I've done this before when doing counts with group bys as it tends to be easier to work with.

So

SELECT COUNT(id), `Tag` from `images-tags`
GROUP BY `Tag`
ORDER BY COUNT(id) DESC
LIMIT 20

Becomes

SELECT COUNT(id), `Tag` from `images-tags`
GROUP BY `Tag`
ORDER 1 DESC
LIMIT 20

In jQuery, how do I get the value of a radio button when they all have the same name?

DEMO : https://jsfiddle.net/ipsjolly/xygr065w/

$(function(){
    $("#submit").click(function(){      
        alert($('input:radio:checked').val());
    });
 });

How do I stretch a background image to cover the entire HTML element?

Simply make a div to be the direct child of body (with the class name bg for example), encompassing all other elements in the body, and add this to the CSS file:

.bg {
    background-image: url('_images/home.jpg');//Put your appropriate image URL here
    background-size: 100% 100%; //You need to put 100% twice here to stretch width and height
}

Refer to this link: https://www.w3schools.com/css/css_rwd_images.asp Scroll down to the part that says:

  1. If the background-size property is set to "100% 100%", the background image will stretch to cover the entire content area

There it shows the 'img_flowers.jpg' stretching to the size of the screen or browser regardless of how you resize it.

JavaScript: Check if mouse button down?

Regarding Pax' solution: it doesn't work if user clicks more than one button intentionally or accidentally. Don't ask me how I know :-(.

The correct code should be like that:

var mouseDown = 0;
document.body.onmousedown = function() { 
  ++mouseDown;
}
document.body.onmouseup = function() {
  --mouseDown;
}

With the test like this:

if(mouseDown){
  // crikey! isn't she a beauty?
}

If you want to know what button is pressed, be prepared to make mouseDown an array of counters and count them separately for separate buttons:

// let's pretend that a mouse doesn't have more than 9 buttons
var mouseDown = [0, 0, 0, 0, 0, 0, 0, 0, 0],
    mouseDownCount = 0;
document.body.onmousedown = function(evt) { 
  ++mouseDown[evt.button];
  ++mouseDownCount;
}
document.body.onmouseup = function(evt) {
  --mouseDown[evt.button];
  --mouseDownCount;
}

Now you can check what buttons were pressed exactly:

if(mouseDownCount){
  // alright, let's lift the little bugger up!
  for(var i = 0; i < mouseDown.length; ++i){
    if(mouseDown[i]){
      // we found it right there!
    }
  }
}

Now be warned that the code above would work only for standard-compliant browsers that pass you a button number starting from 0 and up. IE uses a bit mask of currently pressed buttons:

  • 0 for "nothing is pressed"
  • 1 for left
  • 2 for right
  • 4 for middle
  • and any combination of above, e.g., 5 for left + middle

So adjust your code accordingly! I leave it as an exercise.

And remember: IE uses a global event object called … "event".

Incidentally IE has a feature useful in your case: when other browsers send "button" only for mouse button events (onclick, onmousedown, and onmouseup), IE sends it with onmousemove too. So you can start listening for onmousemove when you need to know the button state, and check for evt.button as soon as you got it — now you know what mouse buttons were pressed:

// for IE only!
document.body.onmousemove = function(){
  if(event.button){
    // aha! we caught a feisty little sheila!
  }
};

Of course you get nothing if she plays dead and not moving.

Relevant links:

Update #1: I don't know why I carried over the document.body-style of code. It will be better to attach event handlers directly to the document.

Calculate time difference in minutes in SQL Server

You can use DATEDIFF(it is a built-in function) and % (for scale calculation) and CONCAT for make result to only one column

select CONCAT('Month: ',MonthDiff,' Days: ' , DayDiff,' Minutes: ',MinuteDiff,' Seconds: ',SecondDiff) as T  from 
(SELECT DATEDIFF(MONTH, '2017-10-15 19:39:47' , '2017-12-31 23:59:59') % 12 as MonthDiff,
        DATEDIFF(DAY, '2017-10-15 19:39:47' , '2017-12-31 23:59:59') % 30 as DayDiff,
        DATEDIFF(HOUR, '2017-10-15 19:39:47' , '2017-12-31 23:59:59') % 24 as HourDiff,
        DATEDIFF(MINUTE, '2017-10-15 19:39:47' , '2017-12-31 23:59:59') % 60 AS MinuteDiff,
        DATEDIFF(SECOND, '2017-10-15 19:39:47' , '2017-12-31 23:59:59') % 60 AS SecondDiff) tbl

Find a value anywhere in a database

If you need to run such search only once then you can probably go with any of the scripts already shown in other answers. But otherwise, I’d recommend using ApexSQL Search for this. It’s a free SSMS addin and it really saved me a lot of time.

Before running any of the scripts you should customize it based on the data type you want to search. If you know you are searching for datetime column then there is no need to search through nvarchar columns. This will speed up all of the queries above.

What does the line "#!/bin/sh" mean in a UNIX shell script?

The first line tells the shell that if you execute the script directly (./run.sh; as opposed to /bin/sh run.sh), it should use that program (/bin/sh in this case) to interpret it.

You can also use it to pass arguments, commonly -e (exit on error), or use other programs (/bin/awk, /usr/bin/perl, etc).

check if a std::vector contains a certain object?

If searching for an element is important, I'd recommend std::set instead of std::vector. Using this:

std::find(vec.begin(), vec.end(), x) runs in O(n) time, but std::set has its own find() member (ie. myset.find(x)) which runs in O(log n) time - that's much more efficient with large numbers of elements

std::set also guarantees all the added elements are unique, which saves you from having to do anything like if not contained then push_back()....

Chrome extension: accessing localStorage in content script

Sometimes it may be better to use chrome.storage API. It's better then localStorage because you can:

  • store information from your content script without the need for message passing between content script and extension;
  • store your data as JavaScript objects without serializing them to JSON (localStorage only stores strings).

Here's a simple code demonstrating the use of chrome.storage. Content script gets the url of visited page and timestamp and stores it, popup.js gets it from storage area.

content_script.js

(function () {
    var visited = window.location.href;
    var time = +new Date();
    chrome.storage.sync.set({'visitedPages':{pageUrl:visited,time:time}}, function () {
        console.log("Just visited",visited)
    });
})();

popup.js

(function () {
    chrome.storage.onChanged.addListener(function (changes,areaName) {
        console.log("New item in storage",changes.visitedPages.newValue);
    })
})();

"Changes" here is an object that contains old and new value for a given key. "AreaName" argument refers to name of storage area, either 'local', 'sync' or 'managed'.

Remember to declare storage permission in manifest.json.

manifest.json

...
"permissions": [
    "storage"
 ],
...

Data truncated for column?

when i first tried to import csv into mysql , i got the same error , and then i figured out mysql table i created doesn't have the character length of the importing csv field , so if it's the first time importing csv

  1. its a good idea to give more character length .
  2. label all fields as varchar or text , don't blend int or other values.

then you are good to go.

How to use NSURLConnection to connect with SSL for an untrusted cert?

To complement the accepted answer, for much better security, you could add your server certificate or your own root CA certificate to keychain( https://stackoverflow.com/a/9941559/1432048), however doing this alone won't make NSURLConnection authenticate your self-signed server automatically. You still need to add the below code to your NSURLConnection delegate, it's copied from Apple sample code AdvancedURLConnections, and you need to add two files(Credentials.h, Credentials.m) from apple sample code to your projects.

- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace {
return [protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust];
}

- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
//        if ([trustedHosts containsObject:challenge.protectionSpace.host])

    OSStatus                err;
    NSURLProtectionSpace *  protectionSpace;
    SecTrustRef             trust;
    SecTrustResultType      trustResult;
    BOOL                    trusted;

    protectionSpace = [challenge protectionSpace];
    assert(protectionSpace != nil);

    trust = [protectionSpace serverTrust];
    assert(trust != NULL);
    err = SecTrustEvaluate(trust, &trustResult);
    trusted = (err == noErr) && ((trustResult == kSecTrustResultProceed) || (trustResult == kSecTrustResultUnspecified));

    // If that fails, apply our certificates as anchors and see if that helps.
    //
    // It's perfectly acceptable to apply all of our certificates to the SecTrust
    // object, and let the SecTrust object sort out the mess.  Of course, this assumes
    // that the user trusts all certificates equally in all situations, which is implicit
    // in our user interface; you could provide a more sophisticated user interface
    // to allow the user to trust certain certificates for certain sites and so on).

    if ( ! trusted ) {
        err = SecTrustSetAnchorCertificates(trust, (CFArrayRef) [Credentials sharedCredentials].certificates);
        if (err == noErr) {
            err = SecTrustEvaluate(trust, &trustResult);
        }
        trusted = (err == noErr) && ((trustResult == kSecTrustResultProceed) || (trustResult == kSecTrustResultUnspecified));
    }
    if(trusted)
        [challenge.sender useCredential:[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust] forAuthenticationChallenge:challenge];
}

[challenge.sender continueWithoutCredentialForAuthenticationChallenge:challenge];
}

Equivalent VB keyword for 'break'

In both Visual Basic 6.0 and VB.NET you would use:

  • Exit For to break from For loop
  • Wend to break from While loop
  • Exit Do to break from Do loop

depending on the loop type. See Exit Statements for more details.

How to import/include a CSS file using PHP code and not HTML code?

Just put

echo "<link rel='stylesheet' type='text/css' href='CSS/main.css'>";

inside the php code, then your style is incuded. Worked for me, I tried.

C++ auto keyword. Why is it magic?

The auto keyword is an important and frequently used keyword for C ++.When initializing a variable, auto keyword is used for type inference(also called type deduction).

There are 3 different rules regarding the auto keyword.

First Rule

auto x = expr; ----> No pointer or reference, only variable name. In this case, const and reference are ignored.

int  y = 10;
int& r = y;
auto x = r; // The type of variable x is int. (Reference Ignored)

const int y = 10;
auto x = y; // The type of variable x is int. (Const Ignored)

int y = 10;
const int& r = y;
auto x = r; // The type of variable x is int. (Both const and reference Ignored)

const int a[10] = {};
auto x = a; //  x is const int *. (Array to pointer conversion)

Note : When the name defined by auto is given a value with the name of a function,
       the type inference will be done as a function pointer.

Second Rule

auto& y = expr; or auto* y = expr; ----> Reference or pointer after auto keyword.

Warning : const is not ignored in this rule !!! .

int y = 10;
auto& x = y; // The type of variable x is int&.

Warning : In this rule, array to pointer conversion (array decay) does not occur !!!.

auto& x = "hello"; // The type of variable x is  const char [6].

static int x = 10;
auto y = x; // The variable y is not static.Because the static keyword is not a type. specifier 
            // The type of variable x is int.

Third Rule

auto&& z = expr; ----> This is not a Rvalue reference.

Warning : If the type inference is in question and the && token is used, the names introduced like this are called "Forwarding Reference" (also called Universal Reference).

auto&& r1 = x; // The type of variable r1 is int&.Because x is Lvalue expression. 

auto&& r2 = x+y; // The type of variable r2 is int&&.Because x+y is PRvalue expression. 

Can you detect "dragging" in jQuery?

// here is how you can detect dragging in all four directions
var isDragging = false;
$("some DOM element").mousedown(function(e) {
    var previous_x_position = e.pageX;
    var previous_y_position = e.pageY;

    $(window).mousemove(function(event) {
        isDragging = true;
        var x_position = event.pageX;
        var y_position = event.pageY;

        if (previous_x_position < x_position) {
            alert('moving right');
        } else {
            alert('moving left');
        }
        if (previous_y_position < y_position) {
            alert('moving down');
        } else {
            alert('moving up');
        }
        $(window).unbind("mousemove");
    });
}).mouseup(function() {
    var wasDragging = isDragging;
    isDragging = false;
    $(window).unbind("mousemove");
});

How do I check when a UITextField changes?

You can make this connection in interface builder.

  1. In your storyboard, click the assistant editor at the top of the screen (two circles in the middle). Assistant editor selected

  2. Ctrl + Click on the textfield in interface builder.

  3. Drag from EditingChanged to inside your view controller class in the assistant view. Making connection

  4. Name your function ("textDidChange" for example) and click connect. Naming function

Is it possible to ping a server from Javascript?

It might be a lot easier than all that. If you want your page to load then check on the availability or content of some foreign page to trigger other web page activity, you could do it using only javascript and php like this.

yourpage.php

<?php
if (isset($_GET['urlget'])){
  if ($_GET['urlget']!=''){
    $foreignpage= file_get_contents('http://www.foreignpage.html');
    // you could also use curl for more fancy internet queries or if http wrappers aren't active in your php.ini
    // parse $foreignpage for data that indicates your page should proceed
    echo $foreignpage; // or a portion of it as you parsed
    exit();  // this is very important  otherwise you'll get the contents of your own page returned back to you on each call
  }
}
?>

<html>
  mypage html content
  ...

<script>
var stopmelater= setInterval("getforeignurl('?urlget=doesntmatter')", 2000);

function getforeignurl(url){
  var handle= browserspec();
  handle.open('GET', url, false);
  handle.send();
  var returnedPageContents= handle.responseText;
  // parse page contents for what your looking and trigger javascript events accordingly.
  // use handle.open('GET', url, true) to allow javascript to continue executing. must provide a callback function to accept the page contents with handle.onreadystatechange()
}
function browserspec(){
  if (window.XMLHttpRequest){
    return new XMLHttpRequest();
  }else{
    return new ActiveXObject("Microsoft.XMLHTTP");
  }
}

</script>

That should do it.

The triggered javascript should include clearInterval(stopmelater)

Let me know if that works for you

Jerry

How do I move a file (or folder) from one folder to another in TortoiseSVN?

In Windows Explorer, with the right-mouse button, click and drag the file from where it is to where you want it. Upon releasing the right-mouse button, you will see a context menu with options such as "SVN Move versioned file here".

http://tortoisesvn.net/most-forgotten-feature

Differences between Emacs and Vim

If you are looking for an objective analysis of both the editors, look at their origins and the philosophy behind their respective designs. Think, which one would suit you better and learn it (and learn it and learn it, because it takes time before you being to discover its true utility as against any IDE). An Introduction to Display Editing with Vi was written by Bill Joy and Mark Horton and he explains why he choose modal design and rationale for various key strokes ( it helps me to remember that CTRL-W +W (will switch to next Window and it will same for CTRL W+ CTRL W, just in case you held the CTRL key for a longer duration.

Here is a link to Emacs timeline and has the reference to Multics Emacs paper. Hereis RMS paper on Emacs, where I see the stress is on a programmable text editor (even way back in 1981 and before).

I have not read the emacs papers, but have read Bill Joy's vi paper a couple of times. Both are old, but still you will get the philosophy and you might choose to use the current tool (vim 7.x or emacs 25?)

Edit: I forgot to mention that it takes patience and imagination to read both these papers as it takes you back in time while reading it. But it is worth.

Heroku deployment error H10 (App crashed)

After going through the entire list of answers I stumbled upon this website: https://status.heroku.com/ which details the current status/incidents with Heroku. Its always safe to check out for incidents before banging your head against the wall. For me, it was the attached incident report published on the above mentioned link that was causing the error.

SERVER INCIDENT UPDATE

Formatting code in Notepad++

We can use the following shortcut in the latest version of notepad++ for formatting the code

Alt + Ctrl + Shift + B

Fit Image into PictureBox

Imam Mahdi aj SizeMode Change in properties

You can use the properties section

Convert Time DataType into AM PM Format:

Try this:

select CONVERT(varchar(15),CAST('2014-05-28 16:07:54.647' AS TIME),100) as CreatedTime

How to convert a python numpy array to an RGB image with Opencv 2.4?

You are looking for scipy.misc.toimage:

import scipy.misc
rgb = scipy.misc.toimage(np_array)

It seems to be also in scipy 1.0, but has a deprecation warning. Instead, you can use pillow and PIL.Image.fromarray

Import .bak file to a database in SQL server

On SQL Server Management Studio

  1. Right click Databases on left pane (Object Explorer)
  2. Click Restore Database...
  3. Choose Device, click ..., and add your .bak file
  4. Click OK, then OK again

Done.

How do I show my global Git configuration?

If you just want to list one part of the Git configuration, such as alias, core, remote, etc., you could just pipe the result through grep. Something like:

git config --global -l | grep core

Construct pandas DataFrame from items in nested dictionary

pd.concat accepts a dictionary. With this in mind, it is possible to improve upon the currently accepted answer in terms of simplicity and performance by use a dictionary comprehension to build a dictionary mapping keys to sub-frames.

pd.concat({k: pd.DataFrame(v).T for k, v in user_dict.items()}, axis=0)

Or,

pd.concat({
        k: pd.DataFrame.from_dict(v, 'index') for k, v in user_dict.items()
    }, 
    axis=0)

              att_1     att_2
12 Category 1     1  whatever
   Category 2    23   another
15 Category 1    10       foo
   Category 2    30       bar

Break or return from Java 8 stream forEach?

What about this one:

final BooleanWrapper condition = new BooleanWrapper();
someObjects.forEach(obj -> {
   if (condition.ok()) {
     // YOUR CODE to control
     condition.stop();
   }
});

Where BooleanWrapper is a class you must implement to control the flow.

Server configuration is missing in Eclipse

If you're not too attached to your current workspace you can create a new workspace, follow BalusC's steps for server creation, and recreate your project in the new workspace.

I got the same error after installing Eclipse Java EE IDE for Web Developers(Juno) but using the workspace of a much older Eclipse installation. When I created a new workspace I was able to get my Tomcat server running without this error.

Excel VBA Run-time Error '32809' - Trying to Understand it

It seems that 32809 is a general error message. After struggling for some time, I found that I had not clicked on the "Enable Macros" security button at the below the workbook ribbon. Once I did this, everything worked fine.

Converting map to struct

You can do it ... it may get a bit ugly and you'll be faced with some trial and error in terms of mapping types .. but heres the basic gist of it:

func FillStruct(data map[string]interface{}, result interface{}) {
    t := reflect.ValueOf(result).Elem()
    for k, v := range data {
        val := t.FieldByName(k)
        val.Set(reflect.ValueOf(v))
    }
}

Working sample: http://play.golang.org/p/PYHz63sbvL