Programs & Examples On #Resume

Starting something again after stopping/pausing it. (DO NOT USE for any topic related to employment or CVs)

Pylint "unresolved import" error in Visual Studio Code

I have resolved import error by Ctrl + Shift + P. Type "Preferences settings" and select the option Preferences Open Settings (JSON)

And add the line "python.pythonPath": "/usr/bin/"

So the JSON content should look like:

{
    "python.pythonPath": "/usr/bin/"
}

Keep other configuration lines if they are present. This should import all modules that you have installed using PIP for autocomplete.

Axios Delete request with body and headers?

I had the same issue I solved it like that:

axios.delete(url, {data:{username:"user", password:"pass"}, headers:{Authorization: "token"}})

Bootstrap 4, How do I center-align a button?

Try this with bootstrap

CODE:

<div class="row justify-content-center">
  <button type="submit" class="btn btn-primary">btnText</button>
</div>

LINK:

https://getbootstrap.com/docs/4.1/layout/grid/#variable-width-content

Set selected item in Android BottomNavigationView

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

   bottomNavigationView.setOnNavigationItemSelectedListener(this);
   Menu menu = bottomNavigationView.getMenu();
   this.onNavigationItemSelected(menu.findItem(R.id.action_favorites));
}

How to request Location Permission at runtime

After having it defined in your manifest file, a friendlier alternative to the native solution would be using Aaper: https://github.com/LikeTheSalad/aaper like so:

@EnsurePermissions(permissions = [Manifest.permission.ACCESS_FINE_LOCATION])
private fun scanForLocation() {
    // Your code that needs the location permission granted.
}

Disclaimer, I'm the creator of Aaper.

How to add a classname/id to React-Bootstrap Component?

1st way is to use props

<Row id = "someRandomID">

Wherein, in the Definition, you may just go

const Row = props  => {
 div id = {props.id}
}

The same could be done with class, replacing id with className in the above example.


You might as well use react-html-id, that is an npm package. This is an npm package that allows you to use unique html IDs for components without any dependencies on other libraries.

Ref: react-html-id


Peace.

Swift 3 URLSession.shared() Ambiguous reference to member 'dataTask(with:completionHandler:) error (bug)

In my case error was in NSURL

let url = NSURL(string: urlString)

In Swift 3 you must write just URL:

let url = URL(string: urlString)

How do I correctly upgrade angular 2 (npm) to the latest version?

Best way to do is use the extension(pflannery.vscode-versionlens) in vscode.

this checks for all satisfy and checks for best fit.

i had lot of issues with updating and keeping my app functioining unitll i let verbose lense did the check and then i run

npm i

to install newly suggested dependencies.

Why Is `Export Default Const` invalid?

You can also do something like this if you want to export default a const/let, instead of

const MyComponent = ({ attr1, attr2 }) => (<p>Now Export On other Line</p>);
export default MyComponent

You can do something like this, which I do not like personally.

let MyComponent;
export default MyComponent = ({ }) => (<p>Now Export On SameLine</p>);

Quicker way to get all unique values of a column in VBA?

Use Excel's AdvancedFilter function to do this.

Using Excels inbuilt C++ is the fastest way with smaller datasets, using the dictionary is faster for larger datasets. For example:

Copy values in Column A and insert the unique values in column B:

Range("A1:A6").AdvancedFilter Action:=xlFilterCopy, CopyToRange:=Range("B1"), Unique:=True

It works with multiple columns too:

Range("A1:B4").AdvancedFilter Action:=xlFilterCopy, CopyToRange:=Range("D1:E1"), Unique:=True

Be careful with multiple columns as it doesn't always work as expected. In those cases I resort to removing duplicates which works by choosing a selection of columns to base uniqueness. Ref: MSDN - Find and remove duplicates

enter image description here

Here I remove duplicate columns based on the third column:

Range("A1:C4").RemoveDuplicates Columns:=3, Header:=xlNo

Here I remove duplicate columns based on the second and third column:

Range("A1:C4").RemoveDuplicates Columns:=Array(2, 3), Header:=xlNo

Unprotect workbook without password

No longer works for spreadsheets Protected with Excel 2013 or later -- they improved the pw hash. So now need to unzip .xlsx and hack the internals.

The resource could not be loaded because the App Transport Security policy requires the use of a secure connection

If you are using Xcode 8.0 to 8.3.3 and swift 2.2 to 3.0

In my case need to change in URL http:// to https:// (if not working then try)

Add an App Transport Security Setting: Dictionary.
Add a NSAppTransportSecurity: Dictionary.
Add a NSExceptionDomains: Dictionary.
Add a yourdomain.com: Dictionary.  (Ex: stackoverflow.com)

Add Subkey named " NSIncludesSubdomains" as Boolean: YES
Add Subkey named " NSExceptionAllowsInsecureHTTPLoads" as Boolean: YES

enter image description here

Android "gps requires ACCESS_FINE_LOCATION" error, even though my manifest file contains this

My simple solution is this

if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) ==
        PackageManager.PERMISSION_GRANTED &&
        ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) ==
        PackageManager.PERMISSION_GRANTED) {
    googleMap.setMyLocationEnabled(true);
    googleMap.getUiSettings().setMyLocationButtonEnabled(true);
} else {
    Toast.makeText(this, R.string.error_permission_map, Toast.LENGTH_LONG).show();
}

or you can open permission dialog in else like this

} else {
   ActivityCompat.requestPermissions(this, new String[] {
      Manifest.permission.ACCESS_FINE_LOCATION, 
      Manifest.permission.ACCESS_COARSE_LOCATION }, 
      TAG_CODE_PERMISSION_LOCATION);
}

How to make HTTP Post request with JSON body in Swift

a combination of several answers found in my attempt to not use 3rd party frameworks like Alamofire.

    let body: [String: Any] = ["provider": "Google", "email": "[email protected]"]
    let api_url = "https://erics.es/p/u"
    let url = URL(string: api_url)!
    var request = URLRequest(url: url)

    do {
        let jsonData = try JSONSerialization.data(withJSONObject: body, options: .prettyPrinted)
        request.httpBody = jsonData
    } catch let e {
        print(e)
    }

    request.httpMethod = HTTPMethod.post.rawValue
    request.addValue("application/json", forHTTPHeaderField: "Content-Type")

    let task = URLSession.shared.dataTask(with: request) { data, response, error in
        guard let data = data, error == nil else {
            print(error?.localizedDescription ?? "No data")
            return
        }
        let responseJSON = try? JSONSerialization.jsonObject(with: data, options: [])
        if let responseJSON = responseJSON as? [String: Any] {
            print(responseJSON)
        }
    }

    task.resume()

NSURLSession/NSURLConnection HTTP load failed on iOS 9

Found solution:

In iOS9, ATS enforces best practices during network calls, including the use of HTTPS.

From Apple documentation:

ATS prevents accidental disclosure, provides secure default behavior, and is easy to adopt. You should adopt ATS as soon as possible, regardless of whether you’re creating a new app or updating an existing one. If you’re developing a new app, you should use HTTPS exclusively. If you have an existing app, you should use HTTPS as much as you can right now, and create a plan for migrating the rest of your app as soon as possible.

In beta 1, currently there is no way to define this in info.plist. Solution is to add it manually:

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
</dict>

enter image description here

Update1: This is a temporary workaround until you're ready to adopt iOS9 ATS support.

Update2: For more details please refer following link: http://ste.vn/2015/06/10/configuring-app-transport-security-ios-9-osx-10-11/

Update3: If you are trying to connect to a host (YOURHOST.COM) that only has TLS 1.0

Add these to your app's Info.plist

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSExceptionDomains</key>
    <dict>
        <key>YOURHOST.COM</key>
        <dict>
            <key>NSIncludesSubdomains</key>
            <true/>
            <key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key>
            <true/>
            <key>NSTemporaryExceptionMinimumTLSVersion</key>
            <string>1.0</string>
            <key>NSTemporaryExceptionRequiresForwardSecrecy</key>
            <false/>
        </dict>
    </dict>
</dict>

Java - Writing strings to a CSV file

I think this is a simple code in java which will show the string value in CSV after compile this code.

public class CsvWriter {

    public static void main(String args[]) {
        // File input path
        System.out.println("Starting....");
        File file = new File("/home/Desktop/test/output.csv");
        try {
            FileWriter output = new FileWriter(file);
            CSVWriter write = new CSVWriter(output);

            // Header column value
            String[] header = { "ID", "Name", "Address", "Phone Number" };
            write.writeNext(header);
            // Value
            String[] data1 = { "1", "First Name", "Address1", "12345" };
            write.writeNext(data1);
            String[] data2 = { "2", "Second Name", "Address2", "123456" };
            write.writeNext(data2);
            String[] data3 = { "3", "Third Name", "Address3", "1234567" };
            write.writeNext(data3);
            write.close();
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();

        }

        System.out.println("End.");

    }
}

Notepad++ cached files location

I lost somehow my temporary notepad++ files, they weren't showing in tabs. So I did some search in appdata folder, and I found all my temporary files there. It seems that they are stored there for a long time.

C:\Users\USER\AppData\Roaming\Notepad++\backup

or

%AppData%\Notepad++\backup

Manage toolbar's navigation and back button from fragment in android

You have to manage your back button pressed action on your main Activity because your main Activity is container for your fragment.

First, add your all fragment to transaction.addToBackStack(null) and now navigation back button call will be going on main activity. I hope following code will help you...

@Override
    public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case android.R.id.home:
        onBackPressed();
        }
    return super.onOptionsItemSelected(item);
}

you can also use

Fragment fragment =fragmentManager.findFragmentByTag(Constant.TAG); 
if(fragment!=null) {          
      FragmentTransaction transaction = fragmentManager.beginTransaction();
      transaction.remove(fragment).commit();
}

And to change the title according to fragment name from fragment you can use the following code:

activity.getSupportActionBar().setTitle("Keyword Report Detail");

Can you target an elements parent element using event.target?

To use the parent of an element use parentElement:

function selectedProduct(event){
  var target = event.target;
  var parent = target.parentElement;//parent of "target"
}

How to use class from other files in C# with visual studio?

Yeah, I just made the same 'noob' error and found this thread. I had in fact added the class to the solution and not to the project. So it looked like this:

Wrong and right description

Just adding this in the hope to be of help to someone.

Swift GET request with parameters

Use NSURLComponents to build your NSURL like this

var urlComponents = NSURLComponents(string: "https://www.google.de/maps/")!

urlComponents.queryItems = [
  NSURLQueryItem(name: "q", value: String(51.500833)+","+String(-0.141944)),
  NSURLQueryItem(name: "z", value: String(6))
]
urlComponents.URL // returns https://www.google.de/maps/?q=51.500833,-0.141944&z=6

font: https://www.ralfebert.de/snippets/ios/encoding-nsurl-get-parameters/

Convert String to Float in Swift

In swift 4

let Totalname = "10.0" //Now it is in string

let floatVal  = (Totalname as NSString).floatValue //Now converted to float

Android - save/restore fragment state

Android fragment has some advantages and some disadvantages. The most disadvantage of the fragment is that when you want to use a fragment you create it ones. When you use it, onCreateView of the fragment is called for each time. If you want to keep state of the components in the fragment you must save fragment state and yout must load its state in the next shown. This make fragment view a bit slow and weird.

I have found a solution and I have used this solution: "Everything is great. Every body can try".

When first time onCreateView is being run, create view as a global variable. When second time you call this fragment onCreateView is called again you can return this global view. The fragment component state will be kept.

View view;

@Override
public View onCreateView(LayoutInflater inflater,
        @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    setActionBar(null);
    if (view != null) {
        if ((ViewGroup)view.getParent() != null)
            ((ViewGroup)view.getParent()).removeView(view);
        return view; 
    }
    view = inflater.inflate(R.layout.mylayout, container, false);
}

Apache won't start in wamp

Invalid Command '80HostnameLookups' , perhaps misspelled or defined by a module not included in the server configuration
I got this error when I debug the issue (wamp server was not going online) by the procedure defined by @RiggsFolly. Just comment the line 80HostnameLookups Off by changing it to #80HostnameLookups Off. This solution worked for me and apache starts running.
Note:80HostnameLookups Off can be found on line 222 of httpd.conf file located in C:\wamp\bin\apache\apache2.4.9\conf

How to fix 'sudo: no tty present and no askpass program specified' error?

If you add this line to your /etc/sudoers (via visudo) it will fix this problem without having to disable entering your password and when an alias for sudo -S won't work (scripts calling sudo):

Defaults visiblepw

Of course read the manual yourself to understand it, but I think for my use case of running in an LXD container via lxc exec instance -- /bin/bash its pretty safe since it isn't printing the password over a network.

Warning: session_start(): Cannot send session cookie - headers already sent by (output started at

  1. session_start() must be at the top of your source, no html or other output befor!
  2. your can only send session_start() one time
  3. by this way if(session_status()!=PHP_SESSION_ACTIVE) session_start()

How can I pause setInterval() functions?

You shouldn't measure time in interval function. Instead just save time when timer was started and measure difference when timer was stopped/paused. Use setInterval only to update displayed value. So there is no need to pause timer and you will get best possible accuracy in this way.

Import Google Play Services library in Android Studio

//gradle.properties

systemProp.http.proxyHost=www.somehost.org

systemProp.http.proxyPort=8080

systemProp.http.proxyUser=userid

systemProp.http.proxyPassword=password

systemProp.http.nonProxyHosts=*.nonproxyrepos.com|localhost

Object variable or With block variable not set (Error 91)

As I wrote in my comment, the solution to your problem is to write the following:

Set hyperLinkText = hprlink.Range

Set is needed because TextRange is a class, so hyperLinkText is an object; as such, if you want to assign it, you need to make it point to the actual object that you need.

What is the intended use-case for git stash?

I know StackOverflow is not the place for opinion based answers, but I actually have a good opinion on when to shelve changes with a stash.

You don't want to commit you experimental changes

When you make changes in your workspace/working tree, if you need to perform any branch based operations like a merge, push, fetch or pull, you must be at a clean commit point. So if you have workspace changes you need to commit them. But what if you don't want to commit them? What if they are experimental? Something you don't want part of your commit history? Something you don't want others to see when you push to GitHub?

You don't want to lose local changes with a hard reset

In that case, you can do a hard reset. But if you do a hard reset you will lose all of your local working tree changes because everything gets overwritten to where it was at the time of the last commit and you'll lose all of your changes.

So, as for the answer of 'when should you stash', the answer is when you need to get back to a clean commit point with a synchronized working tree/index/commit, but you don't want to lose your local changes in the process. Just shelve your changes in a stash and you're good.

And once you've done your stash and then merged or pulled or pushed, you can just stash pop or apply and you're back to where you started from.

Git stash and GitHub

GitHub is constantly adding new features, but as of right now, there is now way to save a stash there. Again, the idea of a stash is that it's local and private. Nobody else can peek into your stash without physical access to your workstation. Kinda the same way git reflog is private with the git log is public. It probably wouldn't be private if it was pushed up to GitHub.

One trick might be to do a diff of your workspace, check the diff into your git repository, commit and then push. Then you can do a pull from home, get the diff and then unwind it. But that's a pretty messy way to achieve those results.

git diff > git-dif-file.diff

pop the stash

How to read from stdin line by line in Node

// Work on POSIX and Windows
var fs = require("fs");
var stdinBuffer = fs.readFileSync(0); // STDIN_FILENO = 0
console.log(stdinBuffer.toString());

event.returnValue is deprecated. Please use the standard event.preventDefault() instead

This is a warning related to the fact that most JavaScript frameworks (jQuery, Angular, YUI, Bootstrap...) offer backward support for old-nasty-most-hated Internet Explorer starting from IE8 down to IE6 :/

One day that backward compatibility support will be dropped (for IE8/7/6 since IE9 deals with it), and you will no more see this warning (and other IEish bugs)..

It's a question of time (now IE8 has 10% worldwide share, once it reaches 1% it is DEAD), meanwhile, just ignore the warning and stay zen :)

Changing API level Android Studio

If you're having troubles specifying the SDK target to Google APIs instead of the base Platform SDK just change the compileSdkVersion 19 to compileSdkVersion "Google Inc.:Google APIs:19"

Send POST request using NSURLSession

You can use https://github.com/mxcl/OMGHTTPURLRQ

id config = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:someID];
id session = [NSURLSession sessionWithConfiguration:config delegate:someObject delegateQueue:[NSOperationQueue new]];

OMGMultipartFormData *multipartFormData = [OMGMultipartFormData new];
[multipartFormData addFile:data1 parameterName:@"file1" filename:@"myimage1.png" contentType:@"image/png"];

NSURLRequest *rq = [OMGHTTPURLRQ POST:url:multipartFormData];

id path = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"upload.NSData"];
[rq.HTTPBody writeToFile:path atomically:YES];

[[session uploadTaskWithRequest:rq fromFile:[NSURL fileURLWithPath:path]] resume];

How to hide Soft Keyboard when activity starts

To hide the softkeyboard at the time of New Activity start or onCreate(),onStart() etc. you can use the code below:

getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

Check if application is installed - Android

Try this:

public static boolean isAvailable(Context ctx, Intent intent) {
    final PackageManager mgr = ctx.getPackageManager();
    List<ResolveInfo> list =
        mgr.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
    return list.size() > 0;
}

Recommended way to save uploaded files in a servlet application

Store it anywhere in an accessible location except of the IDE's project folder aka the server's deploy folder, for reasons mentioned in the answer to Uploaded image only available after refreshing the page:

  1. Changes in the IDE's project folder does not immediately get reflected in the server's work folder. There's kind of a background job in the IDE which takes care that the server's work folder get synced with last updates (this is in IDE terms called "publishing"). This is the main cause of the problem you're seeing.

  2. In real world code there are circumstances where storing uploaded files in the webapp's deploy folder will not work at all. Some servers do (either by default or by configuration) not expand the deployed WAR file into the local disk file system, but instead fully in the memory. You can't create new files in the memory without basically editing the deployed WAR file and redeploying it.

  3. Even when the server expands the deployed WAR file into the local disk file system, all newly created files will get lost on a redeploy or even a simple restart, simply because those new files are not part of the original WAR file.

It really doesn't matter to me or anyone else where exactly on the local disk file system it will be saved, as long as you do not ever use getRealPath() method. Using that method is in any case alarming.

The path to the storage location can in turn be definied in many ways. You have to do it all by yourself. Perhaps this is where your confusion is caused because you somehow expected that the server does that all automagically. Please note that @MultipartConfig(location) does not specify the final upload destination, but the temporary storage location for the case file size exceeds memory storage threshold.

So, the path to the final storage location can be definied in either of the following ways:

  • Hardcoded:

      File uploads = new File("/path/to/uploads");
    
  • Environment variable via SET UPLOAD_LOCATION=/path/to/uploads:

      File uploads = new File(System.getenv("UPLOAD_LOCATION"));
    
  • VM argument during server startup via -Dupload.location="/path/to/uploads":

      File uploads = new File(System.getProperty("upload.location"));
    
  • *.properties file entry as upload.location=/path/to/uploads:

      File uploads = new File(properties.getProperty("upload.location"));
    
  • web.xml <context-param> with name upload.location and value /path/to/uploads:

      File uploads = new File(getServletContext().getInitParameter("upload.location"));
    
  • If any, use the server-provided location, e.g. in JBoss AS/WildFly:

      File uploads = new File(System.getProperty("jboss.server.data.dir"), "uploads");
    

Either way, you can easily reference and save the file as follows:

File file = new File(uploads, "somefilename.ext");

try (InputStream input = part.getInputStream()) {
    Files.copy(input, file.toPath());
}

Or, when you want to autogenerate an unique file name to prevent users from overwriting existing files with coincidentally the same name:

File file = File.createTempFile("somefilename-", ".ext", uploads);

try (InputStream input = part.getInputStream()) {
    Files.copy(input, file.toPath(), StandardCopyOption.REPLACE_EXISTING);
}

How to obtain part in JSP/Servlet is answered in How to upload files to server using JSP/Servlet? and how to obtain part in JSF is answered in How to upload file using JSF 2.2 <h:inputFile>? Where is the saved File?

Note: do not use Part#write() as it interprets the path relative to the temporary storage location defined in @MultipartConfig(location).

See also:

Paste Excel range in Outlook

First off, RangeToHTML. The script calls it like a method, but it isn't. It's a popular function by MVP Ron de Bruin. Coincidentally, that links points to the exact source of the script you posted, before those few lines got b?u?t?c?h?e?r?e?d? modified.

On with Range.SpecialCells. This method operates on a range and returns only those cells that match the given criteria. In your case, you seem to be only interested in the visible text cells. Importantly, it operates on a Range, not on HTML text.

For completeness sake, I'll post a working version of the script below. I'd certainly advise to disregard it and revisit the excellent original by Ron the Bruin.

Sub Mail_Selection_Range_Outlook_Body()

Dim rng As Range
Dim OutApp As Object
Dim OutMail As Object

Set rng = Nothing
' Only send the visible cells in the selection.

Set rng = Sheets("Sheet1").Range("D4:D12").SpecialCells(xlCellTypeVisible)

If rng Is Nothing Then
    MsgBox "The selection is not a range or the sheet is protected. " & _
           vbNewLine & "Please correct and try again.", vbOKOnly
    Exit Sub
End If

With Application
    .EnableEvents = False
    .ScreenUpdating = False
End With

Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)


With OutMail
    .To = ThisWorkbook.Sheets("Sheet2").Range("C1").Value
    .CC = ""
    .BCC = ""
    .Subject = "This is the Subject line"
    .HTMLBody = RangetoHTML(rng)
    ' In place of the following statement, you can use ".Display" to
    ' display the e-mail message.
    .Display
End With
On Error GoTo 0

With Application
    .EnableEvents = True
    .ScreenUpdating = True
End With

Set OutMail = Nothing
Set OutApp = Nothing
End Sub


Function RangetoHTML(rng As Range)
' By Ron de Bruin.
    Dim fso As Object
    Dim ts As Object
    Dim TempFile As String
    Dim TempWB As Workbook

    TempFile = Environ$("temp") & "/" & Format(Now, "dd-mm-yy h-mm-ss") & ".htm"

    'Copy the range and create a new workbook to past the data in
    rng.Copy
    Set TempWB = Workbooks.Add(1)
    With TempWB.Sheets(1)
        .Cells(1).PasteSpecial Paste:=8
        .Cells(1).PasteSpecial xlPasteValues, , False, False
        .Cells(1).PasteSpecial xlPasteFormats, , False, False
        .Cells(1).Select
        Application.CutCopyMode = False
        On Error Resume Next
        .DrawingObjects.Visible = True
        .DrawingObjects.Delete
        On Error GoTo 0
    End With

    'Publish the sheet to a htm file
    With TempWB.PublishObjects.Add( _
         SourceType:=xlSourceRange, _
         Filename:=TempFile, _
         Sheet:=TempWB.Sheets(1).Name, _
         Source:=TempWB.Sheets(1).UsedRange.Address, _
         HtmlType:=xlHtmlStatic)
        .Publish (True)
    End With

    'Read all data from the htm file into RangetoHTML
    Set fso = CreateObject("Scripting.FileSystemObject")
    Set ts = fso.GetFile(TempFile).OpenAsTextStream(1, -2)
    RangetoHTML = ts.ReadAll
    ts.Close
    RangetoHTML = Replace(RangetoHTML, "align=center x:publishsource=", _
                          "align=left x:publishsource=")

    'Close TempWB
    TempWB.Close savechanges:=False

    'Delete the htm file we used in this function
    Kill TempFile

    Set ts = Nothing
    Set fso = Nothing
    Set TempWB = Nothing
End Function

How to resume Fragment from BackStack if exists

getFragmentManager().addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() {

    @Override
    public void onBackStackChanged() {

        if(getFragmentManager().getBackStackEntryCount()==0) {
            onResume();
        }    
    }
});

Allow only pdf, doc, docx format for file upload?

_x000D_
_x000D_
$('#surat_lampiran').bind('change', function() {_x000D_
  alerr = "";_x000D_
  sts = false;_x000D_
  alert(this.files[0].type);_x000D_
  if(this.files[0].type != "application/pdf" && this.files[0].type != "application/msword" && this.files[0].type != "application/vnd.openxmlformats-officedocument.wordprocessingml.document"){_x000D_
  sts = true;_x000D_
  alerr += "Jenis file bukan .pdf/.doc/.docx ";_x000D_
}_x000D_
});
_x000D_
_x000D_
_x000D_

Android Fatal signal 11 (SIGSEGV) at 0x636f7d89 (code=1). How can it be tracked down?

I was getting this error by saving an object to the shared preferences as a gson converted string. The gson String was no good, so retrieving and deserializing the object was not actually working correctly. This meant any subsequent accesses to the object resulted in this error. Scary :)

Check if ADODB connection is open

This topic is old but if other people like me search a solution, this is a solution that I have found:

Public Function DBStats() As Boolean
    On Error GoTo errorHandler
        If Not IsNull(myBase.Version) Then 
            DBStats = True
        End If
        Exit Function
    errorHandler:
        DBStats = False  
End Function

So "myBase" is a Database Object, I have made a class to access to database (class with insert, update etc...) and on the module the class is use declare in an object (obviously) and I can test the connection with "[the Object].DBStats":

Dim BaseAccess As New myClass
BaseAccess.DBOpen 'I open connection
Debug.Print BaseAccess.DBStats ' I test and that tell me true
BaseAccess.DBClose ' I close the connection
Debug.Print BaseAccess.DBStats ' I test and tell me false

Edit : In DBOpen I use "OpenDatabase" and in DBClose I use ".Close" and "set myBase = nothing" Edit 2: In the function, if you are not connect, .version give you an error so if aren't connect, the errorHandler give you false

how to fix groovy.lang.MissingMethodException: No signature of method:

You can also get this error if the objects you're passing to the method are out of order. In other words say your method takes, in order, a string, an integer, and a date. If you pass a date, then a string, then an integer you will get the same error message.

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

Find out where MySQL is installed on Mac OS X

If you've installed with the dmg, you can also go to the Mac "System Preferences" menu, click on "MySql" and then on the configuration tab to see the location of all MySql directories.

Reference: https://dev.mysql.com/doc/refman/8.0/en/osx-installation-prefpane.html

How to check a channel is closed or not without reading it?

From the documentation:

A channel may be closed with the built-in function close. The multi-valued assignment form of the receive operator reports whether a received value was sent before the channel was closed.

https://golang.org/ref/spec#Receive_operator

Example by Golang in Action shows this case:

// This sample program demonstrates how to use an unbuffered
// channel to simulate a game of tennis between two goroutines.
package main

import (
    "fmt"
    "math/rand"
    "sync"
    "time"
)

// wg is used to wait for the program to finish.
var wg sync.WaitGroup

func init() {
    rand.Seed(time.Now().UnixNano())
}

// main is the entry point for all Go programs.
func main() {
    // Create an unbuffered channel.
    court := make(chan int)
    // Add a count of two, one for each goroutine.
    wg.Add(2)
    // Launch two players.
    go player("Nadal", court)
    go player("Djokovic", court)
    // Start the set.
    court <- 1
    // Wait for the game to finish.
    wg.Wait()
}

// player simulates a person playing the game of tennis.
func player(name string, court chan int) {
    // Schedule the call to Done to tell main we are done.
    defer wg.Done()
    for {
        // Wait for the ball to be hit back to us.
        ball, ok := <-court
        fmt.Printf("ok %t\n", ok)
        if !ok {
            // If the channel was closed we won.
            fmt.Printf("Player %s Won\n", name)
            return
        }
        // Pick a random number and see if we miss the ball.
        n := rand.Intn(100)
        if n%13 == 0 {
            fmt.Printf("Player %s Missed\n", name)
            // Close the channel to signal we lost.
            close(court)
            return
        }

        // Display and then increment the hit count by one.
        fmt.Printf("Player %s Hit %d\n", name, ball)
        ball++
        // Hit the ball back to the opposing player.
        court <- ball
    }
}

EXCEL VBA, inserting blank row and shifting cells

If you want to just shift everything down you can use:

Rows(1).Insert shift:=xlShiftDown

Similarly to shift everything over:

Columns(1).Insert shift:=xlShiftRight

Sending an HTTP POST request on iOS

I am not really sure why, but as soon as I comment out the following method it works:

connectionDidFinishDownloading:destinationURL:

Furthermore, I don't think you need the methods from the NSUrlConnectionDownloadDelegate protocol, only those from NSURLConnectionDataDelegate, unless you want some download information.

CKEditor automatically strips classes from div

Please refer to the official Advanced Content Filter guide and plugin integration tutorial.

You'll find much more than this about this powerful feature. Also see config.extraAllowedContent that seems suitable for your needs.

How to use onResume()?

Any Activity that restarts has its onResume() method executed first.

To use this method, do this:

@Override
public void onResume(){
    super.onResume();
    // put your code here...

}

Refresh or force redraw the fragment

I am using remove and replace both for refreshing content of Fragment like

final FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.remove(resetFragment).commit();
fragmentTransaction.replace(R.id.frame_container,resetFragment).commit();

How to send email to multiple recipients with addresses stored in Excel?

Both answers are correct. If you user .TO -method then the semicolumn is OK - but not for the addrecipients-method. There you need to split, e.g. :

                Dim Splitter() As String
                Splitter = Split(AddrMail, ";")
                For Each Dest In Splitter
                    .Recipients.Add (Trim(Dest))
                Next

Bind class toggle to window scroll event

Thanks to Flek for answering my question in his comment:

http://jsfiddle.net/eTTZj/30/

<div ng-app="myApp" scroll id="page" ng-class="{min:boolChangeClass}">

    <header></header>
    <section></section>

</div>

app = angular.module('myApp', []);
app.directive("scroll", function ($window) {
    return function(scope, element, attrs) {
        angular.element($window).bind("scroll", function() {
             if (this.pageYOffset >= 100) {
                 scope.boolChangeClass = true;
             } else {
                 scope.boolChangeClass = false;
             }
            scope.$apply();
        });
    };
});

UnicodeEncodeError: 'charmap' codec can't encode - character maps to <undefined>, print function

If you are using Windows command line to print the data, you should use

chcp 65001

This worked for me!

How to download Google Play Services in an Android emulator?

Go to https://university.xamarin.com/resources/working-with-android-emulators . Scroll down to the "Installing Google Play Services" section. Step by step walk through there.

Directly plagarized from xamarin here so I don't get dinged for linking and not including solution. Posting this as I found the hit in stack before I found the solution that worked across the board on the xamarin page.

  1. Start the Xamarin Android Player and run one of the supplied images, the following assumes you have started the KitKat Nexus 4 image. Download the proper Google Play Services .zip file from www.teamandroid.com/gapps/ . Make sure to download the image appropriate for your version of Android.
  2. Drag the .zip file onto the running emulator and drop it to install the component, here we show it on Mac OS X, but the same mechanism is used in Windows. You will get a prompt to install the package onto the emulator which indicates the image will be restarted
  3. Once it restarts, you will get a notification that installation is completed, and the image will now have Google Maps, Google+ and support for the Google Play store. Note that some things do not work correctly and you may get a few errors from some of the services, but you can safely dismiss these and continue the instructions.
  4. Next, you will need to associate a Google account so that you can update the services using the Google Play store. It should prompt you for this, but if it does not, you can go into the Google Settings and add a new account. Once you've added the account, you can then update the Google apps by opening the Google Play store application and going into settings from the side bar menu.
  5. Select Settings and then scroll down to the Build Version number information and double-tap on it until it tells you it is either up-to-date, or that it will download and install a new version.
  6. Power off the device (press and hold the power button in the toolbar on the right) and restart it. Once it restarts, it should indicate that it needs to update the Google Play services, tapping the notification will open the Google Play Store and install the latest version

Now you can run applications that depend on Google Maps in the Xamarin Android Player.

Android : Check whether the phone is dual SIM

Update 23 March'15 :

Official multiple SIM API is available now from Android 5.1 onwards

Other possible option :

You can use Java reflection to get both IMEI numbers.

Using these IMEI numbers you can check whether the phone is a DUAL SIM or not.

Try following activity :

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        TelephonyInfo telephonyInfo = TelephonyInfo.getInstance(this);

        String imeiSIM1 = telephonyInfo.getImsiSIM1();
        String imeiSIM2 = telephonyInfo.getImsiSIM2();

        boolean isSIM1Ready = telephonyInfo.isSIM1Ready();
        boolean isSIM2Ready = telephonyInfo.isSIM2Ready();

        boolean isDualSIM = telephonyInfo.isDualSIM();

        TextView tv = (TextView) findViewById(R.id.tv);
        tv.setText(" IME1 : " + imeiSIM1 + "\n" +
                " IME2 : " + imeiSIM2 + "\n" +
                " IS DUAL SIM : " + isDualSIM + "\n" +
                " IS SIM1 READY : " + isSIM1Ready + "\n" +
                " IS SIM2 READY : " + isSIM2Ready + "\n");
    }
}

And here is TelephonyInfo.java :

import java.lang.reflect.Method;

import android.content.Context;
import android.telephony.TelephonyManager;

public final class TelephonyInfo {

    private static TelephonyInfo telephonyInfo;
    private String imeiSIM1;
    private String imeiSIM2;
    private boolean isSIM1Ready;
    private boolean isSIM2Ready;

    public String getImsiSIM1() {
        return imeiSIM1;
    }

    /*public static void setImsiSIM1(String imeiSIM1) {
        TelephonyInfo.imeiSIM1 = imeiSIM1;
    }*/

    public String getImsiSIM2() {
        return imeiSIM2;
    }

    /*public static void setImsiSIM2(String imeiSIM2) {
        TelephonyInfo.imeiSIM2 = imeiSIM2;
    }*/

    public boolean isSIM1Ready() {
        return isSIM1Ready;
    }

    /*public static void setSIM1Ready(boolean isSIM1Ready) {
        TelephonyInfo.isSIM1Ready = isSIM1Ready;
    }*/

    public boolean isSIM2Ready() {
        return isSIM2Ready;
    }

    /*public static void setSIM2Ready(boolean isSIM2Ready) {
        TelephonyInfo.isSIM2Ready = isSIM2Ready;
    }*/

    public boolean isDualSIM() {
        return imeiSIM2 != null;
    }

    private TelephonyInfo() {
    }

    public static TelephonyInfo getInstance(Context context){

        if(telephonyInfo == null) {

            telephonyInfo = new TelephonyInfo();

            TelephonyManager telephonyManager = ((TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE));

            telephonyInfo.imeiSIM1 = telephonyManager.getDeviceId();;
            telephonyInfo.imeiSIM2 = null;

            try {
                telephonyInfo.imeiSIM1 = getDeviceIdBySlot(context, "getDeviceIdGemini", 0);
                telephonyInfo.imeiSIM2 = getDeviceIdBySlot(context, "getDeviceIdGemini", 1);
            } catch (GeminiMethodNotFoundException e) {
                e.printStackTrace();

                try {
                    telephonyInfo.imeiSIM1 = getDeviceIdBySlot(context, "getDeviceId", 0);
                    telephonyInfo.imeiSIM2 = getDeviceIdBySlot(context, "getDeviceId", 1);
                } catch (GeminiMethodNotFoundException e1) {
                    //Call here for next manufacturer's predicted method name if you wish
                    e1.printStackTrace();
                }
            }

            telephonyInfo.isSIM1Ready = telephonyManager.getSimState() == TelephonyManager.SIM_STATE_READY;
            telephonyInfo.isSIM2Ready = false;

            try {
                telephonyInfo.isSIM1Ready = getSIMStateBySlot(context, "getSimStateGemini", 0);
                telephonyInfo.isSIM2Ready = getSIMStateBySlot(context, "getSimStateGemini", 1);
            } catch (GeminiMethodNotFoundException e) {

                e.printStackTrace();

                try {
                    telephonyInfo.isSIM1Ready = getSIMStateBySlot(context, "getSimState", 0);
                    telephonyInfo.isSIM2Ready = getSIMStateBySlot(context, "getSimState", 1);
                } catch (GeminiMethodNotFoundException e1) {
                    //Call here for next manufacturer's predicted method name if you wish
                    e1.printStackTrace();
                }
            }
        }

        return telephonyInfo;
    }

    private static String getDeviceIdBySlot(Context context, String predictedMethodName, int slotID) throws GeminiMethodNotFoundException {

        String imei = null;

        TelephonyManager telephony = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);

        try{

            Class<?> telephonyClass = Class.forName(telephony.getClass().getName());

            Class<?>[] parameter = new Class[1];
            parameter[0] = int.class;
            Method getSimID = telephonyClass.getMethod(predictedMethodName, parameter);

            Object[] obParameter = new Object[1];
            obParameter[0] = slotID;
            Object ob_phone = getSimID.invoke(telephony, obParameter);

            if(ob_phone != null){
                imei = ob_phone.toString();

            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new GeminiMethodNotFoundException(predictedMethodName);
        }

        return imei;
    }

    private static  boolean getSIMStateBySlot(Context context, String predictedMethodName, int slotID) throws GeminiMethodNotFoundException {

        boolean isReady = false;

        TelephonyManager telephony = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);

        try{

            Class<?> telephonyClass = Class.forName(telephony.getClass().getName());

            Class<?>[] parameter = new Class[1];
            parameter[0] = int.class;
            Method getSimStateGemini = telephonyClass.getMethod(predictedMethodName, parameter);

            Object[] obParameter = new Object[1];
            obParameter[0] = slotID;
            Object ob_phone = getSimStateGemini.invoke(telephony, obParameter);

            if(ob_phone != null){
                int simState = Integer.parseInt(ob_phone.toString());
                if(simState == TelephonyManager.SIM_STATE_READY){
                    isReady = true;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new GeminiMethodNotFoundException(predictedMethodName);
        }

        return isReady;
    }


    private static class GeminiMethodNotFoundException extends Exception {

        private static final long serialVersionUID = -996812356902545308L;

        public GeminiMethodNotFoundException(String info) {
            super(info);
        }
    }
}

Edit :

Getting access of methods like "getDeviceIdGemini" for other SIM slot's detail has prediction that method exist.

If that method's name doesn't match with one given by device manufacturer than it will not work. You have to find corresponding method name for those devices.

Finding method names for other manufacturers can be done using Java reflection as follows :

public static void printTelephonyManagerMethodNamesForThisDevice(Context context) {

    TelephonyManager telephony = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
    Class<?> telephonyClass;
    try {
        telephonyClass = Class.forName(telephony.getClass().getName());
        Method[] methods = telephonyClass.getMethods();
        for (int idx = 0; idx < methods.length; idx++) {

            System.out.println("\n" + methods[idx] + " declared by " + methods[idx].getDeclaringClass());
        }
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }
} 

EDIT :

As Seetha pointed out in her comment :

telephonyInfo.imeiSIM1 = getDeviceIdBySlot(context, "getDeviceIdDs", 0);
telephonyInfo.imeiSIM2 = getDeviceIdBySlot(context, "getDeviceIdDs", 1); 

It is working for her. She was successful in getting two IMEI numbers for both the SIM in Samsung Duos device.

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

EDIT 2 :

The method used for retrieving data is for Lenovo A319 and other phones by that manufacture (Credit Maher Abuthraa):

telephonyInfo.imeiSIM1 = getDeviceIdBySlot(context, "getSimSerialNumberGemini", 0); 
telephonyInfo.imeiSIM2 = getDeviceIdBySlot(context, "getSimSerialNumberGemini", 1); 

Android ListView not refreshing after notifyDataSetChanged

You are assigning reloaded items to global variable items in onResume(), but this will not reflect in ItemAdapter class, because it has its own instance variable called 'items'.

For refreshing ListView, add a refresh() in ItemAdapter class which accepts list data i.e items

class ItemAdapter
{
    .....

    public void refresh(List<Item> items)
    {
        this.items = items;
        notifyDataSetChanged();
    } 
}

update onResume() with following code

@Override
public void onResume()
{
    super.onResume();
    items.clear();
    items = dbHelper.getItems(); //reload the items from database
    **adapter.refresh(items);**
}

java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState

The reason for the exception is the re-creation of the FragmentActivity during the runtime of the AsyncTask and the access to the previous, destroyed FragmentActivity in onPostExecute() afterwards.

The problem is to get a valid reference to the new FragmentActivity. There is no method for this neither getActivity() nor findById() or something similar. This forum is full of threads according this issue (e.g. search for "Activity context in onPostExecute"). Some of them are describing workarounds (until now I didn't find a good one).

Maybe it would be a better solution to use a Service for my purpose.

Callback to a Fragment from a DialogFragment

You should define an interface in your fragment class and implement that interface in its parent activity. The details are outlined here http://developer.android.com/guide/components/fragments.html#EventCallbacks . The code would look similar to:

Fragment:

public static class FragmentA extends DialogFragment {

    OnArticleSelectedListener mListener;

    // Container Activity must implement this interface
    public interface OnArticleSelectedListener {
        public void onArticleSelected(Uri articleUri);
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            mListener = (OnArticleSelectedListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString() + " must implement OnArticleSelectedListener");
        }
    }
}

Activity:

public class MyActivity extends Activity implements OnArticleSelectedListener{

    ...
    @Override
    public void onArticleSelected(Uri articleUri){

    }
    ...
}

How to display special characters in PHP

This works for me. Try this one before the start of HTML. I hope it will also work for you.

_x000D_
_x000D_
<?php header('Content-Type: text/html; charset=iso-8859-15'); ?>_x000D_
<!DOCTYPE html>_x000D_
_x000D_
<html lang="en-US">_x000D_
<head>
_x000D_
_x000D_
_x000D_

How to set DialogFragment's width and height?

When I need to make the DialogFragment a bit wider I'm setting minWidth:

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:minWidth="320dp"
    ... />

SQLException: No suitable Driver Found for jdbc:oracle:thin:@//localhost:1521/orcl

I had the same problem. To fix it in Jboss 7 AS, I copy the oracle driver jar file to Jboss module folder. Example: ../jboss-as-7.1.1.Final/modules/org/hibernate/main.

You also need to change "module.xml"

<module xmlns="urn:jboss:module:1.1" name="org.hibernate">
<resources>
    <resource-root path="hibernate-core-4.0.1.Final.jar"/>
    <resource-root path="hibernate-commons-annotations-4.0.1.Final.jar"/>
    <resource-root path="hibernate-entitymanager-4.0.1.Final.jar"/>
    <resource-root path="hibernate-infinispan-4.0.1.Final.jar"/>
    <resource-root path="ojdbc6.jar"/>
</resources>

<dependencies>
    <module name="asm.asm"/>
    <module name="javax.api"/>
    <module name="javax.persistence.api"/>
    <module name="javax.transaction.api"/>
    <module name="javax.validation.api"/>
    <module name="org.antlr"/>
    <module name="org.apache.commons.collections"/>
    <module name="org.dom4j"/>
    <module name="org.infinispan" optional="true"/>
    <module name="org.javassist"/>
    <module name="org.jboss.as.jpa.hibernate" slot="4" optional="true"/>
    <module name="org.jboss.logging"/>
    <module name="org.hibernate.envers" services="import" optional="true"/>
</dependencies>

android activity has leaked window com.android.internal.policy.impl.phonewindow$decorview Issue

The dialog needs to be started only after the window states of the Activity are initialized This happens only after onresume.

So call

runOnUIthread(new Runnable(){

    showInfoMessageDialog("Please check your network connection","Network Alert");
});

in your OnResume function. Do not create dialogs in OnCreate
Edit:

use this

Handler h = new Handler();

h.postDelayed(new Runnable(){

        showInfoMessageDialog("Please check your network connection","Network Alert");
    },500);

in your Onresume instead of showonuithread

Android. Fragment getActivity() sometimes returns null

It seems that I found a solution to my problem. Very good explanations are given here and here. Here is my example:

pulic class MyActivity extends FragmentActivity{

private ViewPager pager; 
private TitlePageIndicator indicator;
private TabsAdapter adapter;
private Bundle savedInstanceState;

 @Override
public void onCreate(Bundle savedInstanceState) {

    .... 
    this.savedInstanceState = savedInstanceState;
    pager = (ViewPager) findViewById(R.id.pager);;
    indicator = (TitlePageIndicator) findViewById(R.id.indicator);
    adapter = new TabsAdapter(getSupportFragmentManager(), false);

    if (savedInstanceState == null){    
        adapter.addFragment(new FirstFragment());
        adapter.addFragment(new SecondFragment());
    }else{
        Integer  count  = savedInstanceState.getInt("tabsCount");
        String[] titles = savedInstanceState.getStringArray("titles");
        for (int i = 0; i < count; i++){
            adapter.addFragment(getFragment(i), titles[i]);
        }
    }


    indicator.notifyDataSetChanged();
    adapter.notifyDataSetChanged();

    // push first task
    FirstTask firstTask = new FirstTask(MyActivity.this);
    // set first fragment as listener
    firstTask.setTaskListener((TaskListener) getFragment(0));
    firstTask.execute();

}

private Fragment getFragment(int position){
     return savedInstanceState == null ? adapter.getItem(position) : getSupportFragmentManager().findFragmentByTag(getFragmentTag(position));
}

private String getFragmentTag(int position) {
    return "android:switcher:" + R.id.pager + ":" + position;
}

 @Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putInt("tabsCount",      adapter.getCount());
    outState.putStringArray("titles", adapter.getTitles().toArray(new String[0]));
}

 indicator.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageSelected(int position) {
            Fragment currentFragment = adapter.getItem(position);
            ((Taskable) currentFragment).executeTask();
        }

        @Override
        public void onPageScrolled(int i, float v, int i1) {}

        @Override
        public void onPageScrollStateChanged(int i) {}
 });

The main idea in this code is that, while running your application normally, you create new fragments and pass them to the adapter. When you are resuming your application fragment manager already has this fragment's instance and you need to get it from fragment manager and pass it to the adapter.

UPDATE

Also, it is a good practice when using fragments to check isAdded before getActivity() is called. This helps avoid a null pointer exception when the fragment is detached from the activity. For example, an activity could contain a fragment that pushes an async task. When the task is finished, the onTaskComplete listener is called.

@Override
public void onTaskComplete(List<Feed> result) {

    progress.setVisibility(View.GONE);
    progress.setIndeterminate(false);
    list.setVisibility(View.VISIBLE);

    if (isAdded()) {

        adapter = new FeedAdapter(getActivity(), R.layout.feed_item, result);
        list.setAdapter(adapter);
        adapter.notifyDataSetChanged();
    }

}

If we open the fragment, push a task, and then quickly press back to return to a previous activity, when the task is finished, it will try to access the activity in onPostExecute() by calling the getActivity() method. If the activity is already detached and this check is not there:

if (isAdded()) 

then the application crashes.

Writing a string to a cell in excel

I think you may be getting tripped up on the sheet protection. I streamlined your code a little and am explicitly setting references to the workbook and worksheet objects. In your example, you explicitly refer to the workbook and sheet when you're setting the TxtRng object, but not when you unprotect the sheet.

Try this:

Sub varchanger()

    Dim wb As Workbook
    Dim ws As Worksheet
    Dim TxtRng  As Range

    Set wb = ActiveWorkbook
    Set ws = wb.Sheets("Sheet1")
    'or ws.Unprotect Password:="yourpass"
    ws.Unprotect

    Set TxtRng = ws.Range("A1")
    TxtRng.Value = "SubTotal"
    'http://stackoverflow.com/questions/8253776/worksheet-protection-set-using-ws-protect-but-doesnt-unprotect-using-the-menu
    ' or ws.Protect Password:="yourpass"
    ws.Protect

End Sub

If I run the sub with ws.Unprotect commented out, I get a run-time error 1004. (Assuming I've protected the sheet and have the range locked.) Uncommenting the line allows the code to run fine.

NOTES:

  1. I'm re-setting sheet protection after writing to the range. I'm assuming you want to do this if you had the sheet protected in the first place. If you are re-setting protection later after further processing, you'll need to remove that line.
  2. I removed the error handler. The Excel error message gives you a lot more detail than Err.number. You can put it back in once you get your code working and display whatever you want. Obviously you can use Err.Description as well.
  3. The Cells(1, 1) notation can cause a huge amount of grief. Be careful using it. Range("A1") is a lot easier for humans to parse and tends to prevent forehead-slapping mistakes.

First char to upper case

For completeness, if you wanted to use replaceFirst, try this:

public static String cap1stChar(String userIdea)
{
  String betterIdea = userIdea;
  if (userIdea.length() > 0)
  {
    String first = userIdea.substring(0,1);
    betterIdea = userIdea.replaceFirst(first, first.toUpperCase());
  }
  return betterIdea;
}//end cap1stChar

What to do on TransactionTooLargeException

This was happening in my app because I was passing a list of search results in a fragment's arguments, assigning that list to a property of the fragment - which is actually a reference to the same location in memory pointed to by the fragment's arguments - then adding new items to the list, which also changed the size of the fragment's arguments. When the activity is suspended, the base fragment class tries to save the fragment's arguments in onSaveInstanceState, which crashes if the arguments are larger than 1MB. For example:

private ArrayList<SearchResult> mSearchResults;

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    if (getArguments() != null && getArguments().getSerializable("SearchResults") != null) {
        mSearchResults = (ArrayList) getArguments().getSerializable("SearchResults");
    }
}

private void onSearchResultsObtained(ArrayList<SearchResult> pSearchResults) {

    // Because mSearchResults points to the same location in memory as the fragment's arguments
    // this will also increase the size of the arguments!
    mSearchResults.addAll(pSearchResults);
}

The easiest solution in this case was to assign a copy of the list to the fragment's property instead of assigning a reference:

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    if (getArguments() != null && getArguments().getSerializable("SearchResults") != null) {

        // Copy value of array instead of reference
        mSearchResults = new ArrayList((ArrayList) getArguments().getSerializable("SearchResults"));
    }
}

An even better solution would be to not pass around so much data in the arguments.

I probably never would have found this without the help of this answer and TooLargeTool.

How can I maintain fragment state when added to the back stack?

My problem was similar but I overcame me without keeping the fragment alive. Suppose you have an activity that has 2 fragments - F1 and F2. F1 is started initially and lets say in contains some user info and then upon some condition F2 pops on asking user to fill in additional attribute - their phone number. Next, you want that phone number to pop back to F1 and complete signup but you realize all previous user info is lost and you don't have their previous data. The fragment is recreated from scratch and even if you saved this information in onSaveInstanceState the bundle comes back null in onActivityCreated.

Solution: Save required information as an instance variable in calling activity. Then pass that instance variable into your fragment.

@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    Bundle args = getArguments();

    // this will be null the first time F1 is created. 
    // it will be populated once you replace fragment and provide bundle data
    if (args != null) {
        if (args.get("your_info") != null) {
            // do what you want with restored information
        }
    }
}

So following on with my example: before I display F2 I save user data in the instance variable using a callback. Then I start F2, user fills in phone number and presses save. I use another callback in activity, collect this information and replace my fragment F1, this time it has bundle data that I can use.

@Override
public void onPhoneAdded(String phone) {
        //replace fragment
        F1 f1 = new F1 ();
        Bundle args = new Bundle();
        yourInfo.setPhone(phone);
        args.putSerializable("you_info", yourInfo);
        f1.setArguments(args);

        getFragmentManager().beginTransaction()
                .replace(R.id.fragmentContainer, f1).addToBackStack(null).commit();

    }
}

More information about callbacks can be found here: https://developer.android.com/training/basics/fragments/communicating.html

Fragment onResume() & onPause() is not called on backstack

Follow the below steps, and you shall get the needed answer

1- For both fragments, create a new abstract parent one.
2- Add a custom abstract method that should be implemented by both of them.
3- Call it from the current instance before replacing with the second one.

Get the correct week number of a given date

Good news! A pull request adding System.Globalization.ISOWeek to .NET Core was just merged and is currently slated for the 3.0 release. Hopefully it will propagate to the other .NET platforms in a not-too-distant future.

The type has the following signature, which should cover most ISO week needs:

namespace System.Globalization
{
    public static class ISOWeek
    {
        public static int GetWeekOfYear(DateTime date);
        public static int GetWeeksInYear(int year);
        public static int GetYear(DateTime date);
        public static DateTime GetYearEnd(int year);
        public static DateTime GetYearStart(int year);
        public static DateTime ToDateTime(int year, int week, DayOfWeek dayOfWeek);
    }
}

You can find the source code here.

UPDATE: These APIs have also been included in the 2.1 version of .NET Standard.

Filter Excel pivot table using VBA

Configure the pivot table so that it is like this:

enter image description here

Your code can simply work on range("B1") now and the pivot table will be filtered to you required SavedFamilyCode

Sub FilterPivotTable()
Application.ScreenUpdating = False
    ActiveSheet.Range("B1") = "K123224"
Application.ScreenUpdating = True
End Sub

How to suspend/resume a process in Windows?

Well, Process Explorer has a suspend option. You can right click a process in the process column and select suspend. Once you are ready to resume it again right click and this time select resume. Process Explorer can be obtained from here:

http://technet.microsoft.com/en-us/sysinternals/bb896653.aspx

How to determine when Fragment becomes visible in ViewPager

Override Fragment.onHiddenChanged() for that.

public void onHiddenChanged(boolean hidden)

Called when the hidden state (as returned by isHidden()) of the fragment has changed. Fragments start out not hidden; this will be called whenever the fragment changes state from that.

Parameters
hidden - boolean: True if the fragment is now hidden, false if it is not visible.

support FragmentPagerAdapter holds reference to old fragments

My solution: I set almost every View as static. Now my app interacts perfect. Being able to call the static methods from everywhere is maybe not a good style, but why to play around with code that doesn't work? I read a lot of questions and their answers here on SO and no solution brought success (for me).

I know it can leak the memory, and waste heap, and my code will not be fit on other projects, but I don't feel scared about this - I tested the app on different devices and conditions, no problems at all, the Android Platform seems to be able handle this. The UI gets refreshed every second and even on a S2 ICS (4.0.3) device the app is able to handle thousands of geo-markers.

VBA EXCEL Multiple Nested FOR Loops that Set two variable for expression

I can't get to your google docs file at the moment but there are some issues with your code that I will try to address while answering

Sub stituterangersNEW()
Dim t As Range
Dim x As Range
Dim dify As Boolean
Dim difx As Boolean
Dim time2 As Date
Dim time1 As Date

    'You said time1 doesn't change, so I left it in a singe cell.
    'If that is not correct, you will have to play with this some more.
    time1 = Range("A6").Value

    'Looping through each of our output cells.
    For Each t In Range("B7:E9") 'Change these to match your real ranges.

        'Looping through each departure date/time.
        '(Only one row in your example. This can be adjusted if needed.)
        For Each x In Range("B2:E2") 'Change these to match your real ranges.
            'Check to see if our dep time corresponds to
            'the matching column in our output
            If t.Column = x.Column Then
                'If it does, then check to see what our time value is
                If x > 0 Then
                    time2 = x.Value
                    'Apply the change to the output cell.
                    t.Value = time1 - time2
                    'Exit out of this loop and move to the next output cell.
                    Exit For
                End If
            End If
            'If the columns don't match, or the x value is not a time
            'then we'll move to the next dep time (x)
        Next x
    Next t

End Sub

EDIT

I changed you worksheet to play with (see above for the new Sub). This probably does not suite your needs directly, but hopefully it will demonstrate the conept behind what I think you want to do. Please keep in mind that this code does not follow all the coding best preactices I would recommend (e.g. validating the time is actually a TIME and not some random other data type).

     A                      B                   C                   D                  E
1    LOAD_NUMBER            1                   2                   3                  4
2    DEPARTURE_TIME_DATE    11/12/2011 19:30    11/12/2011 19:30    11/12/2011 19:30    11/12/2011 20:00                
4    Dry_Refrig 7585.1  0   10099.8 16700
6    1/4/2012 19:30

Using the sub I got this output:

    A           B             C             D             E
7   Friday      1272:00:00    1272:00:00    1272:00:00    1271:30:00
8   Saturday    1272:00:00    1272:00:00    1272:00:00    1271:30:00
9   Thursday    1272:00:00    1272:00:00    1272:00:00    1271:30:00

Excel VBA - Delete empty rows

How about

sub foo()
  dim r As Range, rows As Long, i As Long
  Set r = ActiveSheet.Range("A1:Z50")
  rows = r.rows.Count
  For i = rows To 1 Step (-1)
    If WorksheetFunction.CountA(r.rows(i)) = 0 Then r.rows(i).Delete
  Next
End Sub

Try this

Option Explicit

Sub Sample()
    Dim i As Long
    Dim DelRange As Range

    On Error GoTo Whoa

    Application.ScreenUpdating = False

    For i = 1 To 50
        If Application.WorksheetFunction.CountA(Range("A" & i & ":" & "Z" & i)) = 0 Then
            If DelRange Is Nothing Then
                Set DelRange = Range("A" & i & ":" & "Z" & i)
            Else
                Set DelRange = Union(DelRange, Range("A" & i & ":" & "Z" & i))
            End If
        End If
    Next i

    If Not DelRange Is Nothing Then DelRange.Delete shift:=xlUp
LetsContinue:
    Application.ScreenUpdating = True

    Exit Sub
Whoa:
    MsgBox Err.Description
    Resume LetsContinue
End Sub

IF you want to delete the entire row then use this code

Option Explicit

Sub Sample()
    Dim i As Long
    Dim DelRange As Range

    On Error GoTo Whoa

    Application.ScreenUpdating = False

    For i = 1 To 50
        If Application.WorksheetFunction.CountA(Range("A" & i & ":" & "Z" & i)) = 0 Then
            If DelRange Is Nothing Then
                Set DelRange = Rows(i)
            Else
                Set DelRange = Union(DelRange, Rows(i))
            End If
        End If
    Next i

    If Not DelRange Is Nothing Then DelRange.Delete shift:=xlUp
LetsContinue:
    Application.ScreenUpdating = True

    Exit Sub
Whoa:
    MsgBox Err.Description
    Resume LetsContinue
End Sub

Neither BindingResult nor plain target object for bean name available as request attribute

I had problem like this, but with several "actions". My solution looks like this:

    <form method="POST" th:object="${searchRequest}" action="searchRequest" >
          <input type="text" th:field="*{name}"/>
          <input type="submit" value="find" th:value="find" />
    </form>
        ...
    <form method="POST" th:object="${commodity}" >
        <input type="text" th:field="*{description}"/>
        <input type="submit" value="add" />
    </form>

And controller

@Controller
@RequestMapping("/goods")
public class GoodsController {
    @RequestMapping(value = "add", method = GET)
    public String showGoodsForm(Model model){
           model.addAttribute(new Commodity());
           model.addAttribute("searchRequest", new SearchRequest());
           return "goodsForm";
    }
    @RequestMapping(value = "add", method = POST)
    public ModelAndView processAddCommodities(
            @Valid Commodity commodity,
            Errors errors) {
        if (errors.hasErrors()) {
            ModelAndView model = new ModelAndView("goodsForm");
            model.addObject("searchRequest", new SearchRequest());
            return model;
        }
        ModelAndView model = new ModelAndView("redirect:/goods/" + commodity.getName());
        model.addObject(new Commodity());
        model.addObject("searchRequest", new SearchRequest());
        return model;
    }
    @RequestMapping(value="searchRequest", method=POST)
    public String processFindCommodity(SearchRequest commodity, Model model) {
    ...
        return "catalog";
    }

I'm sure - here is not "best practice", but it is works without "Neither BindingResult nor plain target object for bean name available as request attribute".

onNewIntent() lifecycle and registered listeners

onNewIntent() is meant as entry point for singleTop activities which already run somewhere else in the stack and therefore can't call onCreate(). From activities lifecycle point of view it's therefore needed to call onPause() before onNewIntent(). I suggest you to rewrite your activity to not use these listeners inside of onNewIntent(). For example most of the time my onNewIntent() methods simply looks like this:

@Override
protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);
    // getIntent() should always return the most recent
    setIntent(intent);
}

With all setup logic happening in onResume() by utilizing getIntent().

Android activity life cycle - what are all these methods for?

ANDROID LIFE-CYCLE

There are seven methods that manage the life cycle of an Android application:


Answer for what are all these methods for:

Let us take a simple scenario where knowing in what order these methods are called will help us give a clarity why they are used.

  • Suppose you are using a calculator app. Three methods are called in succession to start the app.

onCreate() - - - > onStart() - - - > onResume()

  • When I am using the calculator app, suddenly a call comes the. The calculator activity goes to the background and another activity say. Dealing with the call comes to the foreground, and now two methods are called in succession.

onPause() - - - > onStop()

  • Now say I finish the conversation on the phone, the calculator activity comes to foreground from the background, so three methods are called in succession.

onRestart() - - - > onStart() - - - > onResume()

  • Finally, say I have finished all the tasks in calculator app, and I want to exit the app. Futher two methods are called in succession.

onStop() - - - > onDestroy()


There are four states an activity can possibly exist:

  • Starting State
  • Running State
  • Paused State
  • Stopped state

Starting state involves:

Creating a new Linux process, allocating new memory for the new UI objects, and setting up the whole screen. So most of the work is involved here.

Running state involves:

It is the activity (state) that is currently on the screen. This state alone handles things such as typing on the screen, and touching & clicking buttons.

Paused state involves:

When an activity is not in the foreground and instead it is in the background, then the activity is said to be in paused state.

Stopped state involves:

A stopped activity can only be bought into foreground by restarting it and also it can be destroyed at any point in time.

The activity manager handles all these states in such a way that the user experience and performance is always at its best even in scenarios where the new activity is added to the existing activities

How to refresh activity after changing language (Locale) inside application

If I imagined that you set android:configChanges in manifest.xml and create several directory for several language such as: values-fr OR values-nl, I could suggest this code(In Activity class):

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    Button btn = (Button) findViewById(R.id.btn);
    btn.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // change language by onclick a button
             Configuration newConfig = new Configuration();
             newConfig.locale = Locale.FRENCH;
             onConfigurationChanged(newConfig);
        }
    });
}

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);

    getBaseContext().getResources().updateConfiguration(newConfig, getBaseContext().getResources().getDisplayMetrics());
    setContentView(R.layout.main);
    setTitle(R.string.app_name);

    // Checks the active language
    if (newConfig.locale == Locale.ENGLISH) {
        Toast.makeText(this, "English", Toast.LENGTH_SHORT).show();
    } else if (newConfig.locale == Locale.FRENCH){
        Toast.makeText(this, "French", Toast.LENGTH_SHORT).show();
    }
}

I tested this code, It is correct.

How to stop a vb script running in windows

I can think of at least 2 different ways:

  1. using Task Manager (Ctrl-Shift-Esc), select the process tab, look for a process name cscript.exe or wscript.exe and use End Process.

  2. From the command line you could use taskkill /fi "imagename eq cscript.exe" (change to wscript.exe as needed)

Another way is using scripting and WMI. Here are some hints: look for the Win32_Process class and the Terminate method.

How do I extract specific 'n' bits of a 32-bit unsigned integer in C?

This is a briefer variation of the accepted answer: the function below extracts the bits from-to inclusive by creating a bitmask. After applying an AND logic over the original number the result is shifted so the function returns just the extracted bits. Skipped index/integrity checks for clarity.

uint16_t extractInt(uint16_t orig16BitWord, unsigned from, unsigned to) 
{
  unsigned mask = ( (1<<(to-from+1))-1) << from;
  return (orig16BitWord & mask) >> from;
}

ViewPager and fragments — what's the right way to store fragment's state?

I came up with this simple and elegant solution. It assumes that the activity is responsible for creating the Fragments, and the Adapter just serves them.

This is the adapter's code (nothing weird here, except for the fact that mFragments is a list of fragments maintained by the Activity)

class MyFragmentPagerAdapter extends FragmentStatePagerAdapter {

    public MyFragmentPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        return mFragments.get(position);
    }

    @Override
    public int getCount() {
        return mFragments.size();
    }

    @Override
    public int getItemPosition(Object object) {
        return POSITION_NONE;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        TabFragment fragment = (TabFragment)mFragments.get(position);
        return fragment.getTitle();
    }
} 

The whole problem of this thread is getting a reference of the "old" fragments, so I use this code in the Activity's onCreate.

    if (savedInstanceState!=null) {
        if (getSupportFragmentManager().getFragments()!=null) {
            for (Fragment fragment : getSupportFragmentManager().getFragments()) {
                mFragments.add(fragment);
            }
        }
    }

Of course you can further fine tune this code if needed, for example making sure the fragments are instances of a particular class.

Is there a Sleep/Pause/Wait function in JavaScript?

setTimeout() function it's use to delay a process in JavaScript.

w3schools has an easy tutorial about this function.

Login with facebook android sdk app crash API 4

The official answer from Facebook (http://developers.facebook.com/bugs/282710765082535):

Mikhail,

The facebook android sdk no longer supports android 1.5 and 1.6. Please upgrade to the next api version.

Good luck with your implementation.

Failed to connect to camera service

The problem is related to permission. Copy following code into onCreate() method. The issue will get solved.

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

After that wait for the user action and handle his decision.

@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
    switch (requestCode) {
        case CAMERA_PERMISSION_REQUEST_CODE:
            // If request is cancelled, the result arrays are empty.
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                //Start your camera handling here
            } else {
                AppUtils.showUserMessage("You declined to allow the app to access your camera", this);
            }
    }
}

How can I change the language (to english) in Oracle SQL Developer?

You can also set language at runtime

sqldeveloper.exe --AddVMOption=-Duser.language=en

to avoid editing sqldeveloper.conf every time you install new version.

Android webview launches browser when calling loadurl

Use this:

lWebView.setWebViewClient(new WebViewClient());

How can you tell when a layout has been drawn?

An alternative to the usual methods is to hook into the drawing of the view.

OnPreDrawListener is called many times when displaying a view, so there is no specific iteration where your view has valid measured width or height. This requires that you continually verify (view.getMeasuredWidth() <= 0) or set a limit to the number of times you check for a measuredWidth greater than zero.

There is also a chance that the view will never be drawn, which may indicate other problems with your code.

final View view = [ACQUIRE REFERENCE]; // Must be declared final for inner class
ViewTreeObserver viewTreeObserver = view.getViewTreeObserver();
viewTreeObserver.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
    @Override
    public boolean onPreDraw() {
        if (view.getMeasuredWidth() > 0) {     
            view.getViewTreeObserver().removeOnPreDrawListener(this);
            int width = view.getMeasuredWidth();
            int height = view.getMeasuredHeight();
            //Do something with width and height here!
        }
        return true; // Continue with the draw pass, as not to stop it
    }
});

Apache won't follow symlinks (403 Forbidden)

Yet another subtle pitfall, in case you need AllowOverride All:

Somewhere deep in the fs tree, an old .htaccess having

    Options Indexes

instead of

    Options +Indexes

was all it took to nonchalantly disable the FollowSymLinks set in the server config, and cause a mysterious 403 here.

Why are static variables considered evil?

It might be suggested that in most cases where you use a static variable, you really want to be using the singleton pattern.

The problem with global states is that sometimes what makes sense as global in a simpler context, needs to be a bit more flexible in a practical context, and this is where the singleton pattern becomes useful.

How to switch activity without animation in Android?

The line in the theme style works fine, yet that replaces the animation with a white screen. Especially on a slower phone - it is really annoying. So, if you want an instant transition - you could use this in the theme style:

<item name="android:windowAnimationStyle">@null</item>
<item name="android:windowDisablePreview">true</item>

Android app unable to start activity componentinfo

Your null pointer exception seems to be on this line:

String url = intent.getExtras().getString("userurl");

because intent.getExtras() returns null when the intent doesn't have any extras.

You have to realize that this piece of code:

Intent Main = new Intent(this, ToClass.class);
Main.putExtra("userurl", url);
startActivity(Main);

doesn't start the activity you wrote in Main.java, it will attempt to start an activity called ToClass and if that doesn't exist, your app crashes.

Also, there is no such thing as "android.intent.action.start" so the manifest should look more like:

<activity android:name=".start" android:label="@string/app_name">
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
</activity>
<activity android:name= ".Main">
</activity>

I hope this fixes some of the issues you are encountering but I strongly suggest you check out some "getting started" tutorials for android development and build up from there.

Fragments onResume from back stack

I've changed the suggested solution a little bit. Works better for me like that:

private OnBackStackChangedListener getListener() {
    OnBackStackChangedListener result = new OnBackStackChangedListener() {
        public void onBackStackChanged() {
            FragmentManager manager = getSupportFragmentManager();
            if (manager != null) {
                int backStackEntryCount = manager.getBackStackEntryCount();
                if (backStackEntryCount == 0) {
                    finish();
                }
                Fragment fragment = manager.getFragments()
                                           .get(backStackEntryCount - 1);
                fragment.onResume();
            }
        }
    };
    return result;
}

Objects inside objects in javascript

You may have as many levels of Object hierarchy as you want, as long you declare an Object as being a property of another parent Object. Pay attention to the commas on each level, that's the tricky part. Don't use commas after the last element on each level:

{el1, el2, {el31, el32, el33}, {el41, el42}}

_x000D_
_x000D_
var MainObj = {_x000D_
_x000D_
  prop1: "prop1MainObj",_x000D_
  _x000D_
  Obj1: {_x000D_
    prop1: "prop1Obj1",_x000D_
    prop2: "prop2Obj1",    _x000D_
    Obj2: {_x000D_
      prop1: "hey you",_x000D_
      prop2: "prop2Obj2"_x000D_
    }_x000D_
  },_x000D_
    _x000D_
  Obj3: {_x000D_
    prop1: "prop1Obj3",_x000D_
    prop2: "prop2Obj3"_x000D_
  },_x000D_
  _x000D_
  Obj4: {_x000D_
    prop1: true,_x000D_
    prop2: 3_x000D_
  }  _x000D_
};_x000D_
_x000D_
console.log(MainObj.Obj1.Obj2.prop1);
_x000D_
_x000D_
_x000D_

Read a file one line at a time in node.js?

I wrap the whole logic of daily line processing as a npm module: line-kit https://www.npmjs.com/package/line-kit

_x000D_
_x000D_
// example_x000D_
var count = 0_x000D_
require('line-kit')(require('fs').createReadStream('/etc/issue'),_x000D_
                    (line) => { count++; },_x000D_
                    () => {console.log(`seen ${count} lines`)})
_x000D_
_x000D_
_x000D_

If WorkSheet("wsName") Exists

A version without error-handling:

Function sheetExists(sheetToFind As String) As Boolean
    sheetExists = False
    For Each sheet In Worksheets
        If sheetToFind = sheet.name Then
            sheetExists = True
            Exit Function
        End If
    Next sheet
End Function

Properly Handling Errors in VBA (Excel)

I definitely wouldn't use Block1. It doesn't seem right having the Error block in an IF statement unrelated to Errors.

Blocks 2,3 & 4 I guess are variations of a theme. I prefer the use of Blocks 3 & 4 over 2 only because of a dislike of the GOTO statement; I generally use the Block4 method. This is one example of code I use to check if the Microsoft ActiveX Data Objects 2.8 Library is added and if not add or use an earlier version if 2.8 is not available.

Option Explicit
Public booRefAdded As Boolean 'one time check for references

Public Sub Add_References()
Dim lngDLLmsadoFIND As Long

If Not booRefAdded Then
    lngDLLmsadoFIND = 28 ' load msado28.tlb, if cannot find step down versions until found

        On Error GoTo RefErr:
            'Add Microsoft ActiveX Data Objects 2.8
            Application.VBE.ActiveVBProject.references.AddFromFile _
            Environ("CommonProgramFiles") + "\System\ado\msado" & lngDLLmsadoFIND & ".tlb"

        On Error GoTo 0

    Exit Sub

RefErr:
        Select Case Err.Number
            Case 0
                'no error
            Case 1004
                 'Enable Trust Centre Settings
                 MsgBox ("Certain VBA References are not available, to allow access follow these steps" & Chr(10) & _
                 "Goto Excel Options/Trust Centre/Trust Centre Security/Macro Settings" & Chr(10) & _
                 "1. Tick - 'Disable all macros with notification'" & Chr(10) & _
                 "2. Tick - 'Trust access to the VBA project objects model'")
                 End
            Case 32813
                 'Err.Number 32813 means reference already added
            Case 48
                 'Reference doesn't exist
                 If lngDLLmsadoFIND = 0 Then
                    MsgBox ("Cannot Find Required Reference")
                    End
                Else
                    For lngDLLmsadoFIND = lngDLLmsadoFIND - 1 To 0 Step -1
                           Resume
                    Next lngDLLmsadoFIND
                End If

            Case Else
                 MsgBox Err.Number & vbCrLf & Err.Description, vbCritical, "Error!"
                End
        End Select

        On Error GoTo 0
End If
booRefAdded = TRUE
End Sub

How to force an entire layout View refresh?

To clear a view extending ViewGroup, you just need to use the method removeAllViews()

Just like this (if you have a ViewGroup called myElement) :

myElement.removeAllViews()

Proper way to use AJAX Post in jquery to pass model from strongly typed MVC3 view

If using MVC 5 read this solution!

I know the question specifically called for MVC 3, but I stumbled upon this page with MVC 5 and wanted to post a solution for anyone else in my situation. I tried the above solutions, but they did not work for me, the Action Filter was never reached and I couldn't figure out why. I am using version 5 in my project and ended up with the following action filter:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Filters;

namespace SydHeller.Filters
{
    public class ValidateJSONAntiForgeryHeader : FilterAttribute, IAuthorizationFilter
    {
        public void OnAuthorization(AuthorizationContext filterContext)
        {
            string clientToken = filterContext.RequestContext.HttpContext.Request.Headers.Get(KEY_NAME);
            if (clientToken == null)
            {
                throw new HttpAntiForgeryException(string.Format("Header does not contain {0}", KEY_NAME));
            }

            string serverToken = filterContext.HttpContext.Request.Cookies.Get(KEY_NAME).Value;
            if (serverToken == null)
            {
                throw new HttpAntiForgeryException(string.Format("Cookies does not contain {0}", KEY_NAME));
            }

            System.Web.Helpers.AntiForgery.Validate(serverToken, clientToken);
        }

        private const string KEY_NAME = "__RequestVerificationToken";
    }
}

-- Make note of the using System.Web.Mvc and using System.Web.Mvc.Filters, not the http libraries (I think that is one of the things that changed with MVC v5. --

Then just apply the filter [ValidateJSONAntiForgeryHeader] to your action (or controller) and it should get called correctly.

In my layout page right above </body> I have @AntiForgery.GetHtml();

Finally, in my Razor page, I do the ajax call as follows:

var formForgeryToken = $('input[name="__RequestVerificationToken"]').val();

$.ajax({
  type: "POST",
  url: serviceURL,
  contentType: "application/json; charset=utf-8",
  dataType: "json",
  data: requestData,
  headers: {
     "__RequestVerificationToken": formForgeryToken
  },
     success: crimeDataSuccessFunc,
     error: crimeDataErrorFunc
});

What are naming conventions for MongoDB?

  1. Keep'em short: Optimizing Storage of Small Objects, SERVER-863. Silly but true.

  2. I guess pretty much the same rules that apply to relation databases should apply here. And after so many decades there is still no agreement whether RDBMS tables should be named singular or plural...

  3. MongoDB speaks JavaScript, so utilize JS naming conventions of camelCase.

  4. MongoDB official documentation mentions you may use underscores, also built-in identifier is named _id (but this may be be to indicate that _id is intended to be private, internal, never displayed or edited.

How to update a menu item shown in the ActionBar?

I have used this code:

public boolean onPrepareOptionsMenu (Menu menu) {       
    MenuInflater inflater = getMenuInflater();
    TextView title  = (TextView) findViewById(R.id.title);
    menu.getItem(0).setTitle(
        getString(R.string.payFor) + " " + title.getText().toString());
    menu.getItem(1).setTitle(getString(R.string.payFor) + "...");
    return true;        
}

And worked like a charm to me you can find OnPrepareOptionsMenu here

What is the opposite of evt.preventDefault();

There is no opposite method of event.preventDefault() to understand why you first have to look into what event.preventDefault() does when you call it.

Underneath the hood, the functionality for preventDefault is essentially calling a return false which halts any further execution. If you’re familiar with the old ways of Javascript, it was once in fashion to use return false for canceling events on things like form submits and buttons using return true (before jQuery was even around).

As you probably might have already worked out based on the simple explanation above: the opposite of event.preventDefault() is nothing. You just don’t prevent the event, by default the browser will allow the event if you are not preventing it.

See below for an explanation:

;(function($, window, document, undefined)) {

    $(function() {
        // By default deny the submit
        var allowSubmit = false;

        $("#someform").on("submit", function(event) {

            if (!allowSubmit) {
                event.preventDefault();

                // Your code logic in here (maybe form validation or something)
                // Then you set allowSubmit to true so this code is bypassed

                allowSubmit = true;
            }

        });
    });

})(jQuery, window, document);

In the code above you will notice we are checking if allowSubmit is false. This means we will prevent our form from submitting using event.preventDefault and then we will do some validation logic and if we are happy, set allowSubmit to true.

This is really the only effective method of doing the opposite of event.preventDefault() – you can also try removing events as well which essentially would achieve the same thing.

How to show soft-keyboard when edittext is focused

I discovered a strange behaviour, since in one of my apps, the soft keyboard was automatically showing on entering the activity (there is an editText.requestFocus() in onCreate).

On digging further, I discovered that this was because there is a ScrollView around the layout. If I remove the ScrollView, the behaviour is as described in the original problem statement: only on clicking the already focused editText does the soft keyboard show up.

If it doesn't work for you, try putting in a ScrollView -- it's harmless anyway.

Reload browser window after POST without prompting user to resend POST data

Use

RefreshForm.submit(); 

instead of

document.location.reload(true); 

Android BroadcastReceiver within Activity

You forget to write .show() at the end, which is used to show the toast message.

Toast.makeText(getApplicationContext(), "received", Toast.LENGTH_SHORT).show();

It is a common mistake that programmer does, but i am sure after this you won't repeat the mistake again... :D

Difference between onStart() and onResume()

A particularly feisty example is when you decide to show a managed Dialog from an Activity using showDialog(). If the user rotates the screen while the dialog is still open (we call this a "configuration change"), then the main Activity will go through all the ending lifecycle calls up untill onDestroy(), will be recreated, and go back up through the lifecycles. What you might not expect however, is that onCreateDialog() and onPrepareDialog() (the methods that are called when you do showDialog() and now again automatically to recreate the dialog - automatically since it is a managed dialog) are called between onStart() and onResume(). The pointe here is that the dialog does not cover the full screen and therefore leaves part of the main activity visible. It's a detail but it does matter!

How to use registerReceiver method?

Broadcast receivers receive events of a certain type. I don't think you can invoke them by class name.

First, your IntentFilter must contain an event.

static final String SOME_ACTION = "com.yourcompany.yourapp.SOME_ACTION";
IntentFilter intentFilter = new IntentFilter(SOME_ACTION);

Second, when you send a broadcast, use this same action:

Intent i = new Intent(SOME_ACTION);
sendBroadcast(i);

Third, do you really need MyIntentService to be inline? Static? [EDIT] I discovered that MyIntentSerivce MUST be static if it is inline.

Fourth, is your service declared in the AndroidManifest.xml?

javascript: pause setTimeout();

I don't think you'll find anything better than clearTimeout. Anyway, you can always schedule another timeout later, instead 'resuming' it.

Change application's starting activity

If you are using Android Studio and you might have previously selected another Activity to launch.

Click on Run > Edit configuration and then make sure that Launch default Activity is selected.

Launch default Activity

IEnumerable vs List - What to Use? How do they work?

Nobody mentioned one crucial difference, ironically answered on a question closed as a duplicated of this.

IEnumerable is read-only and List is not.

See Practical difference between List and IEnumerable

Scroll to a div using jquery

First, your code does not contain a contact div, it has a contacts div!

In sidebar you have contact in the div at the bottom of the page you have contacts. I removed the final s for the code sample. (you also misspelled the projectslink id in the sidebar).

Second, take a look at some of the examples for click on the jQuery reference page. You have to use click like, object.click( function() { // Your code here } ); in order to bind a click event handler to the object.... Like in my example below. As an aside, you can also just trigger a click on an object by using it without arguments, like object.click().

Third, scrollTo is a plugin in jQuery. I don't know if you have the plugin installed. You can't use scrollTo() without the plugin. In this case, the functionality you desire is only 2 lines of code, so I see no reason to use the plugin.

Ok, now on to a solution.

The code below will scroll to the correct div if you click a link in the sidebar. The window does have to be big enough to allow scrolling:

// This is a functions that scrolls to #{blah}link
function goToByScroll(id) {
    // Remove "link" from the ID
    id = id.replace("link", "");
    // Scroll
    $('html,body').animate({
        scrollTop: $("#" + id).offset().top
    }, 'slow');
}

$("#sidebar > ul > li > a").click(function(e) {
    // Prevent a page reload when a link is pressed
    e.preventDefault();
    // Call the scroll function
    goToByScroll(this.id);
});

Live Example

( Scroll to function taken from here )


PS: Obviously you should have a compelling reason to go this route instead of using anchor tags <a href="#gohere">blah</a> ... <a name="gohere">blah title</a>

ORA-00054: resource busy and acquire with NOWAIT specified

Thanks for the info user 'user712934'

You can also look up the sql,username,machine,port information and get to the actual process which holds the connection

SELECT O.OBJECT_NAME, S.SID, S.SERIAL#, P.SPID, S.PROGRAM,S.USERNAME,
S.MACHINE,S.PORT , S.LOGON_TIME,SQ.SQL_FULLTEXT 
FROM V$LOCKED_OBJECT L, DBA_OBJECTS O, V$SESSION S, 
V$PROCESS P, V$SQL SQ 
WHERE L.OBJECT_ID = O.OBJECT_ID 
AND L.SESSION_ID = S.SID AND S.PADDR = P.ADDR 
AND S.SQL_ADDRESS = SQ.ADDRESS;

slashes in url variables

Check out this w3schools page about "HTML URL Encoding Reference": https://www.w3schools.com/tags/ref_urlencode.asp

for / you would escape with %2F

How to get anchor text/href on click using jQuery?

Updated code

$('a','div.res').click(function(){
  var currentAnchor = $(this);
  alert(currentAnchor.text());
  alert(currentAnchor.attr('href'));
});

How to keep onItemSelected from firing off on a newly instantiated Spinner?

My small contribution is a variation on some of the above that has suited me a few times.

Declare an integer variable as a default value (or last used value saved in preferences). Use spinner.setSelection(myDefault) to set that value before the listener is registered. In the onItemSelected check whether the new spinner value equals the value you assigned before running any further code.

This has the added advantage of not running code if the user selects the same value again.

What data type to use in MySQL to store images?

What you need, according to your comments, is a 'BLOB' (Binary Large OBject) for both image and resume.

Table overflowing outside of div

You can prevent tables from expanding beyond their parent div by using table-layout:fixed.

The CSS below will make your tables expand to the width of the div surrounding it.

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

I found this trick here.

What does the "On Error Resume Next" statement do?

On Error Resume Next means that On Error, It will resume to the next line to resume.

e.g. if you try the Try block, That will stop the script if a error occurred

Activity <App Name> has leaked ServiceConnection <ServiceConnection Name>@438030a8 that was originally bound here

Try using unbindService() in OnUserLeaveHint(). It prevents the the ServiceConnection leaked scenario and other exceptions.
I used it in my code and works fine.

How do I run a class in a WAR from the command line?

To execute SomeClass.main(String [] args) from a deployed war file do:

Step 1: Write class SomeClass.java that has a main method method i.e. (public static void main(String[] args) {...})

Step 2: Deploy your WAR

Step 3: cd /usr/local/yourprojectsname/tomcat/webapps/projectName/WEB-INF

Step 4: java -cp "lib/jar1.jar:lib/jar2.jar: ... :lib/jarn.jar" com.mypackage.SomeClass arg1 arg2 ... arg3

Note1: (to see if the class SomeOtherClass.class is in /usr/tomcat/webapps/projectName/WEB-INF/lib)

run --> cd /usr/tomcat/webapps/projectName/WEB-INF/lib && find . -name '*.jar' | while read jarfile; do if jar tf "$jarfile" | grep SomeOtherClass.class; then echo "$jarfile"; fi; done

Note2: Write to standard out so you can see if your main actually works via print statements to the console. This is called a back door.

Note3: The comment above by Bozhidar Bozhanov seems correct

Pass table as parameter into sql server UDF

PASSING TABLE AS PARAMETER IN STORED PROCEDURE

Step 1:

CREATE TABLE [DBO].T_EMPLOYEES_DETAILS ( Id int, Name nvarchar(50), Gender nvarchar(10), Salary int )

Step 2:

CREATE TYPE EmpInsertType AS TABLE ( Id int, Name nvarchar(50), Gender nvarchar(10), Salary int )

Step 3:

/* Must add READONLY keyword at end of the variable */

CREATE PROC PRC_EmpInsertType @EmployeeInsertType EmpInsertType READONLY AS BEGIN INSERT INTO [DBO].T_EMPLOYEES_DETAILS SELECT * FROM @EmployeeInsertType END

Step 4:

DECLARE @EmployeeInsertType EmpInsertType

INSERT INTO @EmployeeInsertType VALUES(1,'John','Male',50000) INSERT INTO @EmployeeInsertType VALUES(2,'Praveen','Male',60000) INSERT INTO @EmployeeInsertType VALUES(3,'Chitra','Female',45000) INSERT INTO @EmployeeInsertType VALUES(4,'Mathy','Female',6600) INSERT INTO @EmployeeInsertType VALUES(5,'Sam','Male',50000)

EXEC PRC_EmpInsertType @EmployeeInsertType

=======================================

SELECT * FROM T_EMPLOYEES_DETAILS

OUTPUT

1 John Male 50000

2 Praveen Male 60000

3 Chitra Female 45000

4 Mathy Female 6600

5 Sam Male 50000

Rails: How do I create a default value for attributes in Rails activerecord's model?

I found a better way to do it now:

def status=(value) 
  self[:status] = 'P' 
end 

In Ruby a method call is allowed to have no parentheses, therefore I should name the local variable into something else, otherwise Ruby will recognize it as a method call.

How to add an UIViewController's view as subview

You may use PopupController for the same one the SDK which shows UIViewController as subview You may check PopupController

Here is sample code for the same

popup = PopupController
        .create(self.navigationController!)
        .customize(
            [
                .layout(.center),
                .animation(.fadeIn),
                .backgroundStyle(.blackFilter(alpha: 0.8)),
                .dismissWhenTaps(true),
                .scrollable(true)
            ]
        )
        .didShowHandler { popup in
        }
        .didCloseHandler { popup in
    }
    let container = MTMPlayerAndCardSelectionVC.instance()
    container.closeHandler = {() in
        self.popup.dismiss()
    }

    popup.show(container)

Error Handler - Exit Sub vs. End Sub

Your ProcExit label is your place where you release all the resources whether an error happened or not. For instance:

Public Sub SubA()
  On Error Goto ProcError

  Connection.Open
  Open File for Writing
  SomePreciousResource.GrabIt

ProcExit:  
  Connection.Close
  Connection = Nothing
  Close File
  SomePreciousResource.Release

  Exit Sub

ProcError:  
  MsgBox Err.Description  
  Resume ProcExit
End Sub

PL/SQL block problem: No data found error

Your SELECT statement isn't finding the data you're looking for. That is, there is no record in the ENROLLMENT table with the given STUDENT_ID and SECTION_ID. You may want to try putting some DBMS_OUTPUT.PUT_LINE statements before you run the query, printing the values of v_student_id and v_section_id. They may not be containing what you expect them to contain.

Good Patterns For VBA Error Handling

So you could do something like this

Function Errorthingy(pParam)
On Error GoTo HandleErr

 ' your code here

    ExitHere:
    ' your finally code
    Exit Function

    HandleErr:
        Select Case Err.Number
        ' different error handling here'
        Case Else
            MsgBox "Error " & Err.Number & ": " & Err.Description, vbCritical, "ErrorThingy"
        End Select


   Resume ExitHere

End Function

If you want to bake in custom exceptions. (e.g. ones that violate business rules) use the example above but use the goto to alter the flow of the method as necessary.

How to parse this string in Java?

If it's a File, you can get the parts by creating an instanceof File and then ask for its segments.

This is good because it'll work regardless of the direction of the slashes; it's platform independent (except for the "drive letters" in windows...)

How to have the cp command create any necessary folders for copying a file to a destination

For those that are on Mac OSX, perhaps the easiest way to work around this is to use ditto (only on the mac, AFAIK, though). It will create the directory structure that is missing in the destination.

For instance, I did this

ditto 6.3.2/6.3.2/macosx/bin/mybinary ~/work/binaries/macosx/6.3.2/

where ~/work did not contain the binaries directory before I ran the command.

I thought rsync should work similarly, but it seems it only works for one level of missing directories. That is,

rsync 6.3.3/6.3.3/macosx/bin/mybinary ~/work/binaries/macosx/6.3.3/

worked, because ~/work/binaries/macosx existed but not ~/work/binaries/macosx/6.3.2/

Fling gesture detection on grid layout

I know its too late to answer but Still I am posting Swipe Detection for ListView that How to use Swipe Touch Listener in ListView Item.

Refrence: Exterminator13(one of answer in this page)

Make one ActivitySwipeDetector.class

package com.example.wocketapp;

import android.content.Context;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;

public class ActivitySwipeDetector implements View.OnTouchListener 
{
    static final String logTag = "SwipeDetector";
    private SwipeInterface activity;
    private float downX, downY;
    private long timeDown;
    private final float MIN_DISTANCE;
    private final int VELOCITY;
    private final float MAX_OFF_PATH;

    public ActivitySwipeDetector(Context context, SwipeInterface activity)
    {
        this.activity = activity;
        final ViewConfiguration vc = ViewConfiguration.get(context);
        DisplayMetrics dm = context.getResources().getDisplayMetrics();
        MIN_DISTANCE = vc.getScaledPagingTouchSlop() * dm.density;
        VELOCITY = vc.getScaledMinimumFlingVelocity();
        MAX_OFF_PATH = MIN_DISTANCE * 2;
    }

    public void onRightToLeftSwipe(View v) 
    {
        Log.i(logTag, "RightToLeftSwipe!");
        activity.onRightToLeft(v);
    }

    public void onLeftToRightSwipe(View v) 
    {
        Log.i(logTag, "LeftToRightSwipe!");
        activity.onLeftToRight(v);
    }

    public boolean onTouch(View v, MotionEvent event) 
    {
        switch (event.getAction()) 
        {
            case MotionEvent.ACTION_DOWN:
            {
                Log.d("onTouch", "ACTION_DOWN");
                timeDown = System.currentTimeMillis();
                downX = event.getX();
                downY = event.getY();
                v.getParent().requestDisallowInterceptTouchEvent(false);
                return true;
            }

        case MotionEvent.ACTION_MOVE:
            {
                float y_up = event.getY();
                float deltaY = y_up - downY;
                float absDeltaYMove = Math.abs(deltaY);

                if (absDeltaYMove > 60) 
                {
                    v.getParent().requestDisallowInterceptTouchEvent(false);
                } 
                else
                {
                    v.getParent().requestDisallowInterceptTouchEvent(true);
                }
            }

            break;

            case MotionEvent.ACTION_UP: 
            {
                Log.d("onTouch", "ACTION_UP");
                long timeUp = System.currentTimeMillis();
                float upX = event.getX();
                float upY = event.getY();

                float deltaX = downX - upX;
                float absDeltaX = Math.abs(deltaX);
                float deltaY = downY - upY;
                float absDeltaY = Math.abs(deltaY);

                long time = timeUp - timeDown;

                if (absDeltaY > MAX_OFF_PATH) 
                {
                    Log.e(logTag, String.format(
                            "absDeltaY=%.2f, MAX_OFF_PATH=%.2f", absDeltaY,
                            MAX_OFF_PATH));
                    return v.performClick();
                }

                final long M_SEC = 1000;
                if (absDeltaX > MIN_DISTANCE && absDeltaX > time * VELOCITY / M_SEC) 
                {
                     v.getParent().requestDisallowInterceptTouchEvent(true);
                    if (deltaX < 0) 
                    {
                        this.onLeftToRightSwipe(v);
                        return true;
                    }
                    if (deltaX > 0) 
                    {
                        this.onRightToLeftSwipe(v);
                        return true;
                    }
                }
                else 
                {
                    Log.i(logTag,
                            String.format(
                                    "absDeltaX=%.2f, MIN_DISTANCE=%.2f, absDeltaX > MIN_DISTANCE=%b",
                                    absDeltaX, MIN_DISTANCE,
                                    (absDeltaX > MIN_DISTANCE)));
                    Log.i(logTag,
                            String.format(
                                    "absDeltaX=%.2f, time=%d, VELOCITY=%d, time*VELOCITY/M_SEC=%d, absDeltaX > time * VELOCITY / M_SEC=%b",
                                    absDeltaX, time, VELOCITY, time * VELOCITY
                                            / M_SEC, (absDeltaX > time * VELOCITY
                                            / M_SEC)));
                }

                 v.getParent().requestDisallowInterceptTouchEvent(false);

            }
        }
        return false;
    }
    public interface SwipeInterface 
    {

        public void onLeftToRight(View v);

        public void onRightToLeft(View v);
    }

}

Call it from your activity class like this:

yourLayout.setOnTouchListener(new ActivitySwipeDetector(this, your_activity.this));

And Don't forget to implement SwipeInterface which will give you two @override methods:

    @Override
    public void onLeftToRight(View v) 
    {
        Log.e("TAG", "L to R");
    }

    @Override
    public void onRightToLeft(View v) 
    {
        Log.e("TAG", "R to L");
    }

Disabling browser caching for all browsers from ASP.NET

I've tried various combinations and had them fail in FireFox. It has been a while so the answer above may work fine or I may have missed something.

What has always worked for me is to add the following to the head of each page, or the template (Master Page in .net).

<script language="javascript" type="text/javascript">
    window.onbeforeunload = function () {   
        // This function does nothing.  It won't spawn a confirmation dialog   
        // But it will ensure that the page is not cached by the browser.
    }  
</script>

This has disabled all caching in all browsers for me without fail.

SQL Server: Extract Table Meta-Data (description, fields and their data types)

If you are pulling your queries using java code, there is a great class that can be used, ResultSetMetaData, that can retrieve column names and the properties of the columns (type and length).

Example

ResultSet rs = null;

        rs = sql.executeQuery();

        if (rs != null) {
            if (rs.next()) {
                ResultSetMetaData rsmd = rs.getMetaData();
                for (int i = 1; i <= rsmd.getColumnCount(); i++) {
                    System.out.println("column name: "
                            + rsmd.getColumnName(i));
                    System.out.println("column size: "
                            + rsmd.getColumnDisplaySize(i));
                }
            }

How can I use different certificates on specific connections?

We copy the JRE's truststore and add our custom certificates to that truststore, then tell the application to use the custom truststore with a system property. This way we leave the default JRE truststore alone.

The downside is that when you update the JRE you don't get its new truststore automatically merged with your custom one.

You could maybe handle this scenario by having an installer or startup routine that verifies the truststore/jdk and checks for a mismatch or automatically updates the truststore. I don't know what happens if you update the truststore while the application is running.

This solution isn't 100% elegant or foolproof but it's simple, works, and requires no code.

WSDL vs REST Pros and Cons

SOAP: It can be transported via SMTP also, means we can invoke the service using Email simple text format also

It needs additional framework/engine should be in web service consumer machine to convert SOAP message to respective objects structure in various languages.

REST: Now WSDL2.0 supports to describe REST web service also

We can use when you want to make your service as lightweight, example calling from mobile devices like cell phone, pda etc...

Using Transactions or SaveChanges(false) and AcceptAllChanges()?

With the Entity Framework most of the time SaveChanges() is sufficient. This creates a transaction, or enlists in any ambient transaction, and does all the necessary work in that transaction.

Sometimes though the SaveChanges(false) + AcceptAllChanges() pairing is useful.

The most useful place for this is in situations where you want to do a distributed transaction across two different Contexts.

I.e. something like this (bad):

using (TransactionScope scope = new TransactionScope())
{
    //Do something with context1
    //Do something with context2

    //Save and discard changes
    context1.SaveChanges();

    //Save and discard changes
    context2.SaveChanges();

    //if we get here things are looking good.
    scope.Complete();
}

If context1.SaveChanges() succeeds but context2.SaveChanges() fails the whole distributed transaction is aborted. But unfortunately the Entity Framework has already discarded the changes on context1, so you can't replay or effectively log the failure.

But if you change your code to look like this:

using (TransactionScope scope = new TransactionScope())
{
    //Do something with context1
    //Do something with context2

    //Save Changes but don't discard yet
    context1.SaveChanges(false);

    //Save Changes but don't discard yet
    context2.SaveChanges(false);

    //if we get here things are looking good.
    scope.Complete();
    context1.AcceptAllChanges();
    context2.AcceptAllChanges();

}

While the call to SaveChanges(false) sends the necessary commands to the database, the context itself is not changed, so you can do it again if necessary, or you can interrogate the ObjectStateManager if you want.

This means if the transaction actually throws an exception you can compensate, by either re-trying or logging state of each contexts ObjectStateManager somewhere.

See my blog post for more.

Globally catch exceptions in a WPF application?

AppDomain.UnhandledException Event

This event provides notification of uncaught exceptions. It allows the application to log information about the exception before the system default handler reports the exception to the user and terminates the application.

   public App()
   {
      AppDomain currentDomain = AppDomain.CurrentDomain;
      currentDomain.UnhandledException += new UnhandledExceptionEventHandler(MyHandler);    
   }

   static void MyHandler(object sender, UnhandledExceptionEventArgs args) 
   {
      Exception e = (Exception) args.ExceptionObject;
      Console.WriteLine("MyHandler caught : " + e.Message);
      Console.WriteLine("Runtime terminating: {0}", args.IsTerminating);
   }

If the UnhandledException event is handled in the default application domain, it is raised there for any unhandled exception in any thread, no matter what application domain the thread started in. If the thread started in an application domain that has an event handler for UnhandledException, the event is raised in that application domain. If that application domain is not the default application domain, and there is also an event handler in the default application domain, the event is raised in both application domains.

For example, suppose a thread starts in application domain "AD1", calls a method in application domain "AD2", and from there calls a method in application domain "AD3", where it throws an exception. The first application domain in which the UnhandledException event can be raised is "AD1". If that application domain is not the default application domain, the event can also be raised in the default application domain.

CryptographicException 'Keyset does not exist', but only through WCF

I hit this in my service fabric project after the cert used to authenticate against our key vault expired and was rotated, which changed the thumbprint. I got this error because I had missed updating the thumbprint in the applicationManifest.xml file in this block which precisely does what other answers have suggested - to given NETWORK SERVICE (which all my exes run as, standard config for azure servicefabric cluster) permissions to access the LOCALMACHINE\MY cert store location.

Note the "X509FindValue" attribute value.

_x000D_
_x000D_
<!-- this block added to allow low priv processes (such as service fabric processes) that run as NETWORK SERVICE to read certificates from the store -->_x000D_
  <Principals>_x000D_
    <Users>_x000D_
      <User Name="NetworkService" AccountType="NetworkService" />_x000D_
    </Users>_x000D_
  </Principals>_x000D_
  <Policies>_x000D_
    <SecurityAccessPolicies>_x000D_
      <SecurityAccessPolicy ResourceRef="AzureKeyvaultClientCertificate" PrincipalRef="NetworkService" GrantRights="Full" ResourceType="Certificate" />_x000D_
    </SecurityAccessPolicies>_x000D_
  </Policies>_x000D_
  <Certificates>_x000D_
    <SecretsCertificate X509FindValue="[[THIS KEY ALSO NEEDS TO BE UPDATED]]" Name="AzureKeyvaultClientCertificate" />_x000D_
  </Certificates>_x000D_
  <!-- end block -->
_x000D_
_x000D_
_x000D_

Use JavaScript to place cursor at end of text in text input element

el.setSelectionRange(-1, -1);

https://codesandbox.io/s/peaceful-bash-x2mti

This method updates the HTMLInputElement.selectionStart, selectionEnd, and selectionDirection properties in one call.

https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/setSelectionRange

In other js methods -1 usually means (to the) last character. This is the case for this one too, but I couldn't find explicit mention of this behavior in the docs.

How do I suspend painting for a control and its children?

Or just use Control.SuspendLayout() and Control.ResumeLayout().

Verify if file exists or not in C#

Can't comment yet, but I just wanted to disagree/clarify with erikkallen.

You should not just catch the exception in the situation you've described. If you KNEW that the file should be there and due to some exceptional case, it wasn't, then it would be acceptable to just attempt to access the file and catch any exception that occurs.

In this case, however, you are receiving input from a user and have little reason to believe that the file exists. Here you should always use File.Exists().

I know it is cliché, but you should only use Exceptions for an exceptional event, not as part as the normal flow of your application. It is expensive and makes code more difficult to read/follow.

Efficiently updating database using SQLAlchemy ORM

Withough testing, I'd try:

for c in session.query(Stuff).all():
     c.foo = c.foo+1
session.commit()

(IIRC, commit() works without flush()).

I've found that at times doing a large query and then iterating in python can be up to 2 orders of magnitude faster than lots of queries. I assume that iterating over the query object is less efficient than iterating over a list generated by the all() method of the query object.

[Please note comment below - this did not speed things up at all].

VBScript -- Using error handling

I'm exceptionally new to VBScript, so this may not be considered best practice or there may be a reason it shouldn't be done this that way I'm not yet aware of, but this is the solution I came up with to trim down the amount of error logging code in my main code block.

Dim oConn, connStr
Set oConn = Server.CreateObject("ADODB.Connection")
connStr = "Provider=SQLOLEDB;Server=XX;UID=XX;PWD=XX;Databse=XX"

ON ERROR RESUME NEXT

oConn.Open connStr
If err.Number <> 0 Then : showError() : End If


Sub ShowError()

    'You could write the error details to the console...
    errDetail = "<script>" & _
    "console.log('Description: " & err.Description & "');" & _
    "console.log('Error number: " & err.Number & "');" & _
    "console.log('Error source: " & err.Source & "');" & _
    "</script>"

    Response.Write(errDetail)       

    '...you could display the error info directly in the page...
    Response.Write("Error Description: " & err.Description)
    Response.Write("Error Source: " & err.Source)
    Response.Write("Error Number: " & err.Number)

    '...or you could execute additional code when an error is thrown...
    'Insert error handling code here

    err.clear
End Sub

Is HTML considered a programming language?

Well, L is for language, but it doesn't imply programming language. After all, English or French are (natural) languages too! ;-)

As said above, put them under a subsidiary section, Technology seems to be a good term.

(Looking at my own resume, not updated in a while) I have made a section just called "Languages", so I can't get wrong... :-D
I have put "(X)HTML and CSS, XML/DTD/Schema and SVG" at the end of the section, clearly separated.

In French, I have a section "Langages" (programming and markup) and another "Langues" (French/English). In the English version, I titled both at "Languages", which is clumsy now that I think of it, although context clarify this. I should find a better formulation.

How to set a value to a file input in HTML?

As everyone else here has stated: You cannot upload just any file automatically with JavaScript.

HOWEVER! If you have access to the information you want to send in your code (i.e., not C:\passwords.txt), then you can upload it as a blob-type, and then treat it as a file.

What the server will end up seeing will be indistinguishable from someone actually setting the value of <input type="file" />. The trick, ultimately, is to begin a new XMLHttpRequest() with the server...

function uploadFile (data) {
        // define data and connections
    var blob = new Blob([JSON.stringify(data)]);
    var url = URL.createObjectURL(blob);
    var xhr = new XMLHttpRequest();
    xhr.open('POST', 'myForm.php', true);
    
        // define new form
    var formData = new FormData();
    formData.append('someUploadIdentifier', blob, 'someFileName.json');
        
        // action after uploading happens
    xhr.onload = function(e) {
        console.log("File uploading completed!");
    };
    
        // do the uploading
    console.log("File uploading started!");
    xhr.send(formData);
}

    // This data/text below is local to the JS script, so we are allowed to send it!
uploadFile({'hello!':'how are you?'});

So, what could you possibly use this for? I use it for uploading HTML5 canvas elements as jpg's. This saves the user the trouble of having to open a file input element, only to select the local, cached image that they just resized, modified, etc.. But it should work for any file type.

How do I delete all the duplicate records in a MySQL table without temp tables

Thanks to jveirasv for the answer above.

If you need to remove duplicates of a specific sets of column, you can use this (if you have a timestamp in the table that vary for example)

CREATE TABLE TableA_Verify AS SELECT * FROM TableA WHERE 1 GROUP BY [COLUMN TO remove duplicates BY];

DELETE FROM TableA;

INSERT INTO TableA SELECT * FROM TAbleA_Verify;

DROP TABLE TableA_Verify;

Error when checking model input: expected convolution2d_input_1 to have 4 dimensions, but got array with shape (32, 32, 3)

Got the same problem, non of the answers worked for me. After a lot of debugging I found out that the size of one image was smaller than 32. This leads to a broken array with wrong dimensions and the above mentioned error.

To solve the problem, make sure that all images have the correct dimensions.

Get current date in Swift 3?

You can do it in this way with Swift 3.0:

let date = Date()
let calendar = Calendar.current
let components = calendar.dateComponents([.year, .month, .day], from: date)

let year =  components.year
let month = components.month
let day = components.day

print(year)
print(month)
print(day)

ngFor with index as value in attribute

I think its already been answered before, but just a correction if you are populating an unordered list, the *ngFor will come in the element which you want to repeat. So it should be insdide <li>. Also, Angular2 now uses let to declare a variable.

<ul>
    <li *ngFor="let item of items; let i = index" [attr.data-index]="i">     
               {{item}}
    </li>
</ul>

Simple JavaScript Checkbox Validation

Another simple way is to create a function and check if the checkbox(es) are checked or not, and disable a button that way using jQuery.

HTML:

<input type="checkbox" id="myCheckbox" />
<input type="submit" id="myButton" />

JavaScript:

var alterDisabledState = function () {

var isMyCheckboxChecked = $('#myCheckbox').is(':checked');

     if (isMyCheckboxChecked) {
     $('myButton').removeAttr("disabled");
     } 
     else {
             $('myButton').attr("disabled", "disabled");
     }
}

Now you have a button that is disabled until they select the checkbox, and now you have a better user experience. I would make sure that you still do the server side validation though.

What is the minimum length of a valid international phone number?

EDIT 2015-06-27: Minimum is actually 8, including country code. My bad.

Original post

The minimum phone number that I use is 10 digits. International users should always be putting their country code, and as far as I know there are no countries with fewer than ten digits if you count country code.

More info here: https://en.wikipedia.org/wiki/Telephone_numbering_plan

How to determine the first and last iteration in a foreach loop?

You could use a counter:

$i = 0;
$len = count($array);
foreach ($array as $item) {
    if ($i == 0) {
        // first
    } else if ($i == $len - 1) {
        // last
    }
    // …
    $i++;
}

Can not deserialize instance of java.util.ArrayList out of VALUE_STRING

do you try

[{"name":"myEnterprise", "departments":["HR"]}]

the square brace is the key point.

Is it possible to decompile a compiled .pyc file into a .py file?

Uncompyle6 works for Python 3.x and 2.7 - recommended option as it's most recent tool, aiming to unify earlier forks and focusing on automated unit testing. The GitHub page has more details.

  • if you use Python 3.7+, you could also try decompile3, a fork of Uncompyle6 focusing on 3.7 and higher.
  • do raise GitHub issues on these projects if needed - both run unit test suites on a range of Python versions

With these tools, you get your code back including variable names and docstrings, but without the comments.

The older Uncompyle2 supports Python 2.7 only. This worked well for me some time ago to decompile the .pyc bytecode into .py, whereas unpyclib crashed with an exception.

Get $_POST from multiple checkboxes

It's pretty simple. Pay attention and you'll get it right away! :)

You will create a html array, which will be then sent to php array. Your html code will look like this:

<input type="checkbox" name="check_list[1]" alt="Checkbox" value="checked">
<input type="checkbox" name="check_list[2]" alt="Checkbox" value="checked">
<input type="checkbox" name="check_list[3]" alt="Checkbox" value="checked">

Where [1] [2] [3] are the IDs of your messages, meaning that you will echo your $row['Report ID'] in their place.

Then, when you submit the form, your PHP array will look like this:

print_r($check_list)

[1] => checked [3] => checked

Depending on which were checked and which were not.

I'm sure you can continue from this point forward.

Deserialize Java 8 LocalDateTime with JacksonMapper

This worked for me :

import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.format.annotation.DateTimeFormat.ISO;

@Column(name="end_date", nullable = false)
@DateTimeFormat(iso = ISO.DATE_TIME)
@JsonFormat(pattern = "yyyy-MM-dd HH:mm")
private LocalDateTime endDate;

How to submit a form on enter when the textarea has focus?

You can't do this without JavaScript. Stackoverflow is using the jQuery JavaScript library which attachs functions to HTML elements on page load.

Here's how you could do it with vanilla JavaScript:

<textarea onkeydown="if (event.keyCode == 13) { this.form.submit(); return false; }"></textarea>

Keycode 13 is the enter key.

Here's how you could do it with jQuery like as Stackoverflow does:

<textarea class="commentarea"></textarea>

with

$(document).ready(function() {
    $('.commentarea').keydown(function(event) {
        if (event.which == 13) {
            this.form.submit();
            event.preventDefault();
         }
    });
});

Convert Datetime column from UTC to local time in select statement

In postgres this works very nicely..Tell the server the time at which the time is saved, 'utc', and then ask it to convert to a specific timezone, in this case 'Brazil/East'

quiz_step_progresses.created_at  at time zone 'utc' at time zone 'Brazil/East'

Get a complete list of timezones with the following select;

select * from pg_timezone_names;

See details here.

https://popsql.com/learn-sql/postgresql/how-to-convert-utc-to-local-time-zone-in-postgresql

Need to find a max of three numbers in java

Two things: Change the variables x, y, z as int and call the method as Math.max(Math.max(x,y),z) as it accepts two parameters only.

In Summary, change below:

    String x = keyboard.nextLine();
    String y = keyboard.nextLine();
    String z = keyboard.nextLine();
    int max = Math.max(x,y,z);

to

    int x = keyboard.nextInt();
    int y = keyboard.nextInt();
    int z = keyboard.nextInt();
    int max =  Math.max(Math.max(x,y),z);

How to create a BKS (BouncyCastle) format Java Keystore that contains a client certificate chain

Not sure you resolved this issue or not, but this is how I do it and it works on Android:

  1. Use openssl to merge client's cert(cert must be signed by a CA that accepted by server) and private key into a PCKS12 format key pair: openssl pkcs12 -export -in clientcert.pem -inkey clientkey.pem -out client.p12
  2. You may need patch your JRE to umlimited strength encryption depends on your key strength: copy the jar files fromJCE 5.0 unlimited strength Jurisdiction Policy FIles and override those in your JRE (eg.C:\Program Files\Java\jre6\lib\security)
  3. Use Portecle tool mentioned above and create a new keystore with BKS format
  4. Import PCKS12 key pair generated in step 1 and save it as BKS keystore. This keystore works with Android client authentication.
  5. If you need to do certificate chain, you can use this IBM tool:KeyMan to merge client's PCKS12 key pair with CA cert. But it only generate JKS keystore, so you again need Protecle to convert it to BKS format.

How to define several include path in Makefile

You need to use -I with each directory. But you can still delimit the directories with whitespace if you use (GNU) make's foreach:

INC=$(DIR1) $(DIR2) ...
INC_PARAMS=$(foreach d, $(INC), -I$d)

How can I create a simple message box in Python?

Not the best, here is my basic Message box using only tkinter.

#Python 3.4
from    tkinter import  messagebox  as  msg;
import  tkinter as      tk;

def MsgBox(title, text, style):
    box = [
        msg.showinfo,       msg.showwarning,    msg.showerror,
        msg.askquestion,    msg.askyesno,       msg.askokcancel,        msg.askretrycancel,
];

tk.Tk().withdraw(); #Hide Main Window.

if style in range(7):
    return box[style](title, text);

if __name__ == '__main__':

Return = MsgBox(#Use Like This.
    'Basic Error Exemple',

    ''.join( [
        'The Basic Error Exemple a problem with test',                      '\n',
        'and is unable to continue. The application must close.',           '\n\n',
        'Error code Test',                                                  '\n',
        'Would you like visit http://wwww.basic-error-exemple.com/ for',    '\n',
        'help?',
    ] ),

    2,
);

print( Return );

"""
Style   |   Type        |   Button      |   Return
------------------------------------------------------
0           Info            Ok              'ok'
1           Warning         Ok              'ok'
2           Error           Ok              'ok'
3           Question        Yes/No          'yes'/'no'
4           YesNo           Yes/No          True/False
5           OkCancel        Ok/Cancel       True/False
6           RetryCancal     Retry/Cancel    True/False
"""

What is the syntax of the enhanced for loop in Java?

Enhanced for loop:

for (String element : array) {

    // rest of code handling current element
}

Traditional for loop equivalent:

for (int i=0; i < array.length; i++) {
    String element = array[i]; 

    // rest of code handling current element
}

Take a look at these forums: https://blogs.oracle.com/CoreJavaTechTips/entry/using_enhanced_for_loops_with

http://www.java-tips.org/java-se-tips/java.lang/the-enhanced-for-loop.html

Where does flask look for image files?

Is the image file ayrton_senna_movie_wallpaper_by_bashgfx-d4cm6x6.jpg in your static directory? If you move it to your static directory and update your HTML as such:

<img src="/static/ayrton_senna_movie_wallpaper_by_bashgfx-d4cm6x6.jpg">

It should work.

Also, it is worth noting, there is a better way to structure this.

File structure:

app.py
static
   |----ayrton_senna_movie_wallpaper_by_bashgfx-d4cm6x6.jpg
templates
   |----index.html

app.py

from flask import Flask, render_template, url_for
app = Flask(__name__)

@app.route('/index', methods=['GET', 'POST'])
def lionel(): 
    return render_template('index.html')

if __name__ == '__main__':
    app.run()

templates/index.html

<html>
  <head>

  </head>
  <body>
    <h1>Hi Lionel Messi</h1>

  <img src="{{url_for('static', filename='ayrton_senna_movie_wallpaper_by_bashgfx-d4cm6x6.jpg')}}" />

  </body>

</html>

Doing it this way ensures that you are not hard-coding a URL path for your static assets.

How eliminate the tab space in the column in SQL Server 2008

See it might be worked -------

UPDATE table_name SET column_name=replace(column_name, ' ', '') //Remove white space

UPDATE table_name SET column_name=replace(column_name, '\n', '') //Remove newline

UPDATE table_name SET column_name=replace(column_name, '\t', '') //Remove all tab

Thanks Subroto

SVN Error - Not a working copy

Maybe you just copied tree of folder and trying to add lowest one.

SVN
|_
  |
  subfolder1
       |
       subfolder2   (here you get an error)

in that case you have to commit directory on the upper level.

What does <meta http-equiv="X-UA-Compatible" content="IE=edge"> do?

Just one sentence to say Instruct Internet Explorer to use its latest rendering engine

<meta http-equiv="x-ua-compatible" content="ie=edge">

Cannot use special principal dbo: Error 15405

To fix this, open the SQL Server Management Studio and click New Query. Then type:

USE mydatabase
exec sp_changedbowner 'sa', 'true'

Shell script - remove first and last quote (") from a variable

Use tr to delete ":

 echo "$opt" | tr -d '"'

Note: This removes all double quotes, not just leading and trailing.

Make javascript alert Yes/No Instead of Ok/Cancel

In an attempt to solve a similar situation I've come across this example and adapted it. It uses JQUERY UI Dialog as Nikhil D suggested. Here is a look at the code:

HTML:

<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.6/themes/smoothness/jquery-ui.css" rel="stylesheet"/>
<input type="button" id="box" value="Confirm the thing?" />
<div id="dialog-confirm"></div>

JavaScript:

$('#box').click(function buttonAction() {
  $("#dialog-confirm").html("Do you want to do the thing?");

  // Define the Dialog and its properties.
  $("#dialog-confirm").dialog({
    resizable: false,
    modal: true,
    title: "Do the thing?",
    height: 250,
    width: 400,
    buttons: {
      "Yes": function() {
        $(this).dialog('close');
        alert("Yes, do the thing");
      },
      "No": function() {
        $(this).dialog('close');
        alert("Nope, don't do the thing");
      }
    }
  });
});

$('#box').click(buttonAction);

I have a few more tweaks I need to do to make this example work for my application. Will update this if I see it fit into the answer. Hope this helps someone.

Capture HTML Canvas as gif/jpg/png/pdf?

Here is some help if you do the download through a server (this way you can name/convert/post-process/etc your file):

-Post data using toDataURL

-Set the headers

$filename = "test.jpg"; //or png
header('Content-Description: File Transfer');
if($msie = !strstr($_SERVER["HTTP_USER_AGENT"],"MSIE")==false)      
  header("Content-type: application/force-download");else       
  header("Content-type: application/octet-stream"); 
header("Content-Disposition: attachment; filename=\"$filename\"");   
header("Content-Transfer-Encoding: binary"); 
header("Expires: 0"); header("Cache-Control: must-revalidate"); 
header("Pragma: public");

-create image

$data = $_POST['data'];
$img = imagecreatefromstring(base64_decode(substr($data,strpos($data,',')+1)));

-export image as JPEG

$width = imagesx($img);
$height = imagesy($img);
$output = imagecreatetruecolor($width, $height);
$white = imagecolorallocate($output,  255, 255, 255);
imagefilledrectangle($output, 0, 0, $width, $height, $white);
imagecopy($output, $img, 0, 0, 0, 0, $width, $height);
imagejpeg($output);
exit();

-or as transparent PNG

imagesavealpha($img, true);
imagepng($img);
die($img);

How to access shared folder without giving username and password

You need to go to user accounts and enable Guest Account, its default disabled. Once you do this, you share any folder and add the guest account to the list of users who can accesss that specific folder, this also includes to Turn off password Protected Sharing in 'Advanced Sharing Settings'

The other way to do this where you only enter a password once is to join a Homegroup. if you have a network of 2 or more computers, they can all connect to a homegroup and access all the files they need from each other, and anyone outside the group needs a 1 time password to be able to access your network, this was introduced in windows 7.

Switch: Multiple values in one case?

You can use ifelse instead.but if you want to know how to use switch in this case.here is an example.

int age = Convert.ToInt32(txtBoxAge.Text);`
int flag;
if(age >= 1 && age <= 8) {
flag = 1;
} else if (age >= 9 && age <= 15) {
 flag = 2;
} else if (age >= 16 && age <= 100) {
 flag = 3;
} else {
 flag = 4;   
}
switch (flag) 

{
 case 1:
  MessageBox.Show("You are only " + age + " years old\n You must be kidding right.\nPlease fill in your *real* age.");
break;
case 2:
  MessageBox.Show("You are only " + age + " years old\n That's too young!");
break;
case 3:
  MessageBox.Show("You are " + age + " years old\n Perfect.");
break;
default:
  MessageBox.Show("You an old person.");
break;
}

hope that helps ! :)

How do you format a Date/Time in TypeScript?

Here is another option for Angular (using own formatting function) - this one is for format:

YYYY-mm-dd hh:nn:ss

-you can adjust to your formats, just re-order the lines and change separators

dateAsYYYYMMDDHHNNSS(date): string {
  return date.getFullYear()
            + '-' + this.leftpad(date.getMonth() + 1, 2)
            + '-' + this.leftpad(date.getDate(), 2)
            + ' ' + this.leftpad(date.getHours(), 2)
            + ':' + this.leftpad(date.getMinutes(), 2)
            + ':' + this.leftpad(date.getSeconds(), 2);
}

leftpad(val, resultLength = 2, leftpadChar = '0'): string {
  return (String(leftpadChar).repeat(resultLength)
        + String(val)).slice(String(val).length);
}

For current time stamp use like this:

const curTime = this.dateAsYYYYMMDDHHNNSS(new Date());
console.log(curTime);

Will output e.g: 2018-12-31 23:00:01

Android Studio was unable to find a valid Jvm (Related to MAC OS)

Do not edit the plist. These instructions worked for me the first time I installed Android Studio a few months ago as well as just today. (1/21/2015)

All you need to do is a few simple things, although they aren't really listed on Google's website.

  1. First you need Java installed. this is not the JDK, it is seperate. You can get that from this link. If you don't have this it will probably throw an error saying something like "no JVM installed."
  2. Second you need the Java JDK, I got JDK 7 from this link. Make sure to choose the Mac OS X link under the Java SE Development Kit 7u75 heading. If you don't have this it will probably throw an error saying something like "no JDK installed."
  3. If you haven't already installed Android Studio, do that. But I'm sure you've already done that by now.

Difference between JPanel, JFrame, JComponent, and JApplet

JFrame and JApplet are top level containers. If you wish to create a desktop application, you will use JFrame and if you plan to host your application in browser you will use JApplet.

JComponent is an abstract class for all Swing components and you can use it as the base class for your new component. JPanel is a simple usable component you can use for almost anything.

Since this is for a fun project, the simplest way for you is to work with JPanel and then host it inside JFrame or JApplet. Netbeans has a visual designer for Swing with simple examples.

npm ERR! network getaddrinfo ENOTFOUND

First I check whether proxy is set for me or not using this :

npm config get proxy

It returned null then I run this command

npm config set strict-ssl=false

It disable strict-ssl for that cmd session.

You can see complete list of config using this

npm config list ls -l

Unable to resolve dependency for ':app@debug/compileClasspath': Could not resolve

I think the problems comes from the following: The internet connection with u was unavailable so Android Studio asked you to enable the "offline work" and you just enabled it

To fix this:

  • File
  • Settings
  • Build, Execution, Deployment
  • Gradle
  • Uncheck offline work

why might unchecking the offline work solves the problem, because in the Gradle sometimes some dependencies need to update (the ones containing '+'), so internet connection is needed.

How to uncheck checked radio button

try this

_x000D_
_x000D_
var radio_button=false;_x000D_
$('.radio-button').on("click", function(event){_x000D_
  var this_input=$(this);_x000D_
  if(this_input.attr('checked1')=='11') {_x000D_
    this_input.attr('checked1','11')_x000D_
  } else {_x000D_
    this_input.attr('checked1','22')_x000D_
  }_x000D_
  $('.radio-button').prop('checked', false);_x000D_
  if(this_input.attr('checked1')=='11') {_x000D_
    this_input.prop('checked', false);_x000D_
    this_input.attr('checked1','22')_x000D_
  } else {_x000D_
    this_input.prop('checked', true);_x000D_
    this_input.attr('checked1','11')_x000D_
  }_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>_x000D_
<input type='radio' class='radio-button' name='re'>_x000D_
<input type='radio' class='radio-button' name='re'>_x000D_
<input type='radio' class='radio-button' name='re'>
_x000D_
_x000D_
_x000D_

Sprintf equivalent in Java

Since Java 13 you have formatted 1 method on String, which was added along with text blocks as a preview feature 2. You can use it instead of String.format()

Assertions.assertEquals(
   "%s %d %.3f".formatted("foo", 123, 7.89),
   "foo 123 7.890"
);

Visualizing branch topology in Git

I have this git log alias in ~/.gitconfig to view the graph history:

[alias]
l = log --all --graph --pretty=format:'%C(auto)%h%C(auto)%d %s %C(dim white)(%aN, %ar)'

With the alias in place, git l will show something like this:

enter image description here

In Git 2.12+ you can even customize the line colors of the graph using the log.graphColors configuration option.

As for the logs' format, it's similar to --oneline, with the addition of the author name (respecting .mailmap) and the relative author date. Note that the %C(auto) syntax, which tells Git to use the default colors for commit hash, etc. is supported in Git >= 1.8.3.

Merge 2 arrays of objects

const array1 = [{id:1,name:'ganza'},
{id:2,name:'respice dddd'},{id:4,name:'respice dddd'},{id:6,name:'respice dddd'},
{id:7,name:'respice dddd'}];
const array2 = [{id:1,name:'ganza respice'},{id:2,name:'respice'},{id:3,name:'mg'}];

 function mergeTwoArray(array1,array2){

    return array1.map((item,i)=>{
        if(array2[i] && item.id===array2[i].id){
          return array2[i];
          }else{
            return item;
          }
    });
  }

const result = merge(array1,array2);
console.log(result);
//here is the result:  Array [Object { id: 1, name: "ganza respice" }, Object { id: 2, name: "respice" }, Object { id: 4, name: "respice dddd" }, Object { id: 6, name: "respice dddd" }, Object { id: 7, name: "respice dddd" }]

When do I need to use AtomicBoolean in Java?

When multiple threads need to check and change the boolean. For example:

if (!initialized) {
   initialize();
   initialized = true;
}

This is not thread-safe. You can fix it by using AtomicBoolean:

if (atomicInitialized.compareAndSet(false, true)) {
    initialize();
}

How to get IntPtr from byte[] in C#

In some cases you can use an Int32 type (or Int64) in case of the IntPtr. If you can, another useful class is BitConverter. For what you want you could use BitConverter.ToInt32 for example.

Nginx serves .php files as downloads, instead of executing them

for a record, I found that my php-fpm was not running and I fixed it with service php7.2-fpm stop

How to use Google fonts in React.js?

you should see this tutorial: https://scotch.io/@micwanyoike/how-to-add-fonts-to-a-react-project

import WebFont from 'webfontloader';

WebFont.load({
  google: {
    families: ['Titillium Web:300,400,700', 'sans-serif']
  }
});

I just tried this method and I can say that it works very well ;)

Python 2: AttributeError: 'list' object has no attribute 'strip'

Hope this helps :)

>>> x = [i.split(";") for i in l]
>>> x
[['Facebook', 'Google+', 'MySpace'], ['Apple', 'Android']]
>>> z = [j for i in x for j in i]
>>> z
['Facebook', 'Google+', 'MySpace', 'Apple', 'Android']
>>> 

Trim string in JavaScript?

Trim code from angular js project

var trim = (function() {

  // if a reference is a `String`.
  function isString(value){
       return typeof value == 'string';
  } 

  // native trim is way faster: http://jsperf.com/angular-trim-test
  // but IE doesn't have it... :-(
  // TODO: we should move this into IE/ES5 polyfill

  if (!String.prototype.trim) {
    return function(value) {
      return isString(value) ? 
         value.replace(/^\s*/, '').replace(/\s*$/, '') : value;
    };
  }

  return function(value) {
    return isString(value) ? value.trim() : value;
  };

})();

and call it as trim(" hello ")

python list in sql query as parameter

For example, if you want the sql query:

select name from studens where id in (1, 5, 8)

What about:

my_list = [1, 5, 8]
cur.execute("select name from studens where id in %s" % repr(my_list).replace('[','(').replace(']',')') )

Oracle error : ORA-00905: Missing keyword

If you backup a table in Oracle Database. You try the statement below.

CREATE TABLE name_table_bk
AS
SELECT *
  FROM name_table;

I am using Oracle Database 12c.

How do you set the title color for the new Toolbar?

Very simple, this worked for me (title and icon white):

    <android.support.v7.widget.Toolbar
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="56dp"
    android:background="@color/PrimaryColor"
    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
    app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
    android:elevation="4dp" />

How to set up Automapper in ASP.NET Core

services.AddAutoMapper(); didn't work for me. (I am using Asp.Net Core 2.0)

After configuring as below

   var config = new AutoMapper.MapperConfiguration(cfg =>
   {                 
       cfg.CreateMap<ClientCustomer, Models.Customer>();
   });

initialize the mapper IMapper mapper = config.CreateMapper();

and add the mapper object to services as a singleton services.AddSingleton(mapper);

this way I am able to add a DI to controller

  private IMapper autoMapper = null;

  public VerifyController(IMapper mapper)
  {              
   autoMapper = mapper;  
  }

and I have used as below in my action methods

  ClientCustomer customerObj = autoMapper.Map<ClientCustomer>(customer);

grep using a character vector with multiple patterns

Not sure whether this answer has already appeared...

For the particular pattern in the question, you can just do it with a single grep() call,

grep("A[169]", myfile$Letter)

How can I force input to uppercase in an ASP.NET textbox?

JavaScript has the "toUpperCase()" function of a string.

So, something along these lines:

function makeUpperCase(this)
{
    this.value = this.value.toUpperCase();
}

Display date in dd/mm/yyyy format in vb.net

Dim formattedDate As String = Date.Today.ToString("dd/MM/yyyy")

Check link below

How to create a numpy array of all True or all False?

numpy already allows the creation of arrays of all ones or all zeros very easily:

e.g. numpy.ones((2, 2)) or numpy.zeros((2, 2))

Since True and False are represented in Python as 1 and 0, respectively, we have only to specify this array should be boolean using the optional dtype parameter and we are done.

numpy.ones((2, 2), dtype=bool)

returns:

array([[ True,  True],
       [ True,  True]], dtype=bool)

UPDATE: 30 October 2013

Since numpy version 1.8, we can use full to achieve the same result with syntax that more clearly shows our intent (as fmonegaglia points out):

numpy.full((2, 2), True, dtype=bool)

UPDATE: 16 January 2017

Since at least numpy version 1.12, full automatically casts results to the dtype of the second parameter, so we can just write:

numpy.full((2, 2), True)

Failed to execute removeChild on Node

Your myCoolDiv element isn't a child of the player container. It's a child of the div you created as a wrapper for it (markerDiv in the first part of the code). Which is why it fails, removeChild only removes children, not descendants.

You'd want to remove that wrapper div, or not add it at all.

Here's the "not adding it at all" option:

_x000D_
_x000D_
var markerDiv = document.createElement("div");_x000D_
markerDiv.innerHTML = "<div id='MyCoolDiv' style='color: #2b0808'>123</div>";_x000D_
document.getElementById("playerContainer").appendChild(markerDiv.firstChild);_x000D_
// -------------------------------------------------------------^^^^^^^^^^^_x000D_
_x000D_
setTimeout(function(){ _x000D_
    var myCoolDiv = document.getElementById("MyCoolDiv");_x000D_
    document.getElementById("playerContainer").removeChild(myCoolDiv);_x000D_
}, 1500);
_x000D_
<div id="playerContainer"></div>
_x000D_
_x000D_
_x000D_

Or without using the wrapper (although it's quite handy for parsing that HTML):

_x000D_
_x000D_
var myCoolDiv = document.createElement("div");_x000D_
// Don't reall need this: myCoolDiv.id = "MyCoolDiv";_x000D_
myCoolDiv.style.color = "#2b0808";_x000D_
myCoolDiv.appendChild(_x000D_
  document.createTextNode("123")_x000D_
);_x000D_
document.getElementById("playerContainer").appendChild(myCoolDiv);_x000D_
_x000D_
setTimeout(function(){ _x000D_
    // No need for this, we already have it from the above:_x000D_
    // var myCoolDiv = document.getElementById("MyCoolDiv");_x000D_
    document.getElementById("playerContainer").removeChild(myCoolDiv);_x000D_
}, 1500);
_x000D_
<div id="playerContainer"></div>
_x000D_
_x000D_
_x000D_

laravel Eloquent ORM delete() method

Before delete , there are several methods in laravel.

User::find(1) and User::first() return an instance.

User::where('id',1)->get and User::all() return a collection of instance.

call delete on an model instance will returns true/false

$user=User::find(1);
$user->delete(); //returns true/false

call delete on a collection of instance will returns a number which represents the number of the records had been deleted

//assume you have 10 users, id from 1 to 10;
$result=User::where('id','<',11)->delete(); //returns 11 (the number of the records had been deleted)

//lets call delete again
$result2=User::where('id','<',11)->delete(); //returns 0 (we have already delete the id<11 users, so this time we delete nothing, the result should be the number of the records had been deleted(0)  ) 

Also there are other delete methods, you can call destroy as a model static method like below

$result=User::destroy(1,2,3);
$result=User::destroy([1,2,3]);
$result=User::destroy(collect([1, 2, 3]));
//these 3 statement do the same thing, delete id =1,2,3 users, returns the number of the records had been deleted

One more thing ,if you are new to laravel ,you can use php artisan tinker to see the result, which is more efficient and then dd($result) , print_r($result);

Ruby convert Object to Hash

class Gift
  def initialize
    @name = "book"
    @price = 15.95
  end
end

gift = Gift.new
hash = {}
gift.instance_variables.each {|var| hash[var.to_s.delete("@")] = gift.instance_variable_get(var) }
p hash # => {"name"=>"book", "price"=>15.95}

Alternatively with each_with_object:

gift = Gift.new
hash = gift.instance_variables.each_with_object({}) { |var, hash| hash[var.to_s.delete("@")] = gift.instance_variable_get(var) }
p hash # => {"name"=>"book", "price"=>15.95}

Strange PostgreSQL "value too long for type character varying(500)"

We had this same issue. We solved it adding 'length' to entity attribute definition:

@Column(columnDefinition="text", length=10485760)
private String configFileXml = ""; 

Why do we use __init__ in Python classes?

Classes are objects with attributes (state, characteristic) and methods (functions, capacities) that are specific for that object (like the white color and fly powers, respectively, for a duck).

When you create an instance of a class, you can give it some initial personality (state or character like the name and the color of her dress for a newborn). You do this with __init__.

Basically __init__ sets the instance characteristics automatically when you call instance = MyClass(some_individual_traits).

How to Publish Web with msbuild?

Using the deployment profiles introduced in VS 2012, you can publish with the following command line:

msbuild MyProject.csproj /p:DeployOnBuild=true /p:PublishProfile=<profile-name> /p:Password=<insert-password> /p:VisualStudioVersion=11.0

For more information on the parameters see this.

The values for the /p:VisualStudioVersion parameter depend on your version of Visual Studio. Wikipedia has a table of Visual Studio releases and their versions.

Does Arduino use C or C++?

Arduino doesn't run either C or C++. It runs machine code compiled from either C, C++ or any other language that has a compiler for the Arduino instruction set.

C being a subset of C++, if Arduino can "run" C++ then it can "run" C.

If you don't already know C nor C++, you should probably start with C, just to get used to the whole "pointer" thing. You'll lose all the object inheritance capabilities though.

how to realize countifs function (excel) in R

library(matrixStats)
> data <- rbind(c("M", "F", "M"), c("Student", "Analyst", "Analyst"))
> rowCounts(data, value = 'M') # output = 2 0
> rowCounts(data, value = 'F') # output = 1 0

ascending/descending in LINQ - can one change the order via parameter?

You can easily create your own extension method on IEnumerable or IQueryable:

public static IOrderedEnumerable<TSource> OrderByWithDirection<TSource,TKey>
    (this IEnumerable<TSource> source,
     Func<TSource, TKey> keySelector,
     bool descending)
{
    return descending ? source.OrderByDescending(keySelector)
                      : source.OrderBy(keySelector);
}

public static IOrderedQueryable<TSource> OrderByWithDirection<TSource,TKey>
    (this IQueryable<TSource> source,
     Expression<Func<TSource, TKey>> keySelector,
     bool descending)
{
    return descending ? source.OrderByDescending(keySelector)
                      : source.OrderBy(keySelector);
}

Yes, you lose the ability to use a query expression here - but frankly I don't think you're actually benefiting from a query expression anyway in this case. Query expressions are great for complex things, but if you're only doing a single operation it's simpler to just put that one operation:

var query = dataList.OrderByWithDirection(x => x.Property, direction);

How to debug a bash script?

Use eclipse with the plugins shelled & basheclipse.

https://sourceforge.net/projects/shelled/?source=directory https://sourceforge.net/projects/basheclipse/?source=directory

For shelled: Download the zip and import it into eclipse via help -> install new software : local archive For basheclipse: Copy the jars into dropins directory of eclipse

Follow the steps provides https://sourceforge.net/projects/basheclipse/files/?source=navbar

enter image description here

I wrote a tutorial with many screenshots at http://dietrichschroff.blogspot.de/2017/07/bash-enabling-eclipse-for-bash.html

How to sort alphabetically while ignoring case sensitive?

did you tried converting the first char of the string to lowercase on if(fruits[i].charAt(0) == currChar) and char currChar = fruits[0].charAt(0) statements?

What is the difference between public, private, and protected?

Reviving an old question, but I think a really good way to think of this is in terms of the API that you are defining.

  • public - Everything marked public is part of the API that anyone using your class/interface/other will use and rely on.

  • protected - Don't be fooled, this is also part of the API! People can subclass, extend your code and use anything marked protected.

  • private - Private properties and methods can be changed as much as you like. No one else can use these. These are the only things you can change without making breaking changes.

Or in Semver terms:

  • Changes to anything public or protected should be considered MAJOR changes.

  • Anything new public or protected should be (at least) MINOR

  • Only new/changes to anything private can be PATCH

So in terms of maintaining code, its good to be careful about what things you make public or protected because these are the things you are promising to your users.

Exception in thread "main" java.lang.OutOfMemoryError: Java heap space

Well, it's fairly self-explanatory: you've run out of memory.

You may want to try starting it with more memory, using the -Xmx flag, e.g.

java -Xmx2048m [whatever you'd have written before]

This will use up to 2 gigs of memory.

See the non-standard options list for more details.

Remove all stylings (border, glow) from textarea

If you want to remove EVERYTHING :

textarea {
    border: none;
    background-color: transparent;
    resize: none;
    outline: none;
}

Changing MongoDB data store directory

The following command will work for you, if you want to change default path. Just type this in bin directory of mongodb.

mongod --dbpath=yourdirectory\data\db

In case you want to move existing data too, then just copy all the folders from existing data\db directory to new directory before you execute the command.

And also stop existing mongodb services which are running.

Regex doesn't work in String.matches()

Your regular expression [a-z] doesn't match dkoe since it only matches Strings of lenght 1. Use something like [a-z]+.

Global and local variables in R

Variables declared inside a function are local to that function. For instance:

foo <- function() {
    bar <- 1
}
foo()
bar

gives the following error: Error: object 'bar' not found.

If you want to make bar a global variable, you should do:

foo <- function() {
    bar <<- 1
}
foo()
bar

In this case bar is accessible from outside the function.

However, unlike C, C++ or many other languages, brackets do not determine the scope of variables. For instance, in the following code snippet:

if (x > 10) {
    y <- 0
}
else {
    y <- 1
}

y remains accessible after the if-else statement.

As you well say, you can also create nested environments. You can have a look at these two links for understanding how to use them:

  1. http://stat.ethz.ch/R-manual/R-devel/library/base/html/environment.html
  2. http://stat.ethz.ch/R-manual/R-devel/library/base/html/get.html

Here you have a small example:

test.env <- new.env()

assign('var', 100, envir=test.env)
# or simply
test.env$var <- 100

get('var') # var cannot be found since it is not defined in this environment
get('var', envir=test.env) # now it can be found

BULK INSERT with identity (auto-increment) column

You have to do bulk insert with format file:

   BULK INSERT Employee FROM 'path\tempFile.csv ' 
   WITH (FORMATFILE = 'path\tempFile.fmt');

where format file (tempFile.fmt) looks like this:

11.0
2
1 SQLCHAR 0 50 "\t"  2  Name   SQL_Latin1_General_CP1_CI_AS
2 SQLCHAR 0 50 "\r\n" 3  Address  SQL_Latin1_General_CP1_CI_AS

more details here - http://msdn.microsoft.com/en-us/library/ms179250.aspx

Correct way to use Modernizr to detect IE?

I agree we should test for capabilities, but it's hard to find a simple answer to "what capabilities are supported by 'modern browsers' but not 'old browsers'?"

So I fired up a bunch of browsers and inspected Modernizer directly. I added a few capabilities I definitely require, and then I added "inputtypes.color" because that seems to cover all the major browsers I care about: Chrome, Firefox, Opera, Edge...and NOT IE11. Now I can gently suggest the user would be better off with Chrome/Opera/Firefox/Edge.

This is what I use - you can edit the list of things to test for your particular case. Returns false if any of the capabilities are missing.

/**
 * Check browser capabilities.
 */
public CheckBrowser(): boolean
{
    let tests = ["csstransforms3d", "canvas", "flexbox", "webgl", "inputtypes.color"];

    // Lets see what each browser can do and compare...
    //console.log("Modernizr", Modernizr);

    for (let i = 0; i < tests.length; i++)
    {
        // if you don't test for nested properties then you can just use
        // "if (!Modernizr[tests[i]])" instead
        if (!ObjectUtils.GetProperty(Modernizr, tests[i]))
        {
            console.error("Browser Capability missing: " + tests[i]);
            return false;
        }
    }

    return true;
}

And here is that GetProperty method which is needed for "inputtypes.color".

/**
 * Get a property value from the target object specified by name.
 * 
 * The property name may be a nested property, e.g. "Contact.Address.Code".
 * 
 * Returns undefined if a property is undefined (an existing property could be null).
 * If the property exists and has the value undefined then good luck with that.
 */
public static GetProperty(target: any, propertyName: string): any
{
    if (!(target && propertyName))
    {
        return undefined;
    }

    var o = target;

    propertyName = propertyName.replace(/\[(\w+)\]/g, ".$1");
    propertyName = propertyName.replace(/^\./, "");

    var a = propertyName.split(".");

    while (a.length)
    {
        var n = a.shift();

        if (n in o)
        {
            o = o[n];

            if (o == null)
            {
                return undefined;
            }
        }
        else
        {
            return undefined;
        }
    }

    return o;
}

How to initialize a vector of vectors on a struct?

Like this:

#include <vector>

// ...

std::vector<std::vector<int>> A(dimension, std::vector<int>(dimension));

(Pre-C++11 you need to leave whitespace between the angled brackets.)

git rebase: "error: cannot stat 'file': Permission denied"

Same issue on Windows 10 64 Bit, running Git Bash version 2.9.0.windows1 Using Atom as my editor.

This worked for me: I added the Git software folder (for me, this was C:\Program Files\Git) to the exclusions for Windows Defender.

After the exclusion was added, git checkout 'file' worked fine.

How to Deserialize XML document

try this block of code if your .xml file has been generated somewhere in disk and if you have used List<T>:

//deserialization

XmlSerializer xmlser = new XmlSerializer(typeof(List<Item>));
StreamReader srdr = new StreamReader(@"C:\serialize.xml");
List<Item> p = (List<Item>)xmlser.Deserialize(srdr);
srdr.Close();`

Note: C:\serialize.xml is my .xml file's path. You can change it for your needs.

Error:(9, 5) error: resource android:attr/dialogCornerRadius not found

Found a neat plugin to solve this: cordova-android-support-gradle-release

cordova plugin add cordova-android-support-gradle-release --variable ANDROID_SUPPORT_VERSION=27.+ --save

Accessing MP3 metadata with Python

It can depend on exactly what you want to do in addition to reading the metadata. If it is just simply the bitrate / name etc. that you need, and nothing else, something lightweight is probably best.

If you're manipulating the mp3 past that PyMedia may be suitable.

There are quite a few, whatever you do get, make sure and test it out on plenty of sample media. There are a few different versions of ID3 tags in particular, so make sure it's not too out of date.

Personally I've used this small MP3Info class with luck. It is quite old though.

http://www.omniscia.org/~vivake/python/MP3Info.py

How to add row in JTable?

For the sake of completeness, first make sure you have the correct import so you can use the addRow function:

import javax.swing.table.*;

Assuming your jTable is already created, you can proceed and create your own add row method which will accept the parameters that you need:

public void yourAddRow(String str1, String str2, String str3){
  DefaultTableModel yourModel = (DefaultTableModel) yourJTable.getModel();
  yourModel.addRow(new Object[]{str1, str2, str3});
}

How to convert a data frame column to numeric type?

if x is the column name of dataframe dat, and x is of type factor, use:

as.numeric(as.character(dat$x))

Sass Variable in CSS calc() function

Try this:

@mixin heightBox($body_padding){
   height: calc(100% - $body_padding);
}

body{
   @include heightBox(100% - 25%);
   box-sizing: border-box
   padding:10px;
}

How do you add PostgreSQL Driver as a dependency in Maven?

Updating for latest release:

<dependency>
    <groupId>org.postgresql</groupId>
    <artifactId>postgresql</artifactId>
    <version>42.2.14</version>
</dependency>

Source

Hope it helps!

Is it possible to make abstract classes in Python?

Most Previous answers were correct but here is the answer and example for Python 3.7. Yes, you can create an abstract class and method. Just as a reminder sometimes a class should define a method which logically belongs to a class, but that class cannot specify how to implement the method. For example, in the below Parents and Babies classes they both eat but the implementation will be different for each because babies and parents eat a different kind of food and the number of times they eat is different. So, eat method subclasses overrides AbstractClass.eat.

from abc import ABC, abstractmethod

class AbstractClass(ABC):

    def __init__(self, value):
        self.value = value
        super().__init__()

    @abstractmethod
    def eat(self):
        pass

class Parents(AbstractClass):
    def eat(self):
        return "eat solid food "+ str(self.value) + " times each day"

class Babies(AbstractClass):
    def eat(self):
        return "Milk only "+ str(self.value) + " times or more each day"

food = 3    
mom = Parents(food)
print("moms ----------")
print(mom.eat())

infant = Babies(food)
print("infants ----------")
print(infant.eat())

OUTPUT:

moms ----------
eat solid food 3 times each day
infants ----------
Milk only 3 times or more each day

How to Sort Date in descending order From Arraylist Date in android?

Create Arraylist<Date> of Date class. And use Collections.sort() for ascending order.

See sort(List<T> list)

Sorts the specified list into ascending order, according to the natural ordering of its elements.

For Sort it in descending order See Collections.reverseOrder()

Collections.sort(yourList, Collections.reverseOrder());

Sending data through POST request from a node.js server to a node.js server

Posting data is a matter of sending a query string (just like the way you would send it with an URL after the ?) as the request body.

This requires Content-Type and Content-Length headers, so the receiving server knows how to interpret the incoming data. (*)

var querystring = require('querystring');
var http = require('http');

var data = querystring.stringify({
      username: yourUsernameValue,
      password: yourPasswordValue
    });

var options = {
    host: 'my.url',
    port: 80,
    path: '/login',
    method: 'POST',
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Content-Length': Buffer.byteLength(data)
    }
};

var req = http.request(options, function(res) {
    res.setEncoding('utf8');
    res.on('data', function (chunk) {
        console.log("body: " + chunk);
    });
});

req.write(data);
req.end();

(*) Sending data requires the Content-Type header to be set correctly, i.e. application/x-www-form-urlencoded for the traditional format that a standard HTML form would use.

It's easy to send JSON (application/json) in exactly the same manner; just JSON.stringify() the data beforehand.

URL-encoded data supports one level of structure (i.e. key and value). JSON is useful when it comes to exchanging data that has a nested structure.

The bottom line is: The server must be able to interpret the content type in question. It could be text/plain or anything else; there is no need to convert data if the receiving server understands it as it is.

Add a charset parameter (e.g. application/json; charset=Windows-1252) if your data is in an unusual character set, i.e. not UTF-8. This can be necessary if you read it from a file, for example.

Jboss server error : Failed to start service jboss.deployment.unit."jbpm-console.war"

Best solution: Goto jboss-as-7.1.1.Final\standalone\deployments folder and delete all existing files....

Run again your problem will be solved

ImportError: DLL load failed: %1 is not a valid Win32 application

I just hit this and the problem was that the package had at one point been installed in the per-user packages directory. (On Windows.) aka %AppData%\Python. So Python was looking there first, finding an old 32-bit version of the .pyd file, and failing with the listed error. Unfortunately pip uninstall by itself wasn't enough to clean this, and at this time pip 10.0.1 doesn't seem to have a --user parameter for uninstall, only for install.

tl;dr Deleting the old .pyd from %AppData%\python\python27\site-packages resolved this problem for me.

Referring to a Column Alias in a WHERE Clause

How about using a subquery(this worked for me in Mysql)?

SELECT * from (SELECT logcount, logUserID, maxlogtm
   , DATEDIFF(day, maxlogtm, GETDATE()) AS daysdiff
FROM statslogsummary) as 'your_alias'
WHERE daysdiff > 120

What are the differences between WCF and ASMX web services?

WCF completely replaces ASMX web services. ASMX is the old way to do web services and WCF is the current way to do web services. All new SOAP web service development, on the client or the server, should be done using WCF.

How to compare type of an object in Python?

Type doesn't work on certain classes. If you're not sure of the object's type use the __class__ method, as so:

>>>obj = 'a string'
>>>obj.__class__ == str
True

Also see this article - http://www.siafoo.net/article/56

How to escape comma and double quote at same time for CSV file?

You could also look at how Python writes Excel-compatible csv files.

I believe the default for Excel is to double-up for literal quote characters - that is, literal quotes " are written as "".

Get Time from Getdate()

You will be able to get the time using below query:

select left((convert(time(0), GETDATE ())),5)

Make cross-domain ajax JSONP request with jQuery

Try

alert(xml.Data[0].City)

Case sensitivly!

nginx- duplicate default server error

If you're on Digital Ocean this means you need to go to /etc/nginx/sites-enabled/ and then REMOVE using rm -R digitalocean and default

It fixed it for me!

Pic of Console on Windows 10 using Bitvise

Auto-increment primary key in SQL tables

I think there is a way to do it at definition stage like this

create table employee( id int identity, name varchar(50), primary key(id) ).. I am trying to see if there is a way to alter an existing table and make the column as Identity which does not look possible theoretically (as the existing values might need modification)

java.io.FileNotFoundException: the system cannot find the file specified

Put the word.txt directly as a child of the project root folder and a peer of src

Project_Root
    src
    word.txt

Disclaimer: I'd like to explain why this works for this particular case and why it may not work for others.

Why it works:

When you use File or any of the other FileXxx variants, you are looking for a file on the file system relative to the "working directory". The working directory, can be described as this:

When you run from the command line

C:\EclipseWorkspace\ProjectRoot\bin > java com.mypackage.Hangman1

the working directory is C:\EclipseWorkspace\ProjectRoot\bin. With your IDE (at least all the ones I've worked with), the working directory is the ProjectRoot. So when the file is in the ProjectRoot, then using just the file name as the relative path is valid, because it is at the root of the working directory.

Similarly, if this was your project structure ProjectRoot\src\word.txt, then the path "src/word.txt" would be valid.

Why it May not Work

For one, the working directory could always change. For instance, running the code from the command line like in the example above, the working directory is the bin. So in this case it will fail, as there is not bin\word.txt

Secondly, if you were to export this project into a jar, and the file was configured to be included in the jar, it would also fail, as the path will no longer be valid either.

That being said, you need to determine if the file is to be an (or just "resource" - terms which sometimes I'll use interchangeably). If so, then you will want to build the file into the classpath, and access it via an URL. First thing you would need to do (in this particular) case is make sure that the file get built into the classpath. With the file in the project root, you must configure the build to include the file. But if you put the file in the src or in some directory below, then the default build should put it into the class path.

You can access classpath resource in a number of ways. You can make use of the Class class, which has getResourceXxx method, from which you use to obtain classpath resources.

For example, if you changed your project structure to ProjectRoot\src\resources\word.txt, you could use this:

InputStream is = Hangman1.class.getResourceAsStream("/resources/word.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(is));

getResourceAsStream returns an InputStream, but obtains an URL under the hood. Alternatively, you could get an URL if that's what you need. getResource() will return an URL

For Maven users, where the directory structure is like src/main/resources, the contents of the resources folder is put at the root of the classpath. So if you have a file in there, then you would only use getResourceAsStream("/thefile.txt")

Render HTML to an image

The only library that I got to work for Chrome, Firefox and MS Edge was rasterizeHTML. It outputs better quality that HTML2Canvas and is still supported unlike HTML2Canvas.

Getting Element and Downloading as PNG

var node= document.getElementById("elementId");
var canvas = document.createElement("canvas");
canvas.height = node.offsetHeight;
canvas.width = node.offsetWidth;
var name = "test.png"

rasterizeHTML.drawHTML(node.outerHTML, canvas)
     .then(function (renderResult) {
            if (navigator.msSaveBlob) {
                window.navigator.msSaveBlob(canvas.msToBlob(), name);
            } else {
                const a = document.createElement("a");
                document.body.appendChild(a);
                a.style = "display: none";
                a.href = canvas.toDataURL();
                a.download = name;
                a.click();
                document.body.removeChild(a);
            }
     });

Android splash screen image sizes to fit all devices

Some time ago i created an excel file with supported dimensions
Hope this will be helpful for somebody

To be honest i lost the idea, but it refers another screen feature as size (not only density)
https://developer.android.com/guide/practices/screens_support.html
Please inform me if there are some mistakes

Link1: dimensions.xlsx

Link2: dimensions.xlsx

Excel CSV - Number cell format

There isn’t an easy way to control the formatting Excel applies when opening a .csv file. However listed below are three approaches that might help.

My preference is the first option.

Option 1 – Change the data in the file

You could change the data in the .csv file as follows ...,=”005”,... This will be displayed in Excel as ...,005,...

Excel will have kept the data as a formula, but copying the column and using paste special values will get rid of the formula but retain the formatting

Option 2 – Format the data

If it is simply a format issue and all your data in that column has a three digits length. Then open the data in Excel and then format the column containing the data with this custom format 000

Option 3 – Change the file extension to .dif (Data interchange format)

Change the file extension and use the file import wizard to control the formats. Files with a .dif extension are automatically opened by Excel when double clicked on.

Step by step:

  • Change the file extension from .csv to .dif
  • Double click on the file to open it in Excel.
  • The 'File Import Wizard' will be launched.
  • Set the 'File type' to 'Delimited' and click on the 'Next' button.
  • Under Delimiters, tick 'Comma' and click on the 'Next' button.
  • Click on each column of your data that is displayed and select a 'Column data format'. The column with the value '005' should be formatted as 'Text'.
  • Click on the finish button, the file will be opened by Excel with the formats that you have specified.

Command /usr/bin/codesign failed with exit code 1

What worked for me was to realize that Xcode did not have access to the certificates. Please check that your certs are accessible by Xcode. Go to Keychain Access -> Certificates -> Open the Cert and double click on the private key -> Select Access Control

enter image description here

How to get just numeric part of CSS property with jQuery?

parseFloat($(this).css('marginBottom'))

Even if marginBottom defined in em, the value inside of parseFloat above will be in px, as it's a calculated CSS property.

How do I write a custom init for a UIView subclass in Swift?

I create a common init for the designated and required. For convenience inits I delegate to init(frame:) with frame of zero.

Having zero frame is not a problem because typically the view is inside a ViewController's view; your custom view will get a good, safe chance to layout its subviews when its superview calls layoutSubviews() or updateConstraints(). These two functions are called by the system recursively throughout the view hierarchy. You can use either updateContstraints() or layoutSubviews(). updateContstraints() is called first, then layoutSubviews(). In updateConstraints() make sure to call super last. In layoutSubviews(), call super first.

Here's what I do:

@IBDesignable
class MyView: UIView {

      convenience init(args: Whatever) {
          self.init(frame: CGRect.zero)
          //assign custom vars
      }

      override init(frame: CGRect) {
           super.init(frame: frame)
           commonInit()
      }

      required init?(coder aDecoder: NSCoder) {
           super.init(coder: aDecoder)
           commonInit()
      }

      override func prepareForInterfaceBuilder() {
           super.prepareForInterfaceBuilder()
           commonInit()
      }

      private func commonInit() {
           //custom initialization
      }

      override func updateConstraints() {
           //set subview constraints here
           super.updateConstraints()
      }

      override func layoutSubviews() {
           super.layoutSubviews()
           //manually set subview frames here
      }

}

ASP.NET Core Identity - get current user

Just if any one is interested this worked for me. I have a custom Identity which uses int for a primary key so I overrode the GetUserAsync method

Override GetUserAsync

public override Task<User> GetUserAsync(ClaimsPrincipal principal)
{
    var userId = GetUserId(principal);
    return FindByNameAsync(userId);
}

Get Identity User

var user = await _userManager.GetUserAsync(User);

If you are using a regular Guid primary key you don't need to override GetUserAsync. This is all assuming that you token is configured correctly.

public async Task<string> GenerateTokenAsync(string email)
{
    var user = await _userManager.FindByEmailAsync(email);
    var tokenHandler = new JwtSecurityTokenHandler();
    var key = Encoding.ASCII.GetBytes(_tokenProviderOptions.SecretKey);

    var userRoles = await _userManager.GetRolesAsync(user);
    var roles = userRoles.Select(o => new Claim(ClaimTypes.Role, o));

    var claims = new[]
    {
        new Claim(JwtRegisteredClaimNames.Sub, user.UserName),
        new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
        new Claim(JwtRegisteredClaimNames.Iat, DateTime.UtcNow.ToString(CultureInfo.CurrentCulture)),
        new Claim(JwtRegisteredClaimNames.GivenName, user.FirstName),
        new Claim(JwtRegisteredClaimNames.FamilyName, user.LastName),
        new Claim(JwtRegisteredClaimNames.Email, user.Email),
    }
    .Union(roles);

    var tokenDescriptor = new SecurityTokenDescriptor
    {
        Subject = new ClaimsIdentity(claims),
        Expires = DateTime.UtcNow.AddHours(_tokenProviderOptions.Expires),
        SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
    };

    var token = tokenHandler.CreateToken(tokenDescriptor);

    return Task.FromResult(new JwtSecurityTokenHandler().WriteToken(token)).Result;
}

What's the difference between "Solutions Architect" and "Applications Architect"?

Update 1/5/2018 - over the last 9 years, my thinking has evolved considerably on this topic. I tend to live a little closer to the bleeding edge in our industry than the majority (though certainly not pushing the boundaries nearly as much as a lot of really smart people out there). I've been an architect at varying levels from application, to solution, to enterprise, at multiple companies large and small. I've come to the conclusion that the future in our technology industry is one mostly without architects. If this sounds crazy to you, wait a few years and your company will probably catch up, or your competitors who figure it out will catch up with (and pass) you. The fundamental problem is that "architecture" is nothing more or less than the sum of all the decisions that have been made about your application/solution/portfolio. So the title "architect" really means "decider". That says a lot, also by what it doesn't say. It doesn't say "builder". Creating a career path / hierarchy that implicitly tells people "building" is lower than "deciding", and "deciders" are not directly responsible (by the difference in title) for "building". People who are still hanging on to their architect title will chafe at this and protest "but I am hands-on!" Great, if you're just a builder then give up your meaningless title and stop setting yourself apart from the other builders. Companies that emphasize "all builders are deciders, and all deciders are builders" will move faster than their competitors. We use the title "engineer" for everyone, and "engineer" means deciding and building.

Original answer:

For people who have never worked in a very large organization (or have, but it was a dysfunctional one), "architect" may have left a bad taste in their mouth. However, it is not only a legitimate role, but a highly strategic one for smart companies.

  • When an application becomes so vast and complex that dealing with the overall technical vision and planning, and translating business needs into technical strategy becomes a full-time job, that is an application architect. Application architects also often mentor and/or lead developers, and know the code of their responsible application(s) well.

  • When an organization has so many applications and infrastructure inter-dependencies that it is a full-time job to ensure their alignment and strategy without being involved in the code of any of them, that is a solution architect. Solution architect can sometimes be similar to an application architect, but over a suite of especially large applications that comprise a logical solution for a business.

  • When an organization becomes so large that it becomes a full-time job to coordinate the high-level planning for the solution architects, and frame the terms of the business technology strategy, that role is an enterprise architect. Enterprise architects typically work at an executive level, advising the CxO office and its support functions as well as the business as a whole.

There are also infrastructure architects, information architects, and a few others, but in terms of total numbers these comprise a smaller percentage than the "big three".

Note: numerous other answers have said there is "no standard" for these titles. That is not true. Go to any Fortune 1000 company's IT department and you will find these titles used consistently.

The two most common misconceptions about "architect" are:

  • An architect is simply a more senior/higher-earning developer with a fancy title
  • An architect is someone who is technically useless, hasn't coded in years but still throws around their weight in the business, making life difficult for developers

These misconceptions come from a lot of architects doing a pretty bad job, and organizations doing a terrible job at understanding what an architect is for. It is common to promote the top programmer into an architect role, but that is not right. They have some overlapping but not identical skillsets. The best programmer may often be, but is not always, an ideal architect. A good architect has a good understanding of many technical aspects of the IT industry; a better understanding of business needs and strategies than a developer needs to have; excellent communication skills and often some project management and business analysis skills. It is essential for architects to keep their hands dirty with code and to stay sharp technically. Good ones do.

How to change mysql to mysqli?

I have just created the function with the same names to convert and overwrite to the new one php7:

$host =     "your host";      
$un = "username";    
$pw = "password";       
$db = "database"; 

$MYSQLI_CONNECT = mysqli_connect($host, $un, $pw, $db);

function mysql_query($q) {
    global $MYSQLI_CONNECT;
    return mysqli_query($MYSQLI_CONNECT,$q);
}

function mysql_fetch_assoc($q) {
    return mysqli_fetch_assoc($q);
}

function mysql_fetch_array($q){
    return mysqli_fetch_array($q , MYSQLI_BOTH);
}

function mysql_num_rows($q){
    return mysqli_num_rows($q);
}

function mysql_insert_id() {
    global $MYSQLI_CONNECT;
    return mysqli_insert_id($MYSQLI_CONNECT);
}

function mysql_real_escape_string($q) {
    global $MYSQLI_CONNECT;
    return mysqli_real_escape_string($MYSQLI_CONNECT,$q);
}

It works for me , I hope it will work for you all , if I mistaken , correct me.

AngularJS : ng-click not working

It just happend to me. I solved the problem by tracing backward from the point ng-click is coded. Found out that an extra

</div> 

was placed in the html to prematurely close the div block that contains the ng-click.

Removed the extra

</div> 

then everything is working fine.

ORA-01653: unable to extend table by in tablespace ORA-06512

To resolve this error:

ORA-01653 unable to extend table by 1024 in tablespace your-tablespace-name

Just run this PL/SQL command for extended tablespace size automatically on-demand:

alter database datafile '<your-tablespace-name>.dbf' autoextend on maxsize unlimited;

I get this error in import big dump file, just run this command without stopping import routine or restarting the database.

Note: each data file has a limit of 32GB of size if you need more than 32GB you should add a new data file to your existing tablespace.

More info: alter_autoextend_on

How to remove last n characters from a string in Bash?

You can do like this:

#!/bin/bash

v="some string.rtf"

v2=${v::-4}

echo "$v --> $v2"

TypeError: int() argument must be a string, a bytes-like object or a number, not 'list'

What the error is telling, is that you can't convert an entire list into an integer. You could get an index from the list and convert that into an integer:

x = ["0", "1", "2"] 
y = int(x[0]) #accessing the zeroth element

If you're trying to convert a whole list into an integer, you are going to have to convert the list into a string first:

x = ["0", "1", "2"]
y = ''.join(x) # converting list into string
z = int(y)

If your list elements are not strings, you'll have to convert them to strings before using str.join:

x = [0, 1, 2]
y = ''.join(map(str, x))
z = int(y)

Also, as stated above, make sure that you're not returning a nested list.

Pandas concat: ValueError: Shape of passed values is blah, indices imply blah2

Try sorting index after concatenating them

result=pd.concat([df1,df2]).sort_index()

How to check all checkboxes using jQuery?

if(isAllChecked == 0)
{ 
    $("#select_all").prop("checked", true); 
}   

please change the above line to

if(isAllChecked == 0)
{ 
    $("#checkedAll").prop("checked", true); 
}   

in SSR's answer and its working perfect Thank you

java.lang.IllegalStateException: Fragment not attached to Activity

This error happens due to the combined effect of two factors:

  • The HTTP request, when complete, invokes either onResponse() or onError() (which work on the main thread) without knowing whether the Activity is still in the foreground or not. If the Activity is gone (the user navigated elsewhere), getActivity() returns null.
  • The Volley Response is expressed as an anonymous inner class, which implicitly holds a strong reference to the outer Activity class. This results in a classic memory leak.

To solve this problem, you should always do:

Activity activity = getActivity();
if(activity != null){

    // etc ...

}

and also, use isAdded() in the onError() method as well:

@Override
public void onError(VolleyError error) {

    Activity activity = getActivity(); 
    if(activity != null && isAdded())
        mProgressDialog.setVisibility(View.GONE);
        if (error instanceof NoConnectionError) {
           String errormsg = getResources().getString(R.string.no_internet_error_msg);
           Toast.makeText(activity, errormsg, Toast.LENGTH_LONG).show();
        }
    }
}

How to make a query with group_concat in sql server

This can also be achieved using the Scalar-Valued Function in MSSQL 2008
Declare your function as following,

CREATE FUNCTION [dbo].[FunctionName]
(@MaskId INT)
RETURNS Varchar(500) 
AS
BEGIN

    DECLARE @SchoolName varchar(500)                        

    SELECT @SchoolName =ISNULL(@SchoolName ,'')+ MD.maskdetail +', ' 
    FROM maskdetails MD WITH (NOLOCK)       
    AND MD.MaskId=@MaskId

    RETURN @SchoolName

END

And then your final query will be like

SELECT m.maskid,m.maskname,m.schoolid,s.schoolname,
(SELECT [dbo].[FunctionName](m.maskid)) 'maskdetail'
FROM tblmask m JOIN school s on s.id = m.schoolid 
ORDER BY m.maskname ;

Note: You may have to change the function, as I don't know the complete table structure.

Java Loop every minute

Use Thread.sleep(long millis).

Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds, subject to the precision and accuracy of system timers and schedulers. The thread does not lose ownership of any monitors.

One minute would be (60*1000) = 60000 milliseconds.


For example, this loop will print the current time once every 5 seconds:

    try {
        while (true) {
            System.out.println(new Date());
            Thread.sleep(5 * 1000);
        }
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

If your sleep period becomes too large for int, explicitly compute in long (e.g. 1000L).

IllegalStateException: Can not perform this action after onSaveInstanceState with ViewPager

Another possible workaround, which I'm not sure if helps in all cases (origin here) :

@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        final View rootView = findViewById(android.R.id.content);
        if (rootView != null) {
            rootView.cancelPendingInputEvents();
        }
    }
}

MySQL Update Column +1?

You can do:

UPDATE categories SET posts = posts + 1 WHERE category_id = 42;

Float a div right, without impacting on design

What do you mean by impacts? Content will flow around a float. That's how they work.

If you want it to appear above your design, try setting:

z-index: 10;  
position: absolute;  
right: 0;  
top: 0;

docker: "build" requires 1 argument. See 'docker build --help'

In my case this error was happening in a Gitlab CI pipeline when I was passing multiple Gitlab env variables to docker build with --build-arg flags.

Turns out that one of the variables had a space in it which was causing the error. It was difficult to find since the pipeline logs just showed the $VARIABLE_NAME.

Make sure to quote the environment variables so that spaces get handled correctly.

Change from:

--build-arg VARIABLE_NAME=$VARIABLE_NAME

to:

--build-arg VARIABLE_NAME="$VARIABLE_NAME"

IPhone/IPad: How to get screen width programmatically?

As of iOS 9.0 there's no way to get the orientation reliably. This is the code I used for an app I design for only portrait mode, so if the app is opened in landscape mode it will still be accurate:

screenHeight = [[UIScreen mainScreen] bounds].size.height;
screenWidth = [[UIScreen mainScreen] bounds].size.width;
if (screenWidth > screenHeight) {
    float tempHeight = screenWidth;
    screenWidth = screenHeight;
    screenHeight = tempHeight;
}

Make a nav bar stick

/* Add css in your style */


.sticky-header {
    position: fixed;
    width: 100%;
    left: 0;
    top: 0;
    z-index: 100;
    border-top: 0;
    transition: 0.3s;
}


/* and use this javascript code: */

$(document).ready(function() {

  $(window).scroll(function () {
    if ($(window).scrollTop() > ) {
      $('.headercss').addClass('sticky-header');
    } else{
      $('.headercss').removeClass('sticky-header');
    }
  });
});

Pandas read_sql with parameters

The read_sql docs say this params argument can be a list, tuple or dict (see docs).

To pass the values in the sql query, there are different syntaxes possible: ?, :1, :name, %s, %(name)s (see PEP249).
But not all of these possibilities are supported by all database drivers, which syntax is supported depends on the driver you are using (psycopg2 in your case I suppose).

In your second case, when using a dict, you are using 'named arguments', and according to the psycopg2 documentation, they support the %(name)s style (and so not the :name I suppose), see http://initd.org/psycopg/docs/usage.html#query-parameters.
So using that style should work:

df = psql.read_sql(('select "Timestamp","Value" from "MyTable" '
                     'where "Timestamp" BETWEEN %(dstart)s AND %(dfinish)s'),
                   db,params={"dstart":datetime(2014,6,24,16,0),"dfinish":datetime(2014,6,24,17,0)},
                   index_col=['Timestamp'])

How to do perspective fixing?

The simple solution is to just remap coordinates from the original to the final image, copying pixels from one coordinate space to the other, rounding off as necessary -- which may result in some pixels being copied several times adjacent to each other, and other pixels being skipped, depending on whether you're stretching or shrinking (or both) in either dimension. Make sure your copying iterates through the destination space, so all pixels are covered there even if they're painted more than once, rather than thru the source which may skip pixels in the output.

The better solution involves calculating the corresponding source coordinate without rounding, and then using its fractional position between pixels to compute an appropriate average of the (typically) four pixels surrounding that location. This is essentially a filtering operation, so you lose some resolution -- but the result looks a LOT better to the human eye; it does a much better job of retaining small details and avoids creating straight-line artifacts which humans find objectionable.

Note that the same basic approach can be used to remap flat images onto any other shape, including 3D surface mapping.

How to get all table names from a database?

In newer versions of MySQL connectors the default tables are also listed if catalog is not passed

        DatabaseMetaData dbMeta = con.getMetaData();
        //con.getCatalog() returns database name
        ResultSet rs = dbMeta.getTables(con.getCatalog(), "", null, new String[]{"TABLE"});
        ArrayList<String> tables = new ArrayList<String>();
        while(rs.next()){
            String tableName = rs.getString("TABLE_NAME");
            tables.add(tableName);
        }
        return tables;

What does the "@" symbol do in Powershell?

In PowerShell V2, @ is also the Splat operator.

PS> # First use it to create a hashtable of parameters:
PS> $params = @{path = "c:\temp"; Recurse= $true}
PS> # Then use it to SPLAT the parameters - which is to say to expand a hash table 
PS> # into a set of command line parameters.
PS> dir @params
PS> # That was the equivalent of:
PS> dir -Path c:\temp -Recurse:$true

Assembly - JG/JNLE/JL/JNGE after CMP

The command JG simply means: Jump if Greater. The result of the preceding instructions is stored in certain processor flags (in this it would test if ZF=0 and SF=OF) and jump instruction act according to their state.

Total size of the contents of all the files in a directory

If you want the 'apparent size' (that is the number of bytes in each file), not size taken up by files on the disk, use the -b or --bytes option (if you got a Linux system with GNU coreutils):

% du -sbh <directory>

React - how to pass state to another component

Move all of your state and your handleClick function from Header to your MainWrapper component.

Then pass values as props to all components that need to share this functionality.

class MainWrapper extends React.Component {
    constructor() {
        super();
        this.state = {
            sidbarPushCollapsed: false,
            profileCollapsed: false
        };
        this.handleClick = this.handleClick.bind(this);
    }
    handleClick() {
        this.setState({
            sidbarPushCollapsed: !this.state.sidbarPushCollapsed,
            profileCollapsed: !this.state.profileCollapsed

        });
    }
    render() {
        return (
           //...
           <Header 
               handleClick={this.handleClick} 
               sidbarPushCollapsed={this.state.sidbarPushCollapsed}
               profileCollapsed={this.state.profileCollapsed} />
        );

Then in your Header's render() method, you'd use this.props:

<button type="button" id="sidbarPush" onClick={this.props.handleClick} profile={this.props.profileCollapsed}>

How do I convert a numpy array to (and display) an image?

import numpy as np
from keras.preprocessing.image import array_to_img
img = np.zeros([525,525,3], np.uint8)
b=array_to_img(img)
b

Is there a naming convention for MySQL?

Simple Answer: NO

Well, at least a naming convention as such encouraged by Oracle or community, no, however, basically you have to be aware of following the rules and limits for identifiers, such as indicated in MySQL documentation: https://dev.mysql.com/doc/refman/8.0/en/identifiers.html

About the naming convention you follow, I think it is ok, just the number 5 is a little bit unnecesary, I think most visual tools for managing databases offer a option for sorting column names (I use DBeaver, and it have it), so if the purpouse is having a nice visual presentation of your table you can use this option I mention.

By personal experience, I would recommed this:

  • Use lower case. This almost ensures interoperability when you migrate your databases from one server to another. Sometimes the lower_case_table_names is not correctly configured and your server start throwing errors just by simply unrecognizing your camelCase or PascalCase standard (case sensitivity problem).
  • Short names. Simple and clear. The most easy and fast is identify your table or columns, the better. Trust me, when you make a lot of different queries in a short amount of time is better having all simple to write (and read).
  • Avoid prefixes. Unless you are using the same database for tables of different applications, don't use prefixes. This only add more verbosity to your queries. There are situations when this could be useful, for example, when you want to indentify primary keys and foreign keys, that usually table names are used as prefix for id columns.
  • Use underscores for separating words. If you still want to use more than one word for naming a table, column, etc., so use underscores for separating_the_words, this helps for legibility (your eyes and your stressed brain are going to thank you).
  • Be consistent. Once you have your own standard, follow it. Don´t be the person that create the rules and is the first who breaking them, that is shameful.

And what about the "Plural vs Singular" naming? Well, this is most a situation of personal preferences. In my case I try to use plural names for tables because I think a table as a collection of elements or a package containig elements, so a plural name make sense for me; and singular names for columns because I see columns as attributes that describe singularly to those table elements.

Copy rows from one Datatable to another DataTable?

For those who want single command SQL query for that:

INSERT INTO TABLE002 
(COL001_MEM_ID, COL002_MEM_NAME, COL002_MEM_ADD, COL002_CREATE_USER_C, COL002_CREATE_S)
SELECT COL001_MEM_ID, COL001_MEM_NAME, COL001_MEM_ADD, COL001_CREATE_USER_C, COL001_CREATE_S
FROM TABLE001;

This query will copy data from TABLE001 to TABLE002 and we assume that both columns had different column names.

Column names are mapped one-to-one like:

COL001_MEM_ID -> COL001_MEM_ID

COL001_MEM_NAME -> COL002_MEM_NAME

COL001_MEM_ADD -> COL002_MEM_ADD

COL001_CREATE_USER_C -> COL002_CREATE_USER_C

COL002_CREATE_S -> COL002_CREATE_S

You can also specify where clause, if you need some condition.

CodeIgniter: Create new helper?

Just define a helper in application helper directory then call from your controller just function name like

helper name = new_helper.php
function test_method($data){
 return $data
}   

in controller load the helper

$this->load->new_helper();
$result =  test_method('Hello world!');
if($result){
 echo $result
}

output will be

Hello World!

How can I shutdown Spring task executor/scheduler pools before all other beans in the web app are destroyed?

I have added below code to terminate tasks you can use it. You may change the retry numbers.

package com.xxx.test.schedulers;

import java.util.Map;
import java.util.concurrent.TimeUnit;

import org.apache.log4j.Logger;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.stereotype.Component;

import com.xxx.core.XProvLogger;

@Component
class ContextClosedHandler implements ApplicationListener<ContextClosedEvent> , ApplicationContextAware,BeanPostProcessor{


private ApplicationContext context;

public Logger logger = XProvLogger.getInstance().x;

public void onApplicationEvent(ContextClosedEvent event) {


    Map<String, ThreadPoolTaskScheduler> schedulers = context.getBeansOfType(ThreadPoolTaskScheduler.class);

    for (ThreadPoolTaskScheduler scheduler : schedulers.values()) {         
        scheduler.getScheduledExecutor().shutdown();
        try {
            scheduler.getScheduledExecutor().awaitTermination(20000, TimeUnit.MILLISECONDS);
            if(scheduler.getScheduledExecutor().isTerminated() || scheduler.getScheduledExecutor().isShutdown())
                logger.info("Scheduler "+scheduler.getThreadNamePrefix() + " has stoped");
            else{
                logger.info("Scheduler "+scheduler.getThreadNamePrefix() + " has not stoped normally and will be shut down immediately");
                scheduler.getScheduledExecutor().shutdownNow();
                logger.info("Scheduler "+scheduler.getThreadNamePrefix() + " has shut down immediately");
            }
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    Map<String, ThreadPoolTaskExecutor> executers = context.getBeansOfType(ThreadPoolTaskExecutor.class);

    for (ThreadPoolTaskExecutor executor: executers.values()) {
        int retryCount = 0;
        while(executor.getActiveCount()>0 && ++retryCount<51){
            try {
                logger.info("Executer "+executor.getThreadNamePrefix()+" is still working with active " + executor.getActiveCount()+" work. Retry count is "+retryCount);
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        if(!(retryCount<51))
            logger.info("Executer "+executor.getThreadNamePrefix()+" is still working.Since Retry count exceeded max value "+retryCount+", will be killed immediately");
        executor.shutdown();
        logger.info("Executer "+executor.getThreadNamePrefix()+" with active " + executor.getActiveCount()+" work has killed");
    }
}


@Override
public void setApplicationContext(ApplicationContext context)
        throws BeansException {
    this.context = context;

}


@Override
public Object postProcessAfterInitialization(Object object, String arg1)
        throws BeansException {
    return object;
}


@Override
public Object postProcessBeforeInitialization(Object object, String arg1)
        throws BeansException {
    if(object instanceof ThreadPoolTaskScheduler)
        ((ThreadPoolTaskScheduler)object).setWaitForTasksToCompleteOnShutdown(true);
    if(object instanceof ThreadPoolTaskExecutor)
        ((ThreadPoolTaskExecutor)object).setWaitForTasksToCompleteOnShutdown(true);
    return object;
}

}

Finding the length of an integer in C

In this problem , i've used some arithmetic solution . Thanks :)

int main(void)
{
    int n, x = 10, i = 1;
    scanf("%d", &n);
    while(n / x > 0)
    {
        x*=10;
        i++;
    }
    printf("the number contains %d digits\n", i);

    return 0;
}

SQL Greater than, Equal to AND Less Than

Supposing you use sql server:

WHERE StartTime BETWEEN DATEADD(HOUR, -1, GetDate())
                    AND DATEADD(HOUR, 1, GetDate())

How do I increase the RAM and set up host-only networking in Vagrant?

I could not get any of these answers to work. Here's what I ended up putting at the very top of my Vagrantfile, before the Vagrant::Config.run do block:

Vagrant.configure("2") do |config|
  config.vm.provider "virtualbox" do |vb|
    vb.customize ["modifyvm", :id, "--memory", "1024"]
  end
end

I noticed that the shortcut accessor style, "vb.memory = 1024", didn't seem to work.

How to refresh activity after changing language (Locale) inside application

Call this method to change app locale:

public void settingLocale(Context context, String language) {

    Locale locale;

    Configuration config = new Configuration();

     if(language.equals(LANGUAGE_ENGLISH)) {

        locale = new Locale("en");

        Locale.setDefault(locale);

        config.locale = locale;

    }else if(language.equals(LANGUAGE_ARABIC)){

        locale = new Locale("hi");

        Locale.setDefault(locale);

        config.locale = locale;

    }

    context.getResources().updateConfiguration(config, null);

    // Here again set the text on view to reflect locale change

    // and it will pick resource from new locale

    tv1.setText(R.string.one); //tv1 is textview in my activity

}

Note: Put your strings in value and values- folder.

Can I override and overload static methods in Java?

No, you cannot override a static method. The static resolves against the class, not the instance.

public class Parent { 
    public static String getCName() { 
        return "I am the parent"; 
    } 
} 

public class Child extends Parent { 
    public static String getCName() { 
        return "I am the child"; 
    } 
} 

Each class has a static method getCName(). When you call on the Class name it behaves as you would expect and each returns the expected value.

@Test 
public void testGetCNameOnClass() { 
    assertThat(Parent.getCName(), is("I am the parent")); 
    assertThat(Child.getCName(), is("I am the child")); 
} 

No surprises in this unit test. But this is not overriding.This declaring something that has a name collision.

If we try to reach the static from an instance of the class (not a good practice), then it really shows:

private Parent cp = new Child(); 
`enter code here`
assertThat(cp.getCName(), is("I am the parent")); 

Even though cp is a Child, the static is resolved through the declared type, Parent, instead of the actual type of the object. For non-statics, this is resolved correctly because a non-static method can override a method of its parent.

Using pointer to char array, values in that array can be accessed?

Most people responding don't even seem to know what an array pointer is...

The problem is that you do pointer arithmetics with an array pointer: ptr + 1 will mean "jump 5 bytes ahead since ptr points at a 5 byte array".

Do like this instead:

#include <stdio.h>

int main()
{
  char (*ptr)[5];
  char arr[5] = {'a','b','c','d','e'};
  int i;

  ptr = &arr;
  for(i=0; i<5; i++)
  {
    printf("\nvalue: %c", (*ptr)[i]);
  }
}

Take the contents of what the array pointer points at and you get an array. So they work just like any pointer in C.

I'm getting an error "invalid use of incomplete type 'class map'

Your first usage of Map is inside a function in the combat class. That happens before Map is defined, hence the error.

A forward declaration only says that a particular class will be defined later, so it's ok to reference it or have pointers to objects, etc. However a forward declaration does not say what members a class has, so as far as the compiler is concerned you can't use any of them until Map is fully declared.

The solution is to follow the C++ pattern of the class declaration in a .h file and the function bodies in a .cpp. That way all the declarations appear before the first definitions, and the compiler knows what it's working with.

Express-js wildcard routing to cover everything under and including a path

The connect router has now been removed (https://github.com/senchalabs/connect/issues/262), the author stating that you should use a framework on top of connect (like Express) for routing.

Express currently treats app.get("/foo*") as app.get(/\/foo(.*)/), removing the need for two separate routes. This is in contrast to the previous answer (referring to the now removed connect router) which stated that "* in a path is replaced with .+".

Update: Express now uses the "path-to-regexp" module (since Express 4.0.0) which maintains the same behavior in the version currently referenced. It's unclear to me whether the latest version of that module keeps the behavior, but for now this answer stands.

Export to CSV via PHP

pre-made code attached here. you can use it by just copying and pasting in your code:

https://gist.github.com/umairidrees/8952054#file-php-save-db-table-as-csv

fatal: Not a valid object name: 'master'

When I git init a folder it doesn't create a master branch

This is true, and expected behaviour. Git will not create a master branch until you commit something.

When I do git --bare init it creates the files.

A non-bare git init will also create the same files, in a hidden .git directory in the root of your project.

When I type git branch master it says "fatal: Not a valid object name: 'master'"

That is again correct behaviour. Until you commit, there is no master branch.

You haven't asked a question, but I'll answer the question I assumed you mean to ask. Add one or more files to your directory, and git add them to prepare a commit. Then git commit to create your initial commit and master branch.

SQL Server stored procedure Nullable parameter

It looks like you're passing in Null for every argument except for PropertyValueID and DropDownOptionID, right? I don't think any of your IF statements will fire if only these two values are not-null. In short, I think you have a logic error.

Other than that, I would suggest two things...

First, instead of testing for NULL, use this kind syntax on your if statements (it's safer)...

    ELSE IF ISNULL(@UnitValue, 0) != 0 AND ISNULL(@UnitOfMeasureID, 0) = 0

Second, add a meaningful PRINT statement before each UPDATE. That way, when you run the sproc in MSSQL, you can look at the messages and see how far it's actually getting.

Empty set literal?

It depends on if you want the literal for a comparison, or for assignment.

If you want to make an existing set empty, you can use the .clear() metod, especially if you want to avoid creating a new object. If you want to do a comparison, use set() or check if the length is 0.

example:

#create a new set    
a=set([1,2,3,'foo','bar'])
#or, using a literal:
a={1,2,3,'foo','bar'}

#create an empty set
a=set()
#or, use the clear method
a.clear()

#comparison to a new blank set
if a==set():
    #do something

#length-checking comparison
if len(a)==0:
    #do something

number several equations with only one number

How about something like:

\documentclass{article}

\usepackage{amssymb,amsmath}

\begin{document}

\begin{equation}\label{A_Label}
  \begin{split}
    w^T x_i + b \geqslant 1-\xi_i \text{ if } y_i &= 1, \\
    w^T x_i + b \leqslant -1+\xi_i \text{ if } y_i &= -1
  \end{split}
\end{equation}

\end{document}

which produces:

enter image description here

Neither user 10102 nor current process has android.permission.READ_PHONE_STATE

I was experiencing this problem on Samsung devices (fine on others). like zyamys suggested in his/her comment, I added the manifest.permission line but in addition to rather than instead of the original line, so:

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

I'm targeting API 22, so don't need to explicitly ask for permissions.

Is there a version of JavaScript's String.indexOf() that allows for regular expressions?

var mystring = "abc ab a";
var re  = new RegExp("ab"); // any regex here

if ( re.exec(mystring) != null ){ 
   alert("matches"); // true in this case
}

Use standard regular expressions:

var re  = new RegExp("^ab");  // At front
var re  = new RegExp("ab$");  // At end
var re  = new RegExp("ab(c|d)");  // abc or abd

Reason: no suitable image found

You need to set certificate (just certificate & not provisioning profile) for each and every dynamic framework you are linking(directly or indirectly) in your projectenter image description here

How can I find non-ASCII characters in MySQL?

One missing character from everyone's examples above is the termination character (\0). This is invisible to the MySQL console output and is not discoverable by any of the queries heretofore mentioned. The query to find it is simply:

select * from TABLE where COLUMN like '%\0%';

Troubleshooting "program does not contain a static 'Main' method" when it clearly does...?

Check your project's properties. On the "Application" tab, select your Program class as the Startup object:

alt text

How to pretty-print a numpy.array without scientific notation and with given precision?

And here is what I use, and it's pretty uncomplicated:

print(np.vectorize("%.2f".__mod__)(sparse))

When to use the JavaScript MIME type application/javascript instead of text/javascript?

In theory, according to RFC 4329, application/javascript.

The reason it is supposed to be application is not anything to do with whether the type is readable or executable. It's because there are custom charset-determination mechanisms laid down by the language/type itself, rather than just the generic charset parameter. A subtype of text should be capable of being transcoded by a proxy to another charset, changing the charset parameter. This is not true of JavaScript because:

a. the RFC says user-agents should be doing BOM-sniffing on the script to determine type (I'm not sure if any browsers actually do this though);

b. browsers use other information—the including page's encoding and in some browsers the script charset attribute—to determine the charset. So any proxy that tried to transcode the resource would break its users. (Of course in reality no-one ever uses transcoding proxies anyway, but that was the intent.)

Therefore the exact bytes of the file must be preserved exactly, which makes it a binary application type and not technically character-based text.

For the same reason, application/xml is officially preferred over text/xml: XML has its own in-band charset signalling mechanisms. And everyone ignores application for XML, too.

text/javascript and text/xml may not be the official Right Thing, but there are what everyone uses today for compatibility reasons, and the reasons why they're not the right thing are practically speaking completely unimportant.

Add line break within tooltips

The solution for me was http://jqueryui.com/tooltip/:

And here the code (the part of script that make <br/> Works is "content:"):

HTML HEAD

<head runat="server">
    <script src="../Scripts/jquery-2.0.3.min.js"></script>
    <link href="Content/themes/base/jquery-ui.css" rel="stylesheet" />
    <script src="../Scripts/jquery-ui-1.10.3.min.js"></script>
<script>
    /*Position:
      my =>  at
      at => element*/
    $(function () {
        $(document).tooltip({
            content: function() {
                var element = $( this );
                if ( element.is( "[title]" ) ) {
                    return element.attr( "title" );
                }

            },
            position: { my: "left bottom-3", at: "center top" } });
    });
</script>
</head>

ASPX or HTML control

<asp:TextBox ID="Establecimiento" runat="server" Font-Size="1.3em" placeholder="Establecimiento" title="Texto 1.<br/>TIP: texto 2"></asp:TextBox>

Hope this help someone

Convert Linq Query Result to Dictionary

Try using the ToDictionary method like so:

var dict = TableObj.ToDictionary( t => t.Key, t => t.TimeStamp );

grunt: command not found when running from terminal

For windows

npm install -g grunt-cli

npm install load-grunt-tasks

Then run

grunt

Multiple condition in single IF statement

Yes it is, there have to be boolean expresion after IF. Here you have a direct link. I hope it helps. GL!

How to print register values in GDB?

info registers shows all the registers; info registers eax shows just the register eax. The command can be abbreviated as i r

How to check if a process id (PID) exists

You have two ways:

Lets start by looking for a specific application in my laptop:

[root@pinky:~]# ps fax | grep mozilla
 3358 ?        S      0:00  \_ /bin/sh /usr/lib/firefox-3.5/run-mozilla.sh /usr/lib/firefox-3.5/firefox
16198 pts/2    S+     0:00              \_ grep mozilla

All examples now will look for PID 3358.

First way: Run "ps aux" and grep for the PID in the second column. In this example I look for firefox, and then for it's PID:

[root@pinky:~]# ps aux | awk '{print $2 }' | grep 3358
3358

So your code will be:

if [ ps aux | awk '{print $2 }' | grep -q $PID 2> /dev/null ]; then
    kill $PID 
fi

Second way: Just look for something in the /proc/$PID directory. I am using "exe" in this example, but you can use anything else.

[root@pinky:~]# ls -l /proc/3358/exe 
lrwxrwxrwx. 1 elcuco elcuco 0 2010-06-15 12:33 /proc/3358/exe -> /bin/bash

So your code will be:

if [ -f /proc/$PID/exe ]; then
    kill $PID 
fi

BTW: whats wrong with kill -9 $PID || true ?


EDIT:

After thinking about it for a few months.. (about 24...) the original idea I gave here is a nice hack, but highly unportable. While it teaches a few implementation details of Linux, it will fail to work on Mac, Solaris or *BSD. It may even fail on future Linux kernels. Please - use "ps" as described in other responses.

getting the last item in a javascript object

The other answers overcomplicate it for me.

let animals = {
  a: 'dog',
  b: 'cat',
  c: 'bird'
}

let lastKey = Object.keys(animals).pop()
let lastValue = animals[Object.keys(animals).pop()]

How to create a Custom Dialog box in android?

Full Screen Custom Alert Dialog Class in Kotlin

  1. Create XML file, same as you would an activity

  2. Create AlertDialog custom class

    class Your_Class(context:Context) : AlertDialog(context){
    
     init {
      requestWindowFeature(Window.FEATURE_NO_TITLE)
      setCancelable(false)
     }
    
     override fun onCreate(savedInstanceState: Bundle?) {
      super.onCreate(savedInstanceState)
      setContentView(R.layout.your_Layout)
      val window = this.window
      window?.setLayout(WindowManager.LayoutParams.MATCH_PARENT,
                         WindowManager.LayoutParams.MATCH_PARENT)
    
      //continue custom code here
      //call dismiss() to close
     }
    }
    
  3. Call the dialog within the activity

    val dialog = Your_Class(this)
    //can set some dialog options here
    dialog.show()
    

Note**: If you do not want your dialog to be full screen, delete the following lines

      val window = this.window
      window?.setLayout(WindowManager.LayoutParams.MATCH_PARENT,
                         WindowManager.LayoutParams.MATCH_PARENT)

Then edit the layout_width & layout_height of your top layout within your XML file to be either wrap_content or a fixed DP value.

I generally do not recommend using fixed DP as you would likely want your app to be adaptable to multiple screen sizes, however if you keep your size values small enough you should be fine

What does 'low in coupling and high in cohesion' mean

Short and clear answer

  • High cohesion: Elements within one class/module should functionally belong together and do one particular thing.
  • Loose coupling: Among different classes/modules should be minimal dependency.

Eclipse returns error message "Java was started but returned exit code = 1"

I had same issue in my windows 7, 64-bit machine. Then I downloaded and installed 64 bit jdk for Java(which includes jre). This solved the issue.

Redirecting a request using servlets and the "setHeader" method not working

Another way of doing this if you want to redirect to any url source after the specified point of time

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import java.io.*;

public class MyServlet extends HttpServlet


{

public void doGet(HttpServletRequest request,HttpServletResponse response) throws IOException

{

response.setContentType("text/html");

PrintWriter pw=response.getWriter();

pw.println("<b><centre>Redirecting to Google<br>");


response.setHeader("refresh,"5;https://www.google.com/"); // redirects to url  after 5 seconds


pw.close();
}

}

Running code after Spring Boot starts

It is as simple as this:

@EventListener(ApplicationReadyEvent.class)
public void doSomethingAfterStartup() {
    System.out.println("hello world, I have just started up");
}

Tested on version 1.5.1.RELEASE

RegEx to match stuff between parentheses

Use this expression:

/\(([^()]+)\)/g

e.g:

function()
{
    var mts = "something/([0-9])/([a-z])".match(/\(([^()]+)\)/g );
    alert(mts[0]);
    alert(mts[1]);
}

Why doesn't GCC optimize a*a*a*a*a*a to (a*a*a)*(a*a*a)?

Library functions like "pow" are usually carefully crafted to yield the minimum possible error (in generic case). This is usually achieved approximating functions with splines (according to Pascal's comment the most common implementation seems to be using Remez algorithm)

fundamentally the following operation:

pow(x,y);

has a inherent error of approximately the same magnitude as the error in any single multiplication or division.

While the following operation:

float a=someValue;
float b=a*a*a*a*a*a;

has a inherent error that is greater more than 5 times the error of a single multiplication or division (because you are combining 5 multiplications).

The compiler should be really carefull to the kind of optimization it is doing:

  1. if optimizing pow(a,6) to a*a*a*a*a*a it may improve performance, but drastically reduce the accuracy for floating point numbers.
  2. if optimizing a*a*a*a*a*a to pow(a,6) it may actually reduce the accuracy because "a" was some special value that allows multiplication without error (a power of 2 or some small integer number)
  3. if optimizing pow(a,6) to (a*a*a)*(a*a*a) or (a*a)*(a*a)*(a*a) there still can be a loss of accuracy compared to pow function.

In general you know that for arbitrary floating point values "pow" has better accuracy than any function you could eventually write, but in some special cases multiple multiplications may have better accuracy and performance, it is up to the developer choosing what is more appropriate, eventually commenting the code so that noone else would "optimize" that code.

The only thing that make sense (personal opinion, and apparently a choice in GCC wichout any particular optimization or compiler flag) to optimize should be replacing "pow(a,2)" with "a*a". That would be the only sane thing a compiler vendor should do.

Python popen command. Wait until the command is finished

I think process.communicate() would be suitable for output having small size. For larger output it would not be the best approach.

Gradle finds wrong JAVA_HOME even though it's correctly set

I faced this issue when I run the following command on Ubuntu:

ionic build android

To solve this issue, I did the following steps:

ln -sf /usr/lib/jvm/java-7-openjdk-amd64/jre/bin/java /usr/lib/jvm/default-java

Add JAVA_HOME to /etc/environment:

vi /etc/environment

Add:

JAVA_HOME="/usr/lib/jvm/default-java"

After saving, read it:

source /etc/environment

Finally, you can run build command.

Git merge develop into feature branch outputs "Already up-to-date" while it's not

git pull origin develop

Since pulling a branch into another directly merges them together

How to take a screenshot programmatically on iOS

I'm answering this question as it's a highly viewed, and there are many answers out there plus there's Swift and Obj-C.

Disclaimer This is not my code, nor my answers, this is only to help people that land here find a quick answer. There are links to the original answers to give credit where credit is due!! Please honor the original answers with a +1 if you use their answer!


Using QuartzCore

#import <QuartzCore/QuartzCore.h> 

if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)]) {
    UIGraphicsBeginImageContextWithOptions(self.window.bounds.size, NO, [UIScreen mainScreen].scale);
} else {
    UIGraphicsBeginImageContext(self.window.bounds.size);
}

[self.window.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
NSData *imageData = UIImagePNGRepresentation(image);
if (imageData) {
    [imageData writeToFile:@"screenshot.png" atomically:YES];
} else {
    NSLog(@"error while taking screenshot");
}

In Swift

func captureScreen() -> UIImage
{

    UIGraphicsBeginImageContextWithOptions(self.view.bounds.size, false, 0);

    self.view.drawViewHierarchyInRect(view.bounds, afterScreenUpdates: true)

    let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()

    UIGraphicsEndImageContext()

    return image
}

Note: As the nature with programming, updates may need to be done so please edit or let me know! *Also if I failed to include an answer/method worth including feel free to let me know as well!

Set the default value in dropdownlist using jQuery

$('#userZipFiles option').prop('selected', function() {
        return this.defaultSelected;
    });     

Reading a UTF8 CSV file with Python

Looking at the Latin-1 unicode table, I see the character code 00E9 "LATIN SMALL LETTER E WITH ACUTE". This is the accented character in your sample data. A simple test in Python shows that UTF-8 encoding for this character is different from the unicode (almost UTF-16) encoding.

>>> u'\u00e9'
u'\xe9'
>>> u'\u00e9'.encode('utf-8')
'\xc3\xa9'
>>> 

I suggest you try to encode("UTF-8") the unicode data before calling the special unicode_csv_reader(). Simply reading the data from a file might hide the encoding, so check the actual character values.

How to solve Object reference not set to an instance of an object.?

You need to initialize the list first:

protected List<string> list = new List<string>();

Encrypt & Decrypt using PyCrypto AES 256

I have used both Crypto and PyCryptodomex library and it is blazing fast...

import base64
import hashlib
from Cryptodome.Cipher import AES as domeAES
from Cryptodome.Random import get_random_bytes
from Crypto import Random
from Crypto.Cipher import AES as cryptoAES

BLOCK_SIZE = AES.block_size

key = "my_secret_key".encode()
__key__ = hashlib.sha256(key).digest()
print(__key__)

def encrypt(raw):
    BS = cryptoAES.block_size
    pad = lambda s: s + (BS - len(s) % BS) * chr(BS - len(s) % BS)
    raw = base64.b64encode(pad(raw).encode('utf8'))
    iv = get_random_bytes(cryptoAES.block_size)
    cipher = cryptoAES.new(key= __key__, mode= cryptoAES.MODE_CFB,iv= iv)
    a= base64.b64encode(iv + cipher.encrypt(raw))
    IV = Random.new().read(BLOCK_SIZE)
    aes = domeAES.new(__key__, domeAES.MODE_CFB, IV)
    b = base64.b64encode(IV + aes.encrypt(a))
    return b

def decrypt(enc):
    passphrase = __key__
    encrypted = base64.b64decode(enc)
    IV = encrypted[:BLOCK_SIZE]
    aes = domeAES.new(passphrase, domeAES.MODE_CFB, IV)
    enc = aes.decrypt(encrypted[BLOCK_SIZE:])
    unpad = lambda s: s[:-ord(s[-1:])]
    enc = base64.b64decode(enc)
    iv = enc[:cryptoAES.block_size]
    cipher = cryptoAES.new(__key__, cryptoAES.MODE_CFB, iv)
    b=  unpad(base64.b64decode(cipher.decrypt(enc[cryptoAES.block_size:])).decode('utf8'))
    return b

encrypted_data =encrypt("Hi Steven!!!!!")
print(encrypted_data)
print("=======")
decrypted_data = decrypt(encrypted_data)
print(decrypted_data)

How do I detect what .NET Framework versions and service packs are installed?

See How to: Determine Which .NET Framework Versions Are Installed (MSDN).

MSDN proposes one function example that seems to do the job for version 1-4. According to the article, the method output is:

v2.0.50727  2.0.50727.4016  SP2
v3.0  3.0.30729.4037  SP2
v3.5  3.5.30729.01  SP1
v4
  Client  4.0.30319
  Full  4.0.30319

Note that for "versions 4.5 and later" there is another function.

How can I use getSystemService in a non-activity class (LocationManager)?

You need to pass your context to your fyl class..
One solution is make a constructor like this for your fyl class:

public class fyl {
 Context mContext;
 public fyl(Context mContext) {
       this.mContext = mContext;
 }

 public Location getLocation() {
       --
       locationManager = (LocationManager)mContext.getSystemService(context);

       --
 }
}

So in your activity class create the object of fyl in onCreate function like this:

package com.atClass.lmt;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import android.location.Location;

public class lmt extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        fyl lfyl = new fyl(this); //Here the context is passing 

        Location location = lfyl.getLocation();
        String latLongString = lfyl.updateWithNewLocation(location);

        TextView myLocationText = (TextView)findViewById(R.id.myLocationText);
        myLocationText.setText("Your current position is:\n" + latLongString);
    }
}

batch file to check 64bit or 32bit OS

Many DOS commands in the different versions of Windows are similar but may support different parameters. Plus, newer versions of Windows may support new commands or retire older ones. Thus, if you wish to write a batch file that can run on different types of machines, it may prove beneficial to determine the version of Windows on which the batch file is running. This way the batch file can execute commands appropriate to the operating system.

The following batch file will determine whether or not the machine is running Windows 7, Windows Server 2008, Windows Vista, Windows Server 2003, Windows XP, Windows 2000, or Windows NT. It can easily be modified to support other versions of Windows as necessary or to set an environment variable based on the version of Windows detected. Note that for this batch file to correctly discern between newer versions of Windows Server and consumer versions of Windows, it is more convoluted than batch files you may see elsewhere. I have explained the reasoning below.

1) Open a Notepad window.

2) Copy the following text into Notepad (you may want to access this tip's printed version as some lines wrap):

@echo off

ver | find "2003" > nul
if %ERRORLEVEL% == 0 goto ver_2003

ver | find "XP" > nul
if %ERRORLEVEL% == 0 goto ver_xp

ver | find "2000" > nul
if %ERRORLEVEL% == 0 goto ver_2000

ver | find "NT" > nul
if %ERRORLEVEL% == 0 goto ver_nt

if not exist %SystemRoot%\system32\systeminfo.exe goto warnthenexit

systeminfo | find "OS Name" > %TEMP%\osname.txt
FOR /F "usebackq delims=: tokens=2" %%i IN (%TEMP%\osname.txt) DO set vers=%%i

echo %vers% | find "Windows 7" > nul
if %ERRORLEVEL% == 0 goto ver_7

echo %vers% | find "Windows Server 2008" > nul
if %ERRORLEVEL% == 0 goto ver_2008

echo %vers% | find "Windows Vista" > nul
if %ERRORLEVEL% == 0 goto ver_vista

goto warnthenexit

:ver_7
:Run Windows 7 specific commands here.
echo Windows 7
goto exit

:ver_2008
:Run Windows Server 2008 specific commands here.
echo Windows Server 2008
goto exit

:ver_vista
:Run Windows Vista specific commands here.
echo Windows Vista
goto exit

:ver_2003
:Run Windows Server 2003 specific commands here.
echo Windows Server 2003
goto exit

:ver_xp
:Run Windows XP specific commands here.
echo Windows XP
goto exit

:ver_2000
:Run Windows 2000 specific commands here.
echo Windows 2000
goto exit

:ver_nt
:Run Windows NT specific commands here.
echo Windows NT
goto exit

:warnthenexit
echo Machine undetermined.

:exit

3) Save the file as %WINDIR%\whichvers.bat

4) Now, from the command prompt, enter:

whichvers

This will display which version of Windows you are running.

NOTES:

  1. The reasoning for using the SYSTEMINFO command rather than relying on the VER command is because Windows Server 2008 "shares" version numbers with other Windows releases (see Microsoft). Thus relying on a "version number" of 6.0 to detect Windows Vista or 6.1 to detect Windows 7 fails to differentiate a machine from Windows Server 2008 or Windows Server 2008 R2.

  2. The creation of %TEMP%\osname.txt is solely because I could not place the results of systeminfo | find "OS Name" directly into the for /f command - it does not like piped commands. You may find an easier way to handle grabbing the information from SYSTEMINFO - if so, please comment.

  3. The environment variable %vers% has leading spaces. I could remove these with a longer batch file, but in this case it is not necessary.

  4. The batch file detects for SYSTEMINFO as it assumes if it gets beyond the older operating system detections, the running version of Windows is even older and will not have this utility. On Windows 7 64-bit it is still located in the %SystemRoot%\system32 folder - if later versions of Windows become 64-bit only, this batch file may have to be updated.

Return to the Windows XP and DOS page.

Force unmount of NFS-mounted directory

Your NFS server disappeared.

Ideally your best bet is if the NFS server comes back.

If not, the "umount -f" should have done the trick. It doesn't ALWAYS work, but it often will.

If you happen to know what processes are USING the NFS filesystem, you could try killing those processes and then maybe an unmount would work.

Finally, I'd guess you need to reboot.

Also, DON'T soft-mount your NFS drives. You use hard-mounts to guarantee that they worked. That's necessary if you're doing writes.

How to force page refreshes or reloads in jQuery?

Or better

window.location.assign("relative or absolute address");

that tends to work best across all browsers and mobile

How to group subarrays by a column value?

This array_group_by function achieves what you are looking for:

$grouped = array_group_by($arr, 'id');

It even supports multi-level groupings:

$grouped = array_group_by($arr, 'id', 'part_no');

How to set RelativeLayout layout params in code not in xml?

Something like this..

 RelativeLayout linearLayout = (RelativeLayout) findViewById(R.id.widget43);
                // ListView listView = (ListView) findViewById(R.id.ListView01);

                LayoutInflater inflater = (LayoutInflater) this
                        .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                // View footer = inflater.inflate(R.layout.footer, null);
                View footer = LayoutInflater.from(this).inflate(R.layout.footer,
                        null);
                final RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(
                        RelativeLayout.LayoutParams.FILL_PARENT,
                        RelativeLayout.LayoutParams.FILL_PARENT);
                layoutParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, 1);
footer.setLayoutParams(layoutParams);

How to free memory from char array in C

You don't free anything at all. Since you never acquired any resources dynamically, there is nothing you have to, or even are allowed to, free.

(It's the same as when you say int n = 10;: There are no dynamic resources involved that you have to manage manually.)

Cannot open database "test" requested by the login. The login failed. Login failed for user 'xyz\ASPNET'

Well, the error is pretty clear, no? You are trying to connect to your SQL Server with user "xyz/ASPNET" - that's the account your ASP.NET app is running under.

This account is not allowed to connect to SQL Server - either create a login on SQL Server for that account, or then specify another valid SQL Server account in your connection string.

Can you show us your connection string (by updating your original question)?

UPDATE: Ok, you're using integrated Windows authentication --> you need to create a SQL Server login for "xyz\ASPNET" on your SQL Server - or change your connection string to something like:

connectionString="Server=.\SQLExpress;Database=IFItest;User ID=xyz;pwd=top$secret"

If you have a user "xyz" with a password of "top$secret" in your database.

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

This obviously won't work in many cases, but if your Makefile was created by CMake you might be able to run make help.

$ make help
The following are some of the valid targets for this Makefile:
... all (the default if no target is provided)
... clean
... depend
... install
etc

Display fullscreen mode on Tkinter

Here's a simple solution with lambdas:

root = Tk()
root.attributes("-fullscreen", True)
root.bind("<F11>", lambda event: root.attributes("-fullscreen",
                                    not root.attributes("-fullscreen")))
root.bind("<Escape>", lambda event: root.attributes("-fullscreen", False))
root.mainloop()

This will make the screen exit fullscreen when escape is pressed, and toggle fullscreen when F11 is pressed.

Visual Studio Code Tab Key does not insert a tab

All the above failed for me. But I noticed shift + ? Tab worked as expected (outdenting the line).

So I looked for the "Indent Line" shortcut (which was assigned to alt + ctrl + cmd + 0 ), assigned it to tab, and now I'm happy again.


Next morning edit...

I also use tab to accept snippet suggestions, so I've set the "when" of "Indent Line" to editorTextFocus && !editorReadonly && !inSnippetMode && !suggestWidgetVisible.

An object reference is required to access a non-static member

Make your audioSounds and minTime variables as static variables, as you are using them in a static method (playSound).

Marking a method as static prevents the usage of non-static (instance) members in that method.

To understand more , please read this SO QA:

Static keyword in c#

How to set up a PostgreSQL database in Django

If you are using Fedora 20, Django 1.6.5, postgresql 9.3.* and you need the psycopg2 module, do this:

yum install postgresql-devel
easy_install psycopg2

If you are like me, you may have trouble finding the well documented libpq-dev rpm... The above worked for me just now.

How can I programmatically invoke an onclick() event from a anchor tag while keeping the ‘this’ reference in the onclick function?

Granted, OP stated very similarly that this didn't work, but it did for me. Based on the notes in my source, it seems it was implemented around the time, or after, OP's post. Perhaps it's more standard now.

document.getElementsByName('MyElementsName')[0].click();

In my case, my button didn't have an ID. If your element has an id, preferably use the following (untested).

document.getElementById('MyElementsId').click();

I originally tried this method and it didn't work. After Googling I came back and realized my element was by name, and didn't have an ID. Double check you're calling the right attribute.

Source: https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/click

How to find first element of array matching a boolean condition in JavaScript?

foundElement = myArray[myArray.findIndex(element => //condition here)];

iOS 9 not opening Instagram app with URL SCHEME

When I tried to call Facebook from my own app today, I found that there is no a LSApplicationQueriesSchemes key I can add to the Info.plist (Xcode Version 8.2.1 (8C1002)). I opened the Info.plist with Sublime Text and manually added it into the file, then it worked. Just to let you know that if you cannot find the key, simply add it yourself.

How do I run a shell script without using "sh" or "bash" commands?

You have to enable the executable bit for the program.

chmod +x script.sh

Then you can use ./script.sh

You can add the folder to the PATH in your .bashrc file (located in your home directory). Add this line to the end of the file:

export PATH=$PATH:/your/folder/here

Angular HttpClient "Http failure during parsing"

if you have options

return this.http.post(`${this.endpoint}/account/login`,payload, { ...options, responseType: 'text' })

mysql query result into php array

I think you wanted to do this:

while( $row = mysql_fetch_assoc( $result)){
    $new_array[] = $row; // Inside while loop
}

Or maybe store id as key too

 $new_array[ $row['id']] = $row;

Using the second ways you would be able to address rows directly by their id, such as: $new_array[ 5].

UITableView load more when scrolling to bottom like Facebook application

One more option to use (Swift 3 and iOS 10+):

class DocumentEventsTableViewController: UITableViewController, UITableViewDataSourcePrefetching {

     var currentPage: Int = 1
     let pageSize: Int = 10 // num of items in one page

     override func viewDidLoad() {
         super.viewDidLoad()

         self.tableView.prefetchDataSource = self
     }

     func tableView(_ tableView: UITableView, prefetchRowsAt indexPaths: [IndexPath]) {
         let upcomingRows = indexPaths.map { $0.row }

         if let maxIndex = upcomingRows.max() {

            let nextPage: Int = Int(ceil(Double(maxIndex) / Double(pageSize))) + 1

            if nextPage > currentPage {
                 // Your function, which attempts to load respective page from the local database
                 loadLocalData(page: nextPage)

                 // Your function, which makes a network request to fetch the respective page of data from the network
                 startLoadingDataFromNetwork(page: nextPage) 

                 currentPage = nextPage
             }
         }
     }
 }

For rather small pages (~ 10 items) you might want to manually add data for pages 1 and 2 because nextPage might be somewhere about 1-2 until the table has a few items to be scrolled well. But it will work great for all next pages.

NodeJS/express: Cache and 304 status code

I had the same problem in Safari and Chrome (the only ones I've tested) but I just did something that seems to work, at least I haven't been able to reproduce the problem since I added the solution. What I did was add a metatag to the header with a generated timstamp. Doesn't seem right but it's simple :)

<meta name="304workaround" content="2013-10-24 21:17:23">

Update P.S As far as I can tell, the problem disappears when I remove my node proxy (by proxy i mean both express.vhost and http-proxy module), which is weird...

Extracting Ajax return data in jQuery

Change the .find to .filter...

Google maps Marker Label with multiple characters

For anyone trying to

...in 2019, it's worth noting some of the code referenced here no longer exists (officially). Google discontinued support for the "MarkerWithLabel" project a long time ago. It was originally hosted on Google code here, now it's unofficially hosted on Github here.

But there is another project Google maintained until 2016, called "MapLabel"s. That approach is different (and arguably better). You create a separate map label object with the same origin as the marker instead of adding a mapLabel option to the marker itself. You can make a marker with label with multiple characters using js-marker-label.

SQL Server table creation date query

For SQL Server 2000:

SELECT   su.name,so.name,so.crdate,* 
FROM     sysobjects so JOIN sysusers su
ON       so.uid = su.uid
WHERE    xtype='U'
ORDER BY so.name

OS X Framework Library not loaded: 'Image not found'

[Xcode 11+]

The only thing to do is to add the framework to the General->Frameworks, Libraries And Embedded Content section in the General tab of your app target.

Make sure you select the 'Embed & Sign' option.

enter image description here

[Xcode v6 -> Xcode v10]

The only thing to do is to add the framework to the Embedded binaries section in the General tab of your app target.

Screenshot from Xcode