How to sum digits of an integer in java?
Here is a simple program for sum of digits of the number 321.
import java.math.*;
class SumOfDigits {
public static void main(String args[]) throws Exception {
int sum = 0;
int i = 321;
sum = (i % 10) + (i / 10);
if (sum > 9) {
int n = (sum % 10) + (sum / 10);
System.out.print("Sum of digits of " + i + " is " + n);
}else{
System.out.print("Sum of digits of " + i + " is " + sum );
}
}
}
Output:
Sum of digits of 321 is 6
Or simple you can use this..check below program.
public class SumOfDigits {
public static void main(String[] args)
{
long num = 321;
/* int rem,sum=0;
while(num!=0)
{
rem = num%10;
sum = sum+rem;
num=num/10;
}
System.out.println(sum);
*/
if(num!=0)
{
long sum = ((num%9==0) ? 9 : num%9);
System.out.println(sum);
}
}
Line continue character in C#
@"string here
that is long you mean"
But be careful, because
@"string here
and space before this text
means the space is also a part of the string"
It also escapes things in the string
@"c:\\folder" // c:\\folder
@"c:\folder" // c:\folder
"c:\\folder" // c:\folder
Related
Preserve Line Breaks From TextArea When Writing To MySQL
why make is sooooo hard people when it can be soooo easy :)
//here is the pull from the form
$your_form_text = $_POST['your_form_text'];
//line 1 fixes the line breaks - line 2 the slashes
$your_form_text = nl2br($your_form_text);
$your_form_text = stripslashes($your_form_text);
//email away
$message = "Comments: $your_form_text";
mail("[email protected]", "Website Form Submission", $message, $headers);
you will obviously need headers and likely have more fields, but this is your textarea take care of
Running unittest with typical test directory structure
Python 3+
Adding to @Pierre
Using unittest
directory structure like this:
new_project
+-- antigravity
¦ +-- __init__.py # make it a package
¦ +-- antigravity.py
+-- test
+-- __init__.py # also make test a package
+-- test_antigravity.py
To run the test module test_antigravity.py
:
$ cd new_project
$ python -m unittest test.test_antigravity
Or a single TestCase
$ python -m unittest test.test_antigravity.GravityTestCase
Mandatory don't forget the __init__.py
even if empty otherwise will not work.
Multiline TextBox multiple newline
I had the same problem. If I add one Environment.Newline I get one new line in the textbox. But if I add two Environment.Newline I get one new line.
In my web app I use a whitespace modul that removes all unnecessary white spaces. If i disable this module I get two new lines in my textbox. Hope that helps.
jQuery send string as POST parameters
I see that they did not understand your question.
Answer is: add "traditional"
parameter to your ajax call like this:
$.ajax({
traditional: true,
type: "POST",
url: url,
data: custom,
success: ok,
dataType: "json"
});
And it will work with parameters PASSED AS A STRING.
Tomcat request timeout
You can set the default time out in the server.xml
<Connector URIEncoding="UTF-8"
acceptCount="100"
connectionTimeout="20000"
disableUploadTimeout="true"
enableLookups="false"
maxHttpHeaderSize="8192"
maxSpareThreads="75"
maxThreads="150"
minSpareThreads="25"
port="7777"
redirectPort="8443"/>
SQL Server AS statement aliased column within WHERE statement
Logical Processing Order of the SELECT statement
The following steps show the logical processing order, or binding
order, for a SELECT statement. This order determines when the objects
defined in one step are made available to the clauses in subsequent
steps. For example, if the query processor can bind to (access) the
tables or views defined in the FROM clause, these objects and their
columns are made available to all subsequent steps. Conversely,
because the SELECT clause is step 8, any column aliases or derived
columns defined in that clause cannot be referenced by preceding
clauses. However, they can be referenced by subsequent clauses such as
the ORDER BY clause. Note that the actual physical execution of the
statement is determined by the query processor and the order may vary
from this list.
- FROM
- ON
- JOIN
- WHERE
- GROUP BY
- WITH CUBE or WITH ROLLUP
- HAVING
- SELECT
- DISTINCT
- ORDER BY
- TOP
Source: http://msdn.microsoft.com/en-us/library/ms189499%28v=sql.110%29.aspx
Upload failed You need to use a different version code for your APK because you already have one with version code 2
In Flutter
Update version:1.0.0+1 in pubspec.yaml.
The default version number of the app is 1.0.0. To update it, navigate to the pubspec.yaml
file and update the following line:
version: 1.0.0+1
+1 (the number after the +) represents the versionCode such as 1, 2, 3, etc.
So increase it one by one, like this
version: 1.0.1+2
The version number is three numbers separated by dots, such as 1.0.0 in the example above, followed by an optional build number such as 1 in the example above, separated by a +.
Both the version and the build number may be overridden in Flutter’s build by specifying --build-name and --build-number, respectively.
In Android, build-name is used as versionName while build-number used as versionCode. For more information, see Version your app
After updating the version number in the pubspec file
, run flutter pub
get from the top of the project, or use the Pub get button in your IDE. This updates the versionName
and versionCode
in the local.properties
file, which are later updated in the build.gradle
file when you rebuild the Flutter app.
How to install python3 version of package via pip on Ubuntu?
You should install ALL dependencies:
sudo apt-get install build-essential python3-dev python3-setuptools python3-numpy python3-scipy libatlas-dev libatlas3gf-base
Install pip3(if you have installed, please look step 3):
sudo apt-get install python3-pip
Iinstall scikit-learn by pip3
pip3 install -U scikit-learn
Open your terminal and entry python3 environment, type import sklearn
to check it.
Gook Luck!
C# - Substring: index and length must refer to a location within the string
Your mistake is the parameters to Substring. The first parameter should be the start index and the second should be the length or offset from the startindex.
string newString = url.Substring(18, 7);
If the length of the substring can vary you need to calculate the length.
Something in the direction of (url.Length - 18) - 4
(or url.Length - 22
)
In the end it will look something like this
string newString = url.Substring(18, url.Length - 22);
Properties private set;
Depending on the scope of my application, I like to put the object hydration mechanisms in the object itself. I'll wrap the data reader with a custom object and pass it a delegate that gets executed once the query returns. The delegate gets passed the DataReader. Then, since I'm in my smart business object, I can hydrate away with my private setters.
Edit for Pseudo-Code
The "DataAccessWrapper" wraps all of the connection and object lifecycle management for me. So, when I call "ExecuteDataReader," it creates the connection, with the passed proc (there's an overload for params,) executes it, executes the delegate and then cleans up after itself.
public class User
{
public static List<User> GetAllUsers()
{
DataAccessWrapper daw = new DataAccessWrapper();
return (List<User>)(daw.ExecuteDataReader("MyProc", new ReaderDelegate(ReadList)));
}
protected static object ReadList(SQLDataReader dr)
{
List<User> retVal = new List<User>();
while(dr.Read())
{
User temp = new User();
temp.Prop1 = dr.GetString("Prop1");
temp.Prop2 = dr.GetInt("Prop2");
retVal.Add(temp);
}
return retVal;
}
}
Move an item inside a list?
I profiled a few methods to move an item within the same list with timeit. Here are the ones to use if j>i:
+---------------------------------+
¦ 14.4usec ¦ x[i:i]=x.pop(j), ¦
¦ 14.5usec ¦ x[i:i]=[x.pop(j)] ¦
¦ 15.2usec ¦ x.insert(i,x.pop(j)) ¦
+---------------------------------+
and here the ones to use if j<=i:
+--------------------------------------+
¦ 14.4usec ¦ x[i:i]=x[j],;del x[j] ¦
¦ 14.4usec ¦ x[i:i]=[x[j]];del x[j] ¦
¦ 15.4usec ¦ x.insert(i,x[j]);del x[j] ¦
+--------------------------------------+
Not a huge difference if you only use it a few times, but if you do heavy stuff like manual sorting, it's important to take the fastest one. Otherwise, I'd recommend just taking the one that you think is most readable.
how to use DEXtoJar
Step 1 extract the contents of dex2jar.*.*.zip file
Step 2 copy your .dex file to the extracted directory
Step 3 execute dex2jar.bat <.dex filename> on windows, or ./dex2jar.sh <.dex filename> on linux
__FILE__, __LINE__, and __FUNCTION__ usage in C++
C++20 std::source_location
C++ has finally added a non-macro option, and it will likely dominate at some point in the future when C++20 becomes widespread:
The documentation says:
constexpr const char* function_name() const noexcept;
6 Returns: If this object represents a position in the body of a function,
returns an implementation-defined NTBS that should correspond to the
function name. Otherwise, returns an empty string.
where NTBS means "Null Terminated Byte String".
I'll give it a try when support arrives to GCC, GCC 9.1.0 with g++-9 -std=c++2a
still doesn't support it.
https://en.cppreference.com/w/cpp/utility/source_location claims usage will be like:
#include <iostream>
#include <string_view>
#include <source_location>
void log(std::string_view message,
const std::source_location& location std::source_location::current()
) {
std::cout << "info:"
<< location.file_name() << ":"
<< location.line() << ":"
<< location.function_name() << " "
<< message << '\n';
}
int main() {
log("Hello world!");
}
Possible output:
info:main.cpp:16:main Hello world!
__PRETTY_FUNCTION__
vs __FUNCTION__
vs __func__
vs std::source_location::function_name
Answered at: What's the difference between __PRETTY_FUNCTION__, __FUNCTION__, __func__?
Error in file(file, "rt") : cannot open the connection
Error in file(file, "rt")
Created a .r file and saved it in Desktop together with a sample_10000.csv file.
Once trying to read it
heisenberg <- read.csv(file="sample_100000.csv")
was getting the same error as you
heisenberg <- read.csv(file="sample_10000")
Error in file(file, "rt") : cannot open the connection In addition: Warning message:
In file(file, "rt") : cannot open file 'sample_10000': No such file or
directory
I knew at least two ways to fix this, one using the absolute path and the other changing the working directory.
Absolute path
I fixed it adding the absolute path to the file, more precisely
heisenberg <- read.csv(file="C:/Users/tiago/Desktop/sample_100000.csv")
Working directory
This error shows up because RStudio has a specific working directory defined which isn't necessarily the place the .r file is at.
So, to fix using this approach I've gone to Session > Set Working Directory > Chose Directory (CTRL + Shift + H) and selected Desktop, where the .csv file was at. That way running the following command also worked
heisenberg <- read.csv(file="sample_100000.csv")
nvm keeps "forgetting" node in new terminal session
run this after you installed any version,
n=$(which node);n=${n%/bin/node}; chmod -R 755 $n/bin/*; sudo cp -r $n/{bin,lib,share} /usr/local
This command is copying whatever version of node you have active via nvm into the /usr/local/ directory and setting the permissions so that all users can access them.
Why should we typedef a struct so often in C?
At all, in C language, struct/union/enum are macro instruction processed by the C language preprocessor (do not mistake with the preprocessor that treat "#include" and other)
so :
struct a
{
int i;
};
struct b
{
struct a;
int i;
int j;
};
struct b is expended as something like this :
struct b
{
struct a
{
int i;
};
int i;
int j;
}
and so, at compile time it evolve on stack as something like:
b:
int ai
int i
int j
that also why it's dificult to have selfreferent structs, C preprocessor round in a déclaration loop that can't terminate.
typedef are type specifier, that means only C compiler process it and it can do like he want for optimise assembler code implementation. It also dont expend member of type par stupidly like préprocessor do with structs but use more complex reference construction algorithm, so construction like :
typedef struct a A; //anticipated declaration for member declaration
typedef struct a //Implemented declaration
{
A* b; // member declaration
}A;
is permited and fully functional. This implementation give also access to compilator type conversion and remove some bugging effects when execution thread leave the application field of initialisation functions.
This mean that in C typedefs are more near as C++ class than lonely structs.
Send email using the GMail SMTP server from a PHP page
Send Mail using phpMailer library through Gmail
Please donwload library files from Github
<?php
/**
* This example shows settings to use when sending via Google's Gmail servers.
*/
//SMTP needs accurate times, and the PHP time zone MUST be set
//This should be done in your php.ini, but this is how to do it if you don't have access to that
date_default_timezone_set('Etc/UTC');
require '../PHPMailerAutoload.php';
//Create a new PHPMailer instance
$mail = new PHPMailer;
//Tell PHPMailer to use SMTP
$mail->isSMTP();
//Enable SMTP debugging
// 0 = off (for production use)
// 1 = client messages
// 2 = client and server messages
$mail->SMTPDebug = 2;
//Ask for HTML-friendly debug output
$mail->Debugoutput = 'html';
//Set the hostname of the mail server
$mail->Host = 'smtp.gmail.com';
// use
// $mail->Host = gethostbyname('smtp.gmail.com');
// if your network does not support SMTP over IPv6
//Set the SMTP port number - 587 for authenticated TLS, a.k.a. RFC4409 SMTP submission
$mail->Port = 587;
//Set the encryption system to use - ssl (deprecated) or tls
$mail->SMTPSecure = 'tls';
//Whether to use SMTP authentication
$mail->SMTPAuth = true;
//Username to use for SMTP authentication - use full email address for gmail
$mail->Username = "[email protected]";
//Password to use for SMTP authentication
$mail->Password = "yourpassword";
//Set who the message is to be sent from
$mail->setFrom('[email protected]', 'First Last');
//Set an alternative reply-to address
$mail->addReplyTo('[email protected]', 'First Last');
//Set who the message is to be sent to
$mail->addAddress('[email protected]', 'John Doe');
//Set the subject line
$mail->Subject = 'PHPMailer GMail SMTP test';
//Read an HTML message body from an external file, convert referenced images to embedded,
//convert HTML into a basic plain-text alternative body
$mail->msgHTML(file_get_contents('contents.html'), dirname(__FILE__));
//Replace the plain text body with one created manually
$mail->AltBody = 'This is a plain-text message body';
//Attach an image file
$mail->addAttachment('images/phpmailer_mini.png');
//send the message, check for errors
if (!$mail->send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
} else {
echo "Message sent!";
}
Hidden Features of Xcode
Debugging - how to use GDB
Being new to this still, I find trapping and identifying faults a rather
daunting job. The console, despite it being a powerful tool, usually
does not yield very intuitive results and knowing what you are
looking at in the debugger can be equally difficult to
understand. With the help of some of they guys
on Stack Overflow and the good article about
debugging that can be found at
Cocoa With Love it becomes a little more friendly.
Practical uses of git reset --soft?
I use it to amend more than just the last commit.
Let's say I made a mistake in commit A and then made commit B. Now I can only amend B.
So I do git reset --soft HEAD^^
, I correct and re-commit A and then re-commit B.
Of course, it's not very convenient for large commits… but you shouldn't do large commits anyway ;-)
Disable arrow key scrolling in users browser
Summary
Simply prevent the default browser action:
window.addEventListener("keydown", function(e) {
// space and arrow keys
if([32, 37, 38, 39, 40].indexOf(e.code) > -1) {
e.preventDefault();
}
}, false);
If you need to support Internet Explorer or other older browsers, use e.keyCode
instead of e.code
, but keep in mind that keyCode
is deprecated.
Original answer
I used the following function in my own game:
var keys = {};
window.addEventListener("keydown",
function(e){
keys[e.code] = true;
switch(e.code){
case 37: case 39: case 38: case 40: // Arrow keys
case 32: e.preventDefault(); break; // Space
default: break; // do not block other keys
}
},
false);
window.addEventListener('keyup',
function(e){
keys[e.code] = false;
},
false);
The magic happens in e.preventDefault();
. This will block the default action of the event, in this case moving the viewpoint of the browser.
If you don't need the current button states you can simply drop keys
and just discard the default action on the arrow keys:
var arrow_keys_handler = function(e) {
switch(e.code){
case 37: case 39: case 38: case 40: // Arrow keys
case 32: e.preventDefault(); break; // Space
default: break; // do not block other keys
}
};
window.addEventListener("keydown", arrow_keys_handler, false);
Note that this approach also enables you to remove the event handler later if you need to re-enable arrow key scrolling:
window.removeEventListener("keydown", arrow_keys_handler, false);
References
Responsive css background images
by this code your background image go center and fix it size whatever your div size change , good for small , big , normal sizes , best for all , i use it for my projects where my background size or div size can change
background-repeat:no-repeat;
-webkit-background-size:cover;
-moz-background-size:cover;
-o-background-size:cover;
background-size:cover;
background-position:center;
Have a fixed position div that needs to scroll if content overflows
Leaving an answer for anyone looking to do something similar but in a horizontal direction, like I wanted to.
Tweaking @strider820's answer like below will do the magic:
.fixed-content { //comments showing what I replaced.
left:0; //top: 0;
right:0; //bottom:0;
position:fixed;
overflow-y:hidden; //overflow-y:scroll;
overflow-x:auto; //overflow-x:hidden;
}
That's it. Also check this comment where @train explained using overflow:auto
over overflow:scroll
.
How to set initial value and auto increment in MySQL?
First you need to add column for auto increment
alter table users add column id int(5) NOT NULL AUTO_INCREMENT FIRST
This query for add column at first.
Now you have to reset auto increment initial value. So use this query
alter table users AUTO_INCREMENT=1001
Now your table started with 1001
passing argument to DialogFragment
In my case, none of the code above with bundle-operate
works; Here is my decision (I don't know if it is proper code or not, but it works in my case):
public class DialogMessageType extends DialogFragment {
private static String bodyText;
public static DialogMessageType addSomeString(String temp){
DialogMessageType f = new DialogMessageType();
bodyText = temp;
return f;
};
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final String[] choiseArray = {"sms", "email"};
String title = "Send text via:";
final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(title).setItems(choiseArray, itemClickListener);
builder.setCancelable(true);
return builder.create();
}
DialogInterface.OnClickListener itemClickListener = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
switch (which){
case 0:
prepareToSendCoordsViaSMS(bodyText);
dialog.dismiss();
break;
case 1:
prepareToSendCoordsViaEmail(bodyText);
dialog.dismiss();
break;
default:
break;
}
}
};
[...]
}
public class SendObjectActivity extends FragmentActivity {
[...]
DialogMessageType dialogMessageType = DialogMessageType.addSomeString(stringToSend);
dialogMessageType.show(getSupportFragmentManager(),"dialogMessageType");
[...]
}
Angular 2: Passing Data to Routes?
It changes in angular 2.1.0
In something.module.ts
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { BlogComponent } from './blog.component';
import { AddComponent } from './add/add.component';
import { EditComponent } from './edit/edit.component';
import { RouterModule } from '@angular/router';
import { MaterialModule } from '@angular/material';
import { FormsModule } from '@angular/forms';
const routes = [
{
path: '',
component: BlogComponent
},
{
path: 'add',
component: AddComponent
},
{
path: 'edit/:id',
component: EditComponent,
data: {
type: 'edit'
}
}
];
@NgModule({
imports: [
CommonModule,
RouterModule.forChild(routes),
MaterialModule.forRoot(),
FormsModule
],
declarations: [BlogComponent, EditComponent, AddComponent]
})
export class BlogModule { }
To get the data or params in edit component
import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute, Params, Data } from '@angular/router';
@Component({
selector: 'app-edit',
templateUrl: './edit.component.html',
styleUrls: ['./edit.component.css']
})
export class EditComponent implements OnInit {
constructor(
private route: ActivatedRoute,
private router: Router
) { }
ngOnInit() {
this.route.snapshot.params['id'];
this.route.snapshot.data['type'];
}
}
Difference between variable declaration syntaxes in Javascript (including global variables)?
In global scope there is no semantic difference.
But you really should avoid a=0
since your setting a value to an undeclared variable.
Also use closures to avoid editing global scope at all
(function() {
// do stuff locally
// Hoist something to global scope
window.someGlobal = someLocal
}());
Always use closures and always hoist to global scope when its absolutely neccesary. You should be using asynchronous event handling for most of your communication anyway.
As @AvianMoncellor mentioned there is an IE bug with var a = foo
only declaring a global for file scope. This is an issue with IE's notorious broken interpreter. This bug does sound familiar so it's probably true.
So stick to window.globalName = someLocalpointer
Using .Select and .Where in a single LINQ statement
Did you add the Select()
after the Where()
or before?
You should add it after, because of the concurrency logic:
1 Take the entire table
2 Filter it accordingly
3 Select only the ID's
4 Make them distinct.
If you do a Select first, the Where clause can only contain the ID attribute because all other attributes have already been edited out.
Update: For clarity, this order of operators should work:
db.Items.Where(x=> x.userid == user_ID).Select(x=>x.Id).Distinct();
Probably want to add a .toList()
at the end but that's optional :)
How to script FTP upload and download?
I had this same issue, and solved it with a solution similar to what Cheeso provided, above.
"doesn't work, says password is srequire, tried it a couple different ways "
Yep, that's because FTP sessions via a command file don't require the username to be prefaced with the string "user". Drop that, and try it.
Or, you could be seeing this because your FTP command file is not properly encoded (that bit me, too). That's the crappy part about generating a FTP command file at runtime. Powershell's out-file cmdlet does not have an encoding option that Windows FTP will accept (at least not one that I could find).
Regardless, as doing a WebClient.DownloadFile is the way to go.
Effect of using sys.path.insert(0, path) and sys.path(append) when loading modules
I'm quite a beginner in Python and I found the answer of Anand was very good but quite complicated to me, so I try to reformulate :
1) insert
and append
methods are not specific to sys.path
and as in other languages they add an item into a list or array and :
* append(item)
add item
to the end of the list,
* insert(n, item)
inserts the item
at the nth position in the list (0
at the beginning, 1
after the first element, etc ...).
2) As Anand said, python search the import files in each directory of the path in the order of the path, so :
* If you have no file name collisions, the order of the path has no impact,
* If you look after a function already defined in the path and you use append
to add your path, you will not get your function but the predefined one.
But I think that it is better to use append
and not insert
to not overload the standard behaviour of Python, and use non-ambiguous names for your files and methods.
Forbidden You don't have permission to access /wp-login.php on this server
Change .htaccess file code by this code :
# BEGIN WordPress
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
# uploaded files
RewriteRule ^([_0-9a-zA-Z-]+/)?files/(.+) wp-includes/ms-files.php?file=$2 [L]
# add a trailing slash to /wp-admin
RewriteRule ^([_0-9a-zA-Z-]+/)?wp-admin$ $1wp-admin/ [R=301,L]
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]
RewriteRule ^[_0-9a-zA-Z-]+/(wp-(content|admin|includes).*) $1 [L]
RewriteRule ^[_0-9a-zA-Z-]+/(.*\.php)$ $1 [L]
RewriteRule . index.php [L]
# END WordPress
How to make the checkbox unchecked by default always
jQuery
$('input[type=checkbox]').removeAttr('checked');
Or
<!-- checked -->
<input type='checkbox' name='foo' value='bar' checked=''/>
<!-- unchecked -->
<input type='checkbox' class='inputUncheck' name='foo' value='bar' checked=''/>
<input type='checkbox' class='inputUncheck' name='foo' value='bar'/>
+
$('input.inputUncheck').removeAttr('checked');
Iterating through a variable length array
You've specifically mentioned a "variable-length array" in your question, so neither of the existing two answers (as I write this) are quite right.
Java doesn't have any concept of a "variable-length array", but it does have Collections, which serve in this capacity. Any collection (technically any "Iterable", a supertype of Collections) can be looped over as simply as this:
Collection<Thing> things = ...;
for (Thing t : things) {
System.out.println(t);
}
EDIT: it's possible I misunderstood what he meant by 'variable-length'. He might have just meant it's a fixed length but not every instance is the same fixed length. In which case the existing answers would be fine. I'm not sure what was meant.
Read/write to file using jQuery
Cookies are your best bet. Look for the jquery cookie plugin.
Cookies are designed for this sort of situation -- you want to keep some information about this client on client side. Just be aware that cookies are passed back and forth on every web request so you can't store large amounts of data in there. But just a simple answer to a question should be fine.
How do I print colored output with Python 3?
I use the colors module. Clone the git repository, run the setup.py
and you're good. You can then print text with colors very easily like this:
import colors
print(colors.red('this is red'))
print(colors.green('this is green'))
This works on the command line, but might need further configuration for IDLE.
Xcode "Build and Archive" from command line
Improving on Vincent's answer, I wrote a script to do that: xcodearchive
It allows you to archive (generate an ipa) your project via the command line.
Think of it like the sister of the xcodebuild
command, but for archiving.
Code is available on github: http://github.com/gcerquant/xcodearchive
One option of the script is to enable the archiving of the dSYM symbols in a timestamped archive. No excuse to not keep the symbols anymore, and not be able to symbolicate the crash log you might later receive.
JQuery string contains check
You can use javascript's indexOf function.
_x000D_
_x000D_
var str1 = "ABCDEFGHIJKLMNOP";_x000D_
var str2 = "DEFG";_x000D_
if(str1.indexOf(str2) != -1){_x000D_
console.log(str2 + " found");_x000D_
}
_x000D_
_x000D_
_x000D_
Pass react component as props
As noted in the accepted answer - you can use the special { props.children } property. However - you can just pass a component as a prop as the title requests. I think this is cleaner sometimes as you might want to pass several components and have them render in different places. Here's the react docs with an example of how to do it:
https://reactjs.org/docs/composition-vs-inheritance.html
Make sure you are actually passing a component and not an object (this tripped me up initially).
The code is simply this:
const Parent = () => {
return (
<Child componentToPassDown={<SomeComp />} />
)
}
const Child = ({ componentToPassDown }) => {
return (
<>
{componentToPassDown}
</>
)
}
How to calculate age in T-SQL with years, months, and days
The same sort of thing as a function.
create function [dbo].[Age](@dayOfBirth datetime, @today datetime)
RETURNS varchar(100)
AS
Begin
DECLARE @thisYearBirthDay datetime
DECLARE @years int, @months int, @days int
set @thisYearBirthDay = DATEADD(year, DATEDIFF(year, @dayOfBirth, @today), @dayOfBirth)
set @years = DATEDIFF(year, @dayOfBirth, @today) - (CASE WHEN @thisYearBirthDay > @today THEN 1 ELSE 0 END)
set @months = MONTH(@today - @thisYearBirthDay) - 1
set @days = DAY(@today - @thisYearBirthDay) - 1
return cast(@years as varchar(2)) + ' years,' + cast(@months as varchar(2)) + ' months,' + cast(@days as varchar(3)) + ' days'
end
rejected master -> master (non-fast-forward)
If git pull
does not help, then probably you have pushed your changes (A) and after that had used git commit --amend
to add some more changes (B). Therefore, git thinks that you can lose the history - it interprets B as a different commit despite it contains all changes from A.
B
/
---X---A
If nobody changes the repo after A
, then you can do git push --force
.
However, if there are changes after A
from other person:
B
/
---X---A---C
then you must rebase that persons changes from A
to B
(C
->D
).
B---D
/
---X---A---C
or fix the problem manually. I didn't think how to do that yet.
Easy way to dismiss keyboard?
You may also need to override UIViewController disablesAutomaticKeyboardDismissal to get this to work in some cases. This may have to be done on the UINavigationController if you have one.
2D character array initialization in C
char **options[2][100];
declares a size-2 array of size-100 arrays of pointers to pointers to char
. You'll want to remove one *
. You'll also want to put your string literals in double quotes.
Can you append strings to variables in PHP?
This is because PHP uses the period character .
for string concatenation, not the plus character +
. Therefore to append to a string you want to use the .=
operator:
for ($i=1;$i<=100;$i++)
{
$selectBox .= '<option value="' . $i . '">' . $i . '</option>';
}
$selectBox .= '</select>';
How to filter rows containing a string pattern from a Pandas dataframe
If you want to set the column you filter on as a new index, you could also consider to use .filter
; if you want to keep it as a separate column then str.contains
is the way to go.
Let's say you have
df = pd.DataFrame({'vals': [1, 2, 3, 4, 5], 'ids': [u'aball', u'bball', u'cnut', u'fball', 'ballxyz']})
ids vals
0 aball 1
1 bball 2
2 cnut 3
3 fball 4
4 ballxyz 5
and your plan is to filter all rows in which ids
contains ball
AND set ids
as new index, you can do
df.set_index('ids').filter(like='ball', axis=0)
which gives
vals
ids
aball 1
bball 2
fball 4
ballxyz 5
But filter
also allows you to pass a regex, so you could also filter only those rows where the column entry ends with ball
. In this case you use
df.set_index('ids').filter(regex='ball$', axis=0)
vals
ids
aball 1
bball 2
fball 4
Note that now the entry with ballxyz
is not included as it starts with ball
and does not end with it.
If you want to get all entries that start with ball
you can simple use
df.set_index('ids').filter(regex='^ball', axis=0)
yielding
vals
ids
ballxyz 5
The same works with columns; all you then need to change is the axis=0
part. If you filter based on columns, it would be axis=1
.
textarea character limit
... onkeydown="if(value.length>500)value=value.substr(0,500); if(value.length==500)return false;" ...
It ought to work.
javascript scroll event for iPhone/iPad?
I was able to get a great solution to this problem with iScroll, with the feel of momentum scrolling and everything https://github.com/cubiq/iscroll The github doc is great, and I mostly followed it. Here's the details of my implementation.
HTML:
I wrapped the scrollable area of my content in some divs that iScroll can use:
<div id="wrapper">
<div id="scroller">
... my scrollable content
</div>
</div>
CSS:
I used the Modernizr class for "touch" to target my style changes only to touch devices (because I only instantiated iScroll on touch).
.touch #wrapper {
position: absolute;
z-index: 1;
top: 0;
bottom: 0;
left: 0;
right: 0;
overflow: hidden;
}
.touch #scroller {
position: absolute;
z-index: 1;
width: 100%;
}
JS:
I included iscroll-probe.js from the iScroll download, and then initialized the scroller as below, where updatePosition is my function that reacts to the new scroll position.
# coffeescript
if Modernizr.touch
myScroller = new IScroll('#wrapper', probeType: 3)
myScroller.on 'scroll', updatePosition
myScroller.on 'scrollEnd', updatePosition
You have to use myScroller to get the current position now, instead of looking at the scroll offset. Here is a function taken from http://markdalgleish.com/presentations/embracingtouch/ (a super helpful article, but a little out of date now)
function getScroll(elem, iscroll) {
var x, y;
if (Modernizr.touch && iscroll) {
x = iscroll.x * -1;
y = iscroll.y * -1;
} else {
x = elem.scrollTop;
y = elem.scrollLeft;
}
return {x: x, y: y};
}
The only other gotcha was occasionally I would lose part of my page that I was trying to scroll to, and it would refuse to scroll. I had to add in some calls to myScroller.refresh() whenever I changed the contents of the #wrapper, and that solved the problem.
EDIT: Another gotcha was that iScroll eats all the "click" events. I turned on the option to have iScroll emit a "tap" event and handled those instead of "click" events. Thankfully I didn't need much clicking in the scroll area, so this wasn't a big deal.
CSS Background image not loading
First of all, wave bye-bye to those quotes:
background-image: url(nickcage.jpg); // No quotes around the file name
Next, if your html, css and image are all in the same directory then removing the quotes should fix it.
If, however, your css or image are in subdirectories of where your html lives, you'll want to make sure you correctly path to the image:
background-image: url(../images/nickcage.jpg); // css and image live in subdorectories
background-image: url(images/nickcage.jpg); // css lives with html but images is a subdirectory
Hope it helps.
Make Div Draggable using CSS
After going down the rabbit-hole of trying to do this myself by copy-pasting various code-snippets from Stack Overflow, I would highly recommend just using the InteractJS library, which allows you to create a draggable and resizable div (somewhat) easily.
Get string between two strings in a string
Regex is overkill here.
You could use string.Split
with the overload that takes a string[]
for the delimiters but that would also be overkill.
Look at Substring
and IndexOf
- the former to get parts of a string given and index and a length and the second for finding indexed of inner strings/characters.
Display milliseconds in Excel
I've discovered in Excel 2007, if the results are a Table from an embedded query, the ss.000 does not work. I can paste the query results (from SQL Server Management Studio), and format the time just fine. But when I embed the query as a Data Connection in Excel, the format always gives .000 as the milliseconds.
How do I get a list of locked users in an Oracle database?
This suits the requirement:
select username, account_status, EXPIRY_DATE from dba_users where
username='<username>';
Output:
USERNAME ACCOUNT_STATUS EXPIRY_DA
--------------------------------------------------------------------------------
SYSTEM EXPIRED 13-NOV-17
slf4j: how to log formatted message, object array, exception
As of SLF4J 1.6.0, in the presence of multiple parameters and if the last argument in a logging statement is an exception, then SLF4J will presume that the user wants the last argument to be treated as an exception and not a simple parameter. See also the relevant FAQ entry.
So, writing (in SLF4J version 1.7.x and later)
logger.error("one two three: {} {} {}", "a", "b",
"c", new Exception("something went wrong"));
or writing (in SLF4J version 1.6.x)
logger.error("one two three: {} {} {}", new Object[] {"a", "b",
"c", new Exception("something went wrong")});
will yield
one two three: a b c
java.lang.Exception: something went wrong
at Example.main(Example.java:13)
at java.lang.reflect.Method.invoke(Method.java:597)
at ...
The exact output will depend on the underlying framework (e.g. logback, log4j, etc) as well on how the underlying framework is configured. However, if the last parameter is an exception it will be interpreted as such regardless of the underlying framework.
Can I write a CSS selector selecting elements NOT having a certain class or attribute?
The :not
negation pseudo class
The negation CSS pseudo-class, :not(X)
, is a functional notation
taking a simple selector X as an argument. It matches an element that
is not represented by the argument. X must not contain another
negation selector.
You can use :not
to exclude any subset of matched elements, ordered as you would normal CSS selectors.
Simple example: excluding by class
div:not(.class)
Would select all div
elements without the class .class
_x000D_
_x000D_
div:not(.class) {_x000D_
color: red;_x000D_
}
_x000D_
<div>Make me red!</div>_x000D_
<div class="class">...but not me...</div>
_x000D_
_x000D_
_x000D_
Complex example: excluding by type / hierarchy
:not(div) > div
Would select all div
elements which arent children of another div
_x000D_
_x000D_
div {_x000D_
color: black_x000D_
}_x000D_
:not(div) > div {_x000D_
color: red;_x000D_
}
_x000D_
<div>Make me red!</div>_x000D_
<div>_x000D_
<div>...but not me...</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_
Complex example: chaining pseudo selectors
With the notable exception of not being able to chain/nest :not
selectors and pseudo elements, you can use in conjunction with other pseudo selectors.
_x000D_
_x000D_
div {_x000D_
color: black_x000D_
}_x000D_
:not(:nth-child(2)){_x000D_
color: red;_x000D_
}
_x000D_
<div>_x000D_
<div>Make me red!</div>_x000D_
<div>...but not me...</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_
:not
is a CSS3 level selector, the main exception in terms of support is that it is IE9+
The spec also makes an interesting point:
the :not()
pseudo allows useless selectors to be written. For
instance :not(*|*)
, which represents no element at all, or
foo:not(bar)
, which is equivalent to foo
but with a higher
specificity.
Laravel Unknown Column 'updated_at'
For those who are using laravel 5 or above must use public modifier other wise it will throw an exception
Access level to App\yourModelName::$timestamps must be
public (as in class Illuminate\Database\Eloquent\Model)
public $timestamps = false;
convert string to number node.js
Not a full answer
Ok so this is just to supplement the information about parseInt, which is still very valid. Express doesn't allow the req or res objects to be modified at all (immutable). So if you want to modify/use this data effectively, you must copy it to another variable (var year = req.params.year).
Getting unique values in Excel by using formulas only
This is an oldie, and there are a few solutions out there, but I came up with a shorter and simpler formula than any other I encountered, and it might be useful to anyone passing by.
I have named the colors list Colors
(A2:A7), and the array formula put in cell C2 is this (fixed):
=IFERROR(INDEX(Colors,MATCH(SUM(COUNTIF(C$1:C1,Colors)),COUNTIF(Colors,"<"&Colors),0)),"")
Use Ctrl+Shift+Enter
to enter the formula in C2, and copy C2 down to C3:C7.
Explanation with sample data {"red"; "blue"; "red"; "green"; "blue"; "black"}:
COUNTIF(Colors,"<"&Colors)
returns an array (#1) with the count of values that are smaller then each item in the data {4;1;4;3;1;0} (black=0 items smaller, blue=1 item, red=4 items). This can be translated to a sort value for each item.
COUNTIF(C$1:C...,Colors)
returns an array (#2) with 1 for each data item that is already in the sorted result. In C2 it returns {0;0;0;0;0;0} and in C3 {0;0;0;0;0;1} because "black" is first in the sort and last in the data. In C4 {0;1;0;0;1;1} it indicates "black" and all the occurrences of "blue" are already present.
- The
SUM
returns the k-th sort value, by counting all the smaller values occurrences that are already present (sum of array #2).
MATCH
finds the first index of the k-th sort value (index in array #1).
- The
IFERROR
is only to hide the #N/A
error in the bottom cells, when the sorted unique list is complete.
To know how many unique items you have you can use this regular formula:
=SUM(IF(FREQUENCY(COUNTIF(Colors,"<"&Colors),COUNTIF(Colors,"<"&Colors)),1))
Extract the maximum value within each group in a dataframe
There are many possibilities to do this in R. Here are some of them:
df <- read.table(header = TRUE, text = 'Gene Value
A 12
A 10
B 3
B 5
B 6
C 1
D 3
D 4')
# aggregate
aggregate(df$Value, by = list(df$Gene), max)
aggregate(Value ~ Gene, data = df, max)
# tapply
tapply(df$Value, df$Gene, max)
# split + lapply
lapply(split(df, df$Gene), function(y) max(y$Value))
# plyr
require(plyr)
ddply(df, .(Gene), summarise, Value = max(Value))
# dplyr
require(dplyr)
df %>% group_by(Gene) %>% summarise(Value = max(Value))
# data.table
require(data.table)
dt <- data.table(df)
dt[ , max(Value), by = Gene]
# doBy
require(doBy)
summaryBy(Value~Gene, data = df, FUN = max)
# sqldf
require(sqldf)
sqldf("select Gene, max(Value) as Value from df group by Gene", drv = 'SQLite')
# ave
df[as.logical(ave(df$Value, df$Gene, FUN = function(x) x == max(x))),]
get the margin size of an element with jquery
Exemple, for :
<div id="myBlock" style="margin: 10px 0px 15px 5px:"></div>
In this js code :
var myMarginTop = $("#myBlock").css("marginBottom");
The var becomes "15px", a string.
If you want an Integer, to avoid NaN (Not a Number), there is multiple ways.
The fastest is to use native js method :
var myMarginTop = parseInt( $("#myBlock").css("marginBottom") );
Checking for empty result (php, pdo, mysql)
If you have the option of using fetchAll() then if there are no rows returned it will just be and empty array.
count($sql->fetchAll(PDO::FETCH_ASSOC))
will return the number of rows returned.
I can pass a variable from a JSP scriptlet to JSTL but not from JSTL to a JSP scriptlet without an error
Scripts are raw java embedded in the page code, and if you declare variables in your scripts, then they become local variables embedded in the page.
In contrast, JSTL works entirely with scoped attributes, either at page
, request
or session
scope. You need to rework your scriptlet to fish test
out as an attribute:
<c:set var="test" value="test1"/>
<%
String resp = "abc";
String test = pageContext.getAttribute("test");
resp = resp + test;
pageContext.setAttribute("resp", resp);
%>
<c:out value="${resp}"/>
If you look at the docs for <c:set>
, you'll see you can specify scope
as page
, request
or session
, and it defaults to page
.
Better yet, don't use scriptlets at all: they make the baby jesus cry.
How to make JQuery-AJAX request synchronous
From jQuery.ajax()
async Boolean
Default: true
By default, all requests are sent asynchronously (i.e. this is set to true by default). If you need synchronous requests, set this option to false.
So in your request, you must do async: false
instead of async: "false"
.
Update:
The return value of ajaxSubmit
is not the return value of the success: function(){...}
. ajaxSubmit
returns no value at all, which is equivalent to undefined
, which in turn evaluates to true.
And that is the reason, why the form is always submitted and is independent of sending the request synchronous or not.
If you want to submit the form only, when the response is "Successful"
, you must return false
from ajaxSubmit
and then submit the form in the success
function, as @halilb already suggested.
Something along these lines should work
function ajaxSubmit() {
var password = $.trim($('#employee_password').val());
$.ajax({
type: "POST",
url: "checkpass.php",
data: "password="+password,
success: function(response) {
if(response == "Successful")
{
$('form').removeAttr('onsubmit'); // prevent endless loop
$('form').submit();
}
}
});
return false;
}
What is the Java ?: operator called and what does it do?
Its Ternary Operator(?:)
The ternary operator is an operator that takes three arguments. The first
argument is a comparison argument, the second is the result upon a true
comparison, and the third is the result upon a false comparison.
Android emulator-5554 offline
Did you try deleting and recreating your AVD?
You can manually delete the AVD files by going to the directory they're stored in (in your user's /.android/avd subdirectory).
Android: Create spinner programmatically from array
ArrayAdapter<String>
should work.
i.e.:
Spinner spinner = new Spinner(this);
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>
(this, android.R.layout.simple_spinner_item,
spinnerArray); //selected item will look like a spinner set from XML
spinnerArrayAdapter.setDropDownViewResource(android.R.layout
.simple_spinner_dropdown_item);
spinner.setAdapter(spinnerArrayAdapter);
How to show all shared libraries used by executables in Linux?
On OS X by default there is no ldd
, objdump
or lsof
. As an alternative, try otool -L
:
$ otool -L `which openssl`
/usr/bin/openssl:
/usr/lib/libcrypto.0.9.8.dylib (compatibility version 0.9.8, current version 0.9.8)
/usr/lib/libssl.0.9.8.dylib (compatibility version 0.9.8, current version 0.9.8)
/usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 1213.0.0)
In this example, using which openssl
fills in the fully qualified path for the given executable and current user environment.
What is "X-Content-Type-Options=nosniff"?
Description
Setting a server's X-Content-Type-Options
HTTP response header to nosniff
instructs browsers to disable content or MIME sniffing which is used to override response Content-Type
headers to guess and process the data using an implicit content type. While this can be convenient in some scenarios, it can also lead to some attacks listed below. Configuring your server to return the X-Content-Type-Options
HTTP response header set to nosniff
will instruct browsers that support MIME sniffing to use the server-provided Content-Type
and not interpret the content as a different content type.
Browser Support
The X-Content-Type-Options
HTTP response header is supported in Chrome, Firefox and Edge as well as other browsers. The latest browser support is available on the Mozilla Developer Network (MDN) Browser Compatibility Table for X-Content-Type-Options:
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Content-Type-Options
Attacks Countered
MIME Confusion Attack enables attacks via user generated content sites by allowing users uploading malicious code that is then executed by browsers which will interpret the files using alternate content types, e.g. implicit application/javascript
vs. explicit text/plain
. This can result in a "drive-by download" attack which is a common attack vector for phishing. Sites that host user generated content should use this header to protect their users. This is mentioned by VeraCode and OWASP which says the following:
This reduces exposure to drive-by download attacks and sites serving user uploaded content that, by clever naming, could be treated by MSIE as executable or dynamic HTML files.
Unauthorized Hotlinking can also be enabled by Content-Type
sniffing. By hotlinking to sites with resources for one purpose, e.g. viewing, apps can rely on content-type sniffing and generate a lot of traffic on sites for another purpose where it may be against their terms of service, e.g. GitHub displays JavaScript code for viewing, but not for execution:
Some pesky non-human users (namely computers) have taken to "hotlinking" assets via the raw view feature -- using the raw URL as the src
for a <script>
or <img>
tag. The problem is that these are not static assets. The raw file view, like any other view in a Rails app, must be rendered before being returned to the user. This quickly adds up to a big toll on performance. In the past we've been forced to block popular content served this way because it put excessive strain on our servers.
When to use: Java 8+ interface default method, vs. abstract method
There's a lot more to abstract classes than default method implementations (such as private state), but as of Java 8, whenever you have the choice of either, you should go with the defender (aka. default
) method in the interface.
The constraint on the default method is that it can be implemented only in the terms of calls to other interface methods, with no reference to a particular implementation's state. So the main use case is higher-level and convenience methods.
The good thing about this new feature is that, where before you were forced to use an abstract class for the convenience methods, thus constraining the implementor to single inheritance, now you can have a really clean design with just the interface and a minimum of implementation effort forced on the programmer.
The original motivation to introduce default
methods to Java 8 was the desire to extend the Collections Framework interfaces with lambda-oriented methods without breaking any existing implementations. Although this is more relevant to the authors of public libraries, you may find the same feature useful in your project as well. You've got one centralized place where to add new convenience and you don't have to rely on how the rest of the type hierarchy looks.
Filter Pyspark dataframe column with None value
if column = None
COLUMN_OLD_VALUE
----------------
None
1
None
100
20
------------------
Use
create a temptable on data frame:
sqlContext.sql("select * from tempTable where column_old_value='None' ").show()
So use : column_old_value='None'
How do implement a breadth first traversal?
Breadth first search
Queue<TreeNode> queue = new LinkedList<BinaryTree.TreeNode>() ;
public void breadth(TreeNode root) {
if (root == null)
return;
queue.clear();
queue.add(root);
while(!queue.isEmpty()){
TreeNode node = queue.remove();
System.out.print(node.element + " ");
if(node.left != null) queue.add(node.left);
if(node.right != null) queue.add(node.right);
}
}
Find files in a folder using Java
As @Clarke said, you can use java.io.FilenameFilter
to filter the file by specific condition.
As a complementary, I'd like to show how to use java.io.FilenameFilter
to search file in current directory and its subdirectory.
The common methods getTargetFiles and printFiles are used to search files and print them.
public class SearchFiles {
//It's used in dfs
private Map<String, Boolean> map = new HashMap<String, Boolean>();
private File root;
public SearchFiles(File root){
this.root = root;
}
/**
* List eligible files on current path
* @param directory
* The directory to be searched
* @return
* Eligible files
*/
private String[] getTargetFiles(File directory){
if(directory == null){
return null;
}
String[] files = directory.list(new FilenameFilter(){
@Override
public boolean accept(File dir, String name) {
// TODO Auto-generated method stub
return name.startsWith("Temp") && name.endsWith(".txt");
}
});
return files;
}
/**
* Print all eligible files
*/
private void printFiles(String[] targets){
for(String target: targets){
System.out.println(target);
}
}
}
I will demo how to use recursive, bfs and dfs to get the job done.
Recursive:
/**
* How many files in the parent directory and its subdirectory <br>
* depends on how many files in each subdirectory and their subdirectory
*/
private void recursive(File path){
printFiles(getTargetFiles(path));
for(File file: path.listFiles()){
if(file.isDirectory()){
recursive(file);
}
}
if(path.isDirectory()){
printFiles(getTargetFiles(path));
}
}
public static void main(String args[]){
SearchFiles searcher = new SearchFiles(new File("C:\\example"));
searcher.recursive(searcher.root);
}
Breadth First Search:
/**
* Search the node's neighbors firstly before moving to the next level neighbors
*/
private void bfs(){
if(root == null){
return;
}
Queue<File> queue = new LinkedList<File>();
queue.add(root);
while(!queue.isEmpty()){
File node = queue.remove();
printFiles(getTargetFiles(node));
File[] childs = node.listFiles(new FileFilter(){
@Override
public boolean accept(File pathname) {
// TODO Auto-generated method stub
if(pathname.isDirectory())
return true;
return false;
}
});
if(childs != null){
for(File child: childs){
queue.add(child);
}
}
}
}
public static void main(String args[]){
SearchFiles searcher = new SearchFiles(new File("C:\\example"));
searcher.bfs();
}
Depth First Search:
/**
* Search as far as possible along each branch before backtracking
*/
private void dfs(){
if(root == null){
return;
}
Stack<File> stack = new Stack<File>();
stack.push(root);
map.put(root.getAbsolutePath(), true);
while(!stack.isEmpty()){
File node = stack.peek();
File child = getUnvisitedChild(node);
if(child != null){
stack.push(child);
printFiles(getTargetFiles(child));
map.put(child.getAbsolutePath(), true);
}else{
stack.pop();
}
}
}
/**
* Get unvisited node of the node
*
*/
private File getUnvisitedChild(File node){
File[] childs = node.listFiles(new FileFilter(){
@Override
public boolean accept(File pathname) {
// TODO Auto-generated method stub
if(pathname.isDirectory())
return true;
return false;
}
});
if(childs == null){
return null;
}
for(File child: childs){
if(map.containsKey(child.getAbsolutePath()) == false){
map.put(child.getAbsolutePath(), false);
}
if(map.get(child.getAbsolutePath()) == false){
return child;
}
}
return null;
}
public static void main(String args[]){
SearchFiles searcher = new SearchFiles(new File("C:\\example"));
searcher.dfs();
}
How to reload / refresh model data from the server programmatically?
You're half way there on your own. To implement a refresh, you'd just wrap what you already have in a function on the scope:
function PersonListCtrl($scope, $http) {
$scope.loadData = function () {
$http.get('/persons').success(function(data) {
$scope.persons = data;
});
};
//initial load
$scope.loadData();
}
then in your markup
<div ng-controller="PersonListCtrl">
<ul>
<li ng-repeat="person in persons">
Name: {{person.name}}, Age {{person.age}}
</li>
</ul>
<button ng-click="loadData()">Refresh</button>
</div>
As far as "accessing your model", all you'd need to do is access that $scope.persons array in your controller:
for example (just puedo code) in your controller:
$scope.addPerson = function() {
$scope.persons.push({ name: 'Test Monkey' });
};
Then you could use that in your view or whatever you'd want to do.
Declaring an HTMLElement Typescript
In JavaScript you declare variables or functions by using the keywords var, let or function. In TypeScript classes you declare class members or methods without these keywords followed by a colon and the type or interface of that class member.
It’s just syntax sugar, there is no difference between:
var el: HTMLElement = document.getElementById('content');
and:
var el = document.getElementById('content');
On the other hand, because you specify the type you get all the information of your HTMLElement object.
java: ArrayList - how can I check if an index exists?
If your index is less than the size of your list then it does exist, possibly with null
value. If index is bigger then you may call ensureCapacity()
to be able to use that index.
If you want to check if a value at your index is null
or not, call get()
How to set a text box for inputing password in winforms?
To set a text box for password input:
textBox1.PasswordChar = '*';
you can also change this property in design time by editing properties of the text box.
To show if "Capslock is ON":
using System;
using System.Windows.Forms;
//...
if (Control.IsKeyLocked(Keys.CapsLock)) {
MessageBox.Show("The Caps Lock key is ON.");
}
OpenCV C++/Obj-C: Detecting a sheet of paper / Square Detection
This is a recurring subject in Stackoverflow and since I was unable to find a relevant implementation I decided to accept the challenge.
I made some modifications to the squares demo present in OpenCV and the resulting C++ code below is able to detect a sheet of paper in the image:
void find_squares(Mat& image, vector<vector<Point> >& squares)
{
// blur will enhance edge detection
Mat blurred(image);
medianBlur(image, blurred, 9);
Mat gray0(blurred.size(), CV_8U), gray;
vector<vector<Point> > contours;
// find squares in every color plane of the image
for (int c = 0; c < 3; c++)
{
int ch[] = {c, 0};
mixChannels(&blurred, 1, &gray0, 1, ch, 1);
// try several threshold levels
const int threshold_level = 2;
for (int l = 0; l < threshold_level; l++)
{
// Use Canny instead of zero threshold level!
// Canny helps to catch squares with gradient shading
if (l == 0)
{
Canny(gray0, gray, 10, 20, 3); //
// Dilate helps to remove potential holes between edge segments
dilate(gray, gray, Mat(), Point(-1,-1));
}
else
{
gray = gray0 >= (l+1) * 255 / threshold_level;
}
// Find contours and store them in a list
findContours(gray, contours, CV_RETR_LIST, CV_CHAIN_APPROX_SIMPLE);
// Test contours
vector<Point> approx;
for (size_t i = 0; i < contours.size(); i++)
{
// approximate contour with accuracy proportional
// to the contour perimeter
approxPolyDP(Mat(contours[i]), approx, arcLength(Mat(contours[i]), true)*0.02, true);
// Note: absolute value of an area is used because
// area may be positive or negative - in accordance with the
// contour orientation
if (approx.size() == 4 &&
fabs(contourArea(Mat(approx))) > 1000 &&
isContourConvex(Mat(approx)))
{
double maxCosine = 0;
for (int j = 2; j < 5; j++)
{
double cosine = fabs(angle(approx[j%4], approx[j-2], approx[j-1]));
maxCosine = MAX(maxCosine, cosine);
}
if (maxCosine < 0.3)
squares.push_back(approx);
}
}
}
}
}
After this procedure is executed, the sheet of paper will be the largest square in vector<vector<Point> >
:
I'm letting you write the function to find the largest square. ;)
Transform only one axis to log10 scale with ggplot2
The simplest is to just give the 'trans' (formerly 'formatter' argument the name of the log function:
m + geom_boxplot() + scale_y_continuous(trans='log10')
EDIT:
Or if you don't like that, then either of these appears to give different but useful results:
m <- ggplot(diamonds, aes(y = price, x = color), log="y")
m + geom_boxplot()
m <- ggplot(diamonds, aes(y = price, x = color), log10="y")
m + geom_boxplot()
EDIT2 & 3:
Further experiments (after discarding the one that attempted successfully to put "$" signs in front of logged values):
fmtExpLg10 <- function(x) paste(round_any(10^x/1000, 0.01) , "K $", sep="")
ggplot(diamonds, aes(color, log10(price))) +
geom_boxplot() +
scale_y_continuous("Price, log10-scaling", trans = fmtExpLg10)
Note added mid 2017 in comment about package syntax change:
scale_y_continuous(formatter = 'log10') is now scale_y_continuous(trans = 'log10') (ggplot2 v2.2.1)
Computed / calculated / virtual / derived columns in PostgreSQL
YES you can!! The solution should be easy, safe, and performant...
I'm new to postgresql, but it seems you can create computed columns by using an expression index, paired with a view (the view is optional, but makes makes life a bit easier).
Suppose my computation is md5(some_string_field)
, then I create the index as:
CREATE INDEX some_string_field_md5_index ON some_table(MD5(some_string_field));
Now, any queries that act on MD5(some_string_field)
will use the index rather than computing it from scratch. For example:
SELECT MAX(some_field) FROM some_table GROUP BY MD5(some_string_field);
You can check this with explain.
However at this point you are relying on users of the table knowing exactly how to construct the column. To make life easier, you can create a VIEW
onto an augmented version of the original table, adding in the computed value as a new column:
CREATE VIEW some_table_augmented AS
SELECT *, MD5(some_string_field) as some_string_field_md5 from some_table;
Now any queries using some_table_augmented
will be able to use some_string_field_md5
without worrying about how it works..they just get good performance. The view doesn't copy any data from the original table, so it is good memory-wise as well as performance-wise. Note however that you can't update/insert into a view, only into the source table, but if you really want, I believe you can redirect inserts and updates to the source table using rules (I could be wrong on that last point as I've never tried it myself).
Edit: it seems if the query involves competing indices, the planner engine may sometimes not use the expression-index at all. The choice seems to be data dependant.
Compare two files and write it to "match" and "nomatch" files
In Eztrieve it's really easy, below is an example how you could code it:
//STEP01 EXEC PGM=EZTPA00
//FILEA DD DSN=FILEA,DISP=SHR
//FILEB DD DSN=FILEB,DISP=SHR
//FILEC DD DSN=FILEC.DIF,
// DISP=(NEW,CATLG,DELETE),
// SPACE=(CYL,(100,50),RLSE),
// UNIT=PRMDA,
// DCB=(RECFM=FB,LRECL=5200,BLKSIZE=0)
//SYSOUT DD SYSOUT=*
//SRTMSG DD SYSOUT=*
//SYSPRINT DD SYSOUT=*
//SYSIN DD *
FILE FILEA
FA-KEY 1 7 A
FA-REC1 8 10 A
FA-REC2 18 5 A
FILE FILEB
FB-KEY 1 7 A
FB-REC1 8 10 A
FB-REC2 18 5 A
FILE FILEC
FILE FILED
FD-KEY 1 7 A
FD-REC1 8 10 A
FD-REC2 18 5 A
JOB INPUT (FILEA KEY FA-KEY FILEB KEY FB-KEY)
IF MATCHED
FD-KEY = FB-KEY
FD-REC1 = FA-REC1
FD-REC2 = FB-REC2
PUT FILED
ELSE
IF FILEA
PUT FILEC FROM FILEA
ELSE
PUT FILEC FROM FILEB
END-IF
END-IF
/*
How to assign name for a screen?
To start a new session
screen -S your_session_name
To rename an existing session
Ctrl+a, : sessionname YOUR_SESSION_NAME Enter
You must be inside the session
.c vs .cc vs. .cpp vs .hpp vs .h vs .cxx
I use ".hpp" for C++ headers and ".h" for C language headers.
The ".hpp" reminds me that the file contains statements for
the C++ language which are not valid for the C language, such
as "class" declarations.
How to fill the whole canvas with specific color?
You know what, there is an entire library for canvas graphics. It is called p5.js
You can add it with just a single line in your head element and an additional sketch.js file.
Do this to your html and body tags first:
<html style="margin:0 ; padding:0">
<body style="margin:0 ; padding:0">
Add this to your head:
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.6.1/p5.js"></script>
<script type="text/javascript" src="sketch.js"></script>
The sketch.js file
function setup() {
createCanvas(windowWidth, windowHeight);
background(r, g, b);
}
Is there any native DLL export functions viewer?
DLL Export Viewer by NirSoft can be used to display exported functions in a DLL.
This utility displays the list of all exported functions and their
virtual memory addresses for the specified DLL files. You can easily
copy the memory address of the desired function, paste it into your
debugger, and set a breakpoint for this memory address. When this
function is called, the debugger will stop in the beginning of this
function.
How to crop an image in OpenCV using Python
here is some code for more robust imcrop ( a bit like in matlab )
def imcrop(img, bbox):
x1,y1,x2,y2 = bbox
if x1 < 0 or y1 < 0 or x2 > img.shape[1] or y2 > img.shape[0]:
img, x1, x2, y1, y2 = pad_img_to_fit_bbox(img, x1, x2, y1, y2)
return img[y1:y2, x1:x2, :]
def pad_img_to_fit_bbox(img, x1, x2, y1, y2):
img = np.pad(img, ((np.abs(np.minimum(0, y1)), np.maximum(y2 - img.shape[0], 0)),
(np.abs(np.minimum(0, x1)), np.maximum(x2 - img.shape[1], 0)), (0,0)), mode="constant")
y1 += np.abs(np.minimum(0, y1))
y2 += np.abs(np.minimum(0, y1))
x1 += np.abs(np.minimum(0, x1))
x2 += np.abs(np.minimum(0, x1))
return img, x1, x2, y1, y2
How do I change the string representation of a Python class?
The closest equivalent to Java's toString
is to implement __str__
for your class. Put this in your class definition:
def __str__(self):
return "foo"
You may also want to implement __repr__
to aid in debugging.
See here for more information:
Oracle query to fetch column names
SELECT * FROM <SCHEMA_NAME.TABLE_NAME> WHERE ROWNUM = 0;
--> Note that, this is Query Result, a ResultSet. This is exportable to other formats.
And, you can export the Query Result to Text
format. Export looks like below when I did SELECT * FROM SATURN.SPRIDEN WHERE ROWNUM = 0;
:
"SPRTELE_PIDM" "SPRTELE_SEQNO" "SPRTELE_TELE_CODE" "SPRTELE_ACTIVITY_DATE" "SPRTELE_PHONE_AREA" "SPRTELE_PHONE_NUMBER" "SPRTELE_PHONE_EXT" "SPRTELE_STATUS_IND" "SPRTELE_ATYP_CODE" "SPRTELE_ADDR_SEQNO" "SPRTELE_PRIMARY_IND" "SPRTELE_UNLIST_IND" "SPRTELE_COMMENT" "SPRTELE_INTL_ACCESS" "SPRTELE_DATA_ORIGIN" "SPRTELE_USER_ID" "SPRTELE_CTRY_CODE_PHONE" "SPRTELE_SURROGATE_ID" "SPRTELE_VERSION" "SPRTELE_VPDI_CODE"
DESCRIBE <TABLE_NAME>
--> Note: This is script output.
C# : Converting Base Class to Child Class
You can use the as operator to perform certain types of conversions between compatible reference types or nullable types.
SkyfilterClient c = client as SkyfilterClient;
if (c != null)
{
//do something with it
}
NetworkClient c = new SkyfilterClient() as NetworkClient; // c is not null
SkyfilterClient c2 = new NetworkClient() as SkyfilterClient; // c2 is null
Oracle SQL: Use sequence in insert with Select Statement
Assuming that you want to group the data before you generate the key with the sequence, it sounds like you want something like
INSERT INTO HISTORICAL_CAR_STATS (
HISTORICAL_CAR_STATS_ID,
YEAR,
MONTH,
MAKE,
MODEL,
REGION,
AVG_MSRP,
CNT)
SELECT MY_SEQ.nextval,
year,
month,
make,
model,
region,
avg_msrp,
cnt
FROM (SELECT '2010' year,
'12' month,
'ALL' make,
'ALL' model,
REGION,
sum(AVG_MSRP*COUNT)/sum(COUNT) avg_msrp,
sum(cnt) cnt
FROM HISTORICAL_CAR_STATS
WHERE YEAR = '2010'
AND MONTH = '12'
AND MAKE != 'ALL'
GROUP BY REGION)
PHP - Failed to open stream : No such file or directory
There are many reasons why one might run into this error and thus a good checklist of what to check first helps considerably.
Let's consider that we are troubleshooting the following line:
require "/path/to/file"
Checklist
1. Check the file path for typos
- either check manually (by visually checking the path)
or move whatever is called by require*
or include*
to its own variable, echo it, copy it, and try accessing it from a terminal:
$path = "/path/to/file";
echo "Path : $path";
require "$path";
Then, in a terminal:
cat <file path pasted>
2. Check that the file path is correct regarding relative vs absolute path considerations
- if it is starting by a forward slash "/" then it is not referring to the root of your website's folder (the document root), but to the root of your server.
- for example, your website's directory might be
/users/tony/htdocs
- if it is not starting by a forward slash then it is either relying on the include path (see below) or the path is relative. If it is relative, then PHP will calculate relatively to the path of the current working directory.
- thus, not relative to the path of your web site's root, or to the file where you are typing
- for that reason, always use absolute file paths
Best practices :
In order to make your script robust in case you move things around, while still generating an absolute path at runtime, you have 2 options :
- use
require __DIR__ . "/relative/path/from/current/file"
. The __DIR__
magic constant returns the directory of the current file.
define a SITE_ROOT
constant yourself :
- at the root of your web site's directory, create a file, e.g.
config.php
in config.php
, write
define('SITE_ROOT', __DIR__);
in every file where you want to reference the site root folder, include config.php
, and then use the SITE_ROOT
constant wherever you like :
require_once __DIR__."/../config.php";
...
require_once SITE_ROOT."/other/file.php";
These 2 practices also make your application more portable because it does not rely on ini settings like the include path.
3. Check your include path
Another way to include files, neither relatively nor purely absolutely, is to rely on the include path. This is often the case for libraries or frameworks such as the Zend framework.
Such an inclusion will look like this :
include "Zend/Mail/Protocol/Imap.php"
In that case, you will want to make sure that the folder where "Zend" is, is part of the include path.
You can check the include path with :
echo get_include_path();
You can add a folder to it with :
set_include_path(get_include_path().":"."/path/to/new/folder");
4. Check that your server has access to that file
It might be that all together, the user running the server process (Apache or PHP) simply doesn't have permission to read from or write to that file.
To check under what user the server is running you can use posix_getpwuid :
$user = posix_getpwuid(posix_geteuid());
var_dump($user);
To find out the permissions on the file, type the following command in the terminal:
ls -l <path/to/file>
and look at permission symbolic notation
5. Check PHP settings
If none of the above worked, then the issue is probably that some PHP settings forbid it to access that file.
Three settings could be relevant :
- open_basedir
- If this is set PHP won't be able to access any file outside of the specified directory (not even through a symbolic link).
- However, the default behavior is for it not to be set in which case there is no restriction
- This can be checked by either calling
phpinfo()
or by using ini_get("open_basedir")
- You can change the setting either by editing your php.ini file or your httpd.conf file
- safe mode
- if this is turned on restrictions might apply. However, this has been removed in PHP 5.4. If you are still on a version that supports safe mode upgrade to a PHP version that is still being supported.
- allow_url_fopen and allow_url_include
- this applies only to including or opening files through a network process such as http:// not when trying to include files on the local file system
- this can be checked with
ini_get("allow_url_include")
and set with ini_set("allow_url_include", "1")
Corner cases
If none of the above enabled to diagnose the problem, here are some special situations that could happen :
1. The inclusion of library relying on the include path
It can happen that you include a library, for example, the Zend framework, using a relative or absolute path. For example :
require "/usr/share/php/libzend-framework-php/Zend/Mail/Protocol/Imap.php"
But then you still get the same kind of error.
This could happen because the file that you have (successfully) included, has itself an include statement for another file, and that second include statement assumes that you have added the path of that library to the include path.
For example, the Zend framework file mentioned before could have the following include :
include "Zend/Mail/Protocol/Exception.php"
which is neither an inclusion by relative path, nor by absolute path. It is assuming that the Zend framework directory has been added to the include path.
In such a case, the only practical solution is to add the directory to your include path.
2. SELinux
If you are running Security-Enhanced Linux, then it might be the reason for the problem, by denying access to the file from the server.
To check whether SELinux is enabled on your system, run the sestatus
command in a terminal. If the command does not exist, then SELinux is not on your system. If it does exist, then it should tell you whether it is enforced or not.
To check whether SELinux policies are the reason for the problem, you can try turning it off temporarily. However be CAREFUL, since this will disable protection entirely. Do not do this on your production server.
setenforce 0
If you no longer have the problem with SELinux turned off, then this is the root cause.
To solve it, you will have to configure SELinux accordingly.
The following context types will be necessary :
httpd_sys_content_t
for files that you want your server to be able to read
httpd_sys_rw_content_t
for files on which you want read and write access
httpd_log_t
for log files
httpd_cache_t
for the cache directory
For example, to assign the httpd_sys_content_t
context type to your website root directory, run :
semanage fcontext -a -t httpd_sys_content_t "/path/to/root(/.*)?"
restorecon -Rv /path/to/root
If your file is in a home directory, you will also need to turn on the httpd_enable_homedirs
boolean :
setsebool -P httpd_enable_homedirs 1
In any case, there could be a variety of reasons why SELinux would deny access to a file, depending on your policies. So you will need to enquire into that. Here is a tutorial specifically on configuring SELinux for a web server.
3. Symfony
If you are using Symfony, and experiencing this error when uploading to a server, then it can be that the app's cache hasn't been reset, either because app/cache
has been uploaded, or that cache hasn't been cleared.
You can test and fix this by running the following console command:
cache:clear
4. Non ACSII characters inside Zip file
Apparently, this error can happen also upon calling zip->close()
when some files inside the zip have non-ASCII characters in their filename, such as "é".
A potential solution is to wrap the file name in utf8_decode()
before creating the target file.
Credits to Fran Cano for identifying and suggesting a solution to this issue
cURL equivalent in Node.js?
I had a problem sending POST data to cloud DB from IOT RaspberryPi, but after hours I managed to get it straight.
I used command prompt to do so.
sudo curl --URL http://<username>.cloudant.com/<database_name> --user <api_key>:<pass_key> -X POST -H "Content-Type:application/json" --data '{"id":"123","type":"987"}'
Command prompt will show the problems - wrong username/pass; bad request etc.
--URL database/server location (I used simple free Cloudant DB)
--user is the authentication part username:pass I entered through API pass
-X defines what command to call (PUT,GET,POST,DELETE)
-H content type - Cloudant is about document database, where JSON is used
--data content itself sorted as JSON
How to playback MKV video in web browser?
You can use this following code. work just on chrome browser.
_x000D_
_x000D_
function failed(e) {_x000D_
// video playback failed - show a message saying why_x000D_
switch (e.target.error.code) {_x000D_
case e.target.error.MEDIA_ERR_ABORTED:_x000D_
alert('You aborted the video playback.');_x000D_
break;_x000D_
case e.target.error.MEDIA_ERR_NETWORK:_x000D_
alert('A network error caused the video download to fail part-way.');_x000D_
break;_x000D_
case e.target.error.MEDIA_ERR_DECODE:_x000D_
alert('The video playback was aborted due to a corruption problem or because the video used features your browser did not support.');_x000D_
break;_x000D_
case e.target.error.MEDIA_ERR_SRC_NOT_SUPPORTED:_x000D_
alert('The video could not be loaded, either because the server or network failed or because the format is not supported.');_x000D_
break;_x000D_
default:_x000D_
alert('An unknown error occurred.');_x000D_
break;_x000D_
}_x000D_
}
_x000D_
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">_x000D_
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">_x000D_
_x000D_
<head>_x000D_
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />_x000D_
<meta name="author" content="Amin Developer!" />_x000D_
_x000D_
<title>Untitled 1</title>_x000D_
</head>_x000D_
<body>_x000D_
_x000D_
<p><video src="http://jell.yfish.us/media/Jellyfish-3-Mbps.mkv" type='video/x-matroska; codecs="theora, vorbis"' autoplay controls onerror="failed(event)" ></video></p>_x000D_
<p><a href="YOU mkv FILE LINK GOES HERE TO DOWNLOAD">Download the video file</a>.</p>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_
Vertical line using XML drawable
Depends, where you want to have the vertical line, but if you want a vertical border for example, you can have the parent view have a background a custom drawable. And you can then define the drawable like this:
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<item>
<shape
android:shape="rectangle">
<stroke android:width="1dp" android:color="#000000" />
<solid android:color="#00ffffff" />
</shape>
</item>
<item android:right="1dp">
<shape android:shape="rectangle">
<solid android:color="#00ffffff" />
</shape>
</item>
</layer-list>
This example will create a 1dp thin black line on the right side of the view, that will have this drawable as an background.
Stop mouse event propagation
If you're in a method bound to an event, simply return false:
@Component({
(...)
template: `
<a href="/test.html" (click)="doSomething()">Test</a>
`
})
export class MyComp {
doSomething() {
(...)
return false;
}
}
mailto link multiple body lines
- Use a single
body
parameter within the mailto
string
- Use
%0D%0A
as newline
The mailto
URI Scheme is specified by by RFC2368 (July 1998) and RFC6068 (October 2010).
Below is an extract of section 5 of this last RFC:
[...] line breaks in the body of a message MUST be encoded with "%0D%0A"
.
Implementations MAY add a final line break to the body of a message
even if there is no trailing "%0D%0A"
in the body [...]
See also in section 6 the example from the same RFC:
<mailto:[email protected]?body=send%20current-issue%0D%0Asend%20index>
The above mailto
body corresponds to:
send current-issue
send index
Check if value exists in column in VBA
If you want to do this without VBA, you can use a combination of IF
, ISERROR
, and MATCH
.
So if all values are in column A, enter this formula in column B:
=IF(ISERROR(MATCH(12345,A:A,0)),"Not Found","Value found on row " & MATCH(12345,A:A,0))
This will look for the value "12345" (which can also be a cell reference). If the value isn't found, MATCH
returns "#N/A" and ISERROR
tries to catch that.
If you want to use VBA, the quickest way is to use a FOR loop:
Sub FindMatchingValue()
Dim i as Integer, intValueToFind as integer
intValueToFind = 12345
For i = 1 to 500 ' Revise the 500 to include all of your values
If Cells(i,1).Value = intValueToFind then
MsgBox("Found value on row " & i)
Exit Sub
End If
Next i
' This MsgBox will only show if the loop completes with no success
MsgBox("Value not found in the range!")
End Sub
You can use Worksheet Functions in VBA, but they're picky and sometimes throw nonsensical errors. The FOR
loop is pretty foolproof.
Determine the type of an object?
type()
is a better solution than isinstance()
, particularly for booleans
:
True
and False
are just keywords that mean 1
and 0
in python. Thus,
isinstance(True, int)
and
isinstance(False, int)
both return True
. Both booleans are an instance of an integer. type()
, however, is more clever:
type(True) == int
returns False
.
How to read specific lines from a file (by line number)?
Here's my little 2 cents, for what it's worth ;)
def indexLines(filename, lines=[2,4,6,8,10,12,3,5,7,1]):
fp = open(filename, "r")
src = fp.readlines()
data = [(index, line) for index, line in enumerate(src) if index in lines]
fp.close()
return data
# Usage below
filename = "C:\\Your\\Path\\And\\Filename.txt"
for line in indexLines(filename): # using default list, specify your own list of lines otherwise
print "Line: %s\nData: %s\n" % (line[0], line[1])
What's the difference between JavaScript and JScript?
According to this article:
JavaScript is a scripting language developed by Netscape Communications designed for developing client and server Internet applications. Netscape Navigator is designed to interpret JavaScript embedded into Web pages. JavaScript is independent of Sun Microsystem's Java language.
Microsoft JScript is an open implementation of Netscape's JavaScript. JScript is a high-performance scripting language designed to create active online content for the World Wide Web. JScript allows developers to link and automate a wide variety of objects in Web pages, including ActiveX controls and Java programs. Microsoft Internet Explorer is designed to interpret JScript embedded into Web pages.
jquery $.each() for objects
Basically you need to do two loops here. The one you are doing already is iterating each element in the 0th array element.
You have programs: [ {...}, {...} ]
so programs[0] is { "name":"zonealarm", "price":"500" }
So your loop is just going over that.
You could do an outer loop over the array
$.each(data.programs, function(index) {
// then loop over the object elements
$.each(data.programs[index], function(key, value) {
console.log(key + ": " + value);
}
}
jQuery to loop through elements with the same class
In JavaScript ES6 .forEach()
over an array-like NodeList collection given by Element.querySelectorAll()
_x000D_
_x000D_
document.querySelectorAll('.testimonial').forEach( el => {_x000D_
el.style.color = 'red';_x000D_
console.log( `Element ${el.tagName} with ID #${el.id} says: ${el.textContent}` );_x000D_
});
_x000D_
<p class="testimonial" id="1">This is some text</p>_x000D_
<div class="testimonial" id="2">Lorem ipsum</div>
_x000D_
_x000D_
_x000D_
Change R default library path using .libPaths in Rprofile.site fails to work
Since most of the answers here are related to Windows & Mac OS, (and considering that I also struggled with this) I decided to post the process that helped me solve this problem on my Arch Linux setup.
Step 1:
- Do a global search of your system (e.g. ANGRYSearch) for the term
Renviron
(which is the configuration file where the settings for the user libraries are set).
- It should return only two results at the following directory paths:
/etc/R/
/usr/lib/R/etc/
NOTE: The Renviron
config files stored at 1 & 2 (above) are hot-linked to each other (which means changes made to one file will automatically be applied [ in the same form / structure ] to the other file when the file being edited is saved - [ you also need sudo
rights for saving the file post-edit ] ).
Step 2:
- Navigate into the 1st directory path (
/etc/R/
) and open the Renviron
file with your favourite text editor.
- Once inside the
Renviron
file search for the R_LIBS_USER
tag and update the text in the curly braces section to your desired directory path.
EXAMPLE:
... Change From ( original entry ):
R_LIBS_USER=${R_LIBS_USER-'~/R/x86_64-pc-linux-gnu-library/4.0'}
... Change To ( your desired entry ):
R_LIBS_USER=${R_LIBS_USER-'~/Apps/R/rUserLibs'}
Step 3:
- Save the
Renviron
file you've just edited ... DONE !!
What is the 'override' keyword in C++ used for?
override
is a C++11 keyword which means that a method is an "override" from a method from a base class. Consider this example:
class Foo
{
public:
virtual void func1();
}
class Bar : public Foo
{
public:
void func1() override;
}
If B::func1()
signature doesn't equal A::func1()
signature a compilation error will be generated because B::func1()
does not override A::func1()
, it will define a new method called func1()
instead.
Insert new item in array on any position in PHP
This can be done with array_splice
however, array_splice fails when inserting an array or using a string key. I wrote a function to handle all cases:
function array_insert(&$arr, $index, $val)
{
if (is_string($index))
$index = array_search($index, array_keys($arr));
if (is_array($val))
array_splice($arr, $index, 0, [$index => $val]);
else
array_splice($arr, $index, 0, $val);
}
Bash: Strip trailing linebreak from output
If you want to remove only the last newline, pipe through:
sed -z '$ s/\n$//'
sed
won't add a \0
to then end of the stream if the delimiter is set to NUL
via -z
, whereas to create a POSIX text file (defined to end in a \n
), it will always output a final \n
without -z
.
Eg:
$ { echo foo; echo bar; } | sed -z '$ s/\n$//'; echo tender
foo
bartender
And to prove no NUL
added:
$ { echo foo; echo bar; } | sed -z '$ s/\n$//' | xxd
00000000: 666f 6f0a 6261 72 foo.bar
To remove multiple trailing newlines, pipe through:
sed -Ez '$ s/\n+$//'
Mutex example / tutorial?
I stumbled upon this post recently and think that it needs an updated solution for the standard library's c++11 mutex (namely std::mutex).
I've pasted some code below (my first steps with a mutex - I learned concurrency on win32 with HANDLE, SetEvent, WaitForMultipleObjects etc).
Since it's my first attempt with std::mutex and friends, I'd love to see comments, suggestions and improvements!
#include <condition_variable>
#include <mutex>
#include <algorithm>
#include <thread>
#include <queue>
#include <chrono>
#include <iostream>
int _tmain(int argc, _TCHAR* argv[])
{
// these vars are shared among the following threads
std::queue<unsigned int> nNumbers;
std::mutex mtxQueue;
std::condition_variable cvQueue;
bool m_bQueueLocked = false;
std::mutex mtxQuit;
std::condition_variable cvQuit;
bool m_bQuit = false;
std::thread thrQuit(
[&]()
{
using namespace std;
this_thread::sleep_for(chrono::seconds(5));
// set event by setting the bool variable to true
// then notifying via the condition variable
m_bQuit = true;
cvQuit.notify_all();
}
);
std::thread thrProducer(
[&]()
{
using namespace std;
int nNum = 13;
unique_lock<mutex> lock( mtxQuit );
while ( ! m_bQuit )
{
while( cvQuit.wait_for( lock, chrono::milliseconds(75) ) == cv_status::timeout )
{
nNum = nNum + 13 / 2;
unique_lock<mutex> qLock(mtxQueue);
cout << "Produced: " << nNum << "\n";
nNumbers.push( nNum );
}
}
}
);
std::thread thrConsumer(
[&]()
{
using namespace std;
unique_lock<mutex> lock(mtxQuit);
while( cvQuit.wait_for(lock, chrono::milliseconds(150)) == cv_status::timeout )
{
unique_lock<mutex> qLock(mtxQueue);
if( nNumbers.size() > 0 )
{
cout << "Consumed: " << nNumbers.front() << "\n";
nNumbers.pop();
}
}
}
);
thrQuit.join();
thrProducer.join();
thrConsumer.join();
return 0;
}
Why should we include ttf, eot, woff, svg,... in a font-face
Woff is a compressed (zipped) form of the TrueType - OpenType font. It is small and can be delivered over the network like a graphic file. Most importantly, this way the font is preserved completely including rendering rule tables that very few people care about because they use only Latin script.
Take a look at [dead URL removed].
The font you see is an experimental web delivered smartfont (woff) that has thousands of combined characters making complex shapes. The underlying text is simple Latin code of romanized Singhala. (Copy and paste to Notepad and see).
Only woff can do this because nobody has this font and yet it is seen anywhere (Mac, Win, Linux and even on smartphones by all browsers except by IE. IE does not have full support for Open Types).
Hibernate Criteria Join with 3 Tables
The fetch mode only says that the association must be fetched. If you want to add restrictions on an associated entity, you must create an alias, or a subcriteria. I generally prefer using aliases, but YMMV:
Criteria c = session.createCriteria(Dokument.class, "dokument");
c.createAlias("dokument.role", "role"); // inner join by default
c.createAlias("role.contact", "contact");
c.add(Restrictions.eq("contact.lastName", "Test"));
return c.list();
This is of course well explained in the Hibernate reference manual, and the javadoc for Criteria even has examples. Read the documentation: it has plenty of useful information.
DateTime to javascript date
If you use MVC with razor
-----Razor/C#
var dt1 = DateTime.Now.AddDays(14).Date;
var dt2 = DateTime.Now.AddDays(18).Date;
var lstDateTime = new List<DateTime>();
lstDateTime.Add(dt1);
lstDateTime.Add(dt2);
---Javascript
$(function() {
var arr = []; //javascript array
@foreach (var item in lstDateTime)
{
@:arr1.push(new Date(@item.Year, @(item.Month - 1), @item.Day));
}
- 1: create the list in C# and fill it
- 2: Create an array in javascript
- 3: Use razor to iterate the list
- 4: Use @: to switch back to js and @ to switch to C#
- 5: The -1 in the month to correct the month number in js.
Good luck
Send JavaScript variable to PHP variable
As Jordan already said you have to post back the javascript variable to your server before the server can handle the value. To do this you can either program a javascript function that submits a form - or you can use ajax / jquery. jQuery.post
Maybe the most easiest approach for you is something like this
function myJavascriptFunction() {
var javascriptVariable = "John";
window.location.href = "myphpfile.php?name=" + javascriptVariable;
}
On your myphpfile.php you can use $_GET['name']
after your javascript was executed.
Regards
How to include static library in makefile
The -L
merely gives the path where to find the .a
or .so
file. What you're looking for is to add -lmine
to the LIBS
variable.
Make that -static -lmine
to force it to pick the static library (in case both static and dynamic library exist).
Addition: Suppose the path to the file has been conveyed to the linker (or compiler driver) via -L
you can also specifically tell it to link libfoo.a
by giving -l:libfoo.a
. Note that in this case the name includes the conventional lib
-prefix. You can also give a full path this way. Sometimes this is the better method to "guide" the linker to the right location.
No Persistence provider for EntityManager named
I'm some years late to the party here but I hit the same exception while trying to get Hibernate 3.5.1 working with HSQLDB and a desktop JavaFX program. I got it to work with the help of this thread and a lot of trial and error. It seems you get this error for a whole variety of problems:
No Persistence provider for EntityManager named mick
I tried building the hibernate tutorial examples but because I was using Java 10 I wasn't able to get them to build and run easily. I gave up on that, not really wanting to waste time fixing its problems. Setting up a module-info.java file (Jigsaw) is another hairball many people haven't discovered yet.
Somewhat confusing is that these (below) were the only two files I needed in my build.gradle file. The Hibernate documentation isn't clear about exactly which Jars you need to include. Entity-manager was causing confusion and is no longer required in the latest Hibernate version, and neither is javax.persistence-api. Note, I'm using Java 10 here so I had to include the jaxb-api, to get around some xml-bind errors, as well as add an entry for the java persistence module in my module-info.java file.
Build.gradle
// https://mvnrepository.com/artifact/org.hibernate/hibernate-core
compile('org.hibernate:hibernate-core:5.3.1.Final')
// https://mvnrepository.com/artifact/javax.xml.bind/jaxb-api
compile group: 'javax.xml.bind', name: 'jaxb-api', version: '2.3.0'
Module-info.java
// Used for HsqlDB - add the hibernate-core jar to build.gradle too
requires java.persistence;
With hibernate 5.3.1 you don't need to specify the provider, below, in your persistence.xml file. If one is not provided the Hibernate provider is chosen by default.
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
The persistence.xml file should be located in the correct directory so:
src/main/resources/META-INF/persistence.xml
Stepping through the hibernate source code in the Intellij debugger, where it checks for a dialect, also threw the exact same exception, because of a missing dialect property in the persistence.xml file. I added this (add the correct one for your DB type):
<property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect"/>
I still got the same exception after this, so stepping through the debugger again in Intellij revealed the test entity I was trying to persist (simple parent-child example) had missing annotations for the OneToMany, ManyToOne relationships. I fixed this and the exception went away and my entities were persisted ok.
Here's my full final persistence.xml:
<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence
http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd"
version="2.1">
<persistence-unit name="mick" transaction-type="RESOURCE_LOCAL">
<description>
Persistence unit for the JPA tutorial of the Hibernate Getting Started Guide
</description>
<!-- Provided in latest release of hibernate
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
-->
<class>com.micks.scenebuilderdemo.database.Parent</class>
<class>com.micks.scenebuilderdemo.database.Child</class>
<properties>
<property name="javax.persistence.jdbc.driver" value="org.hsqldb.jdbc.JDBCDriver"/>
<property name="javax.persistence.jdbc.url"
value="jdbc:hsqldb:file:./database/database;DB_CLOSE_DELAY=-1;MVCC=TRUE"/>
<property name="javax.persistence.jdbc.user" value="sa"/>
<property name="javax.persistence.jdbc.password" value=""/>
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.hbm2ddl.auto" value="create"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect"/>
</properties>
</persistence-unit>
</persistence>
I probably wasted about half a day on this gem. My advice would be to start very simple - a single test entity with one or two fields, as it seems like this exception can have many causes.
Get a UTC timestamp
You can use Date.UTC method to get the time stamp at the UTC timezone.
Usage:
var now = new Date;
var utc_timestamp = Date.UTC(now.getUTCFullYear(),now.getUTCMonth(), now.getUTCDate() ,
now.getUTCHours(), now.getUTCMinutes(), now.getUTCSeconds(), now.getUTCMilliseconds());
Live demo here http://jsfiddle.net/naryad/uU7FH/1/
Android: install .apk programmatically
I solved the problem. I made mistake in setData(Uri)
and setType(String)
.
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(new File(Environment.getExternalStorageDirectory() + "/download/" + "app.apk")), "application/vnd.android.package-archive");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
That is correct now, my auto-update is working. Thanks for help. =)
Edit 20.7.2016:
After a long time, I had to use this way of updating again in another project. I encountered a number of problems with old solution. A lot of things have changed in that time, so I had to do this with a different approach. Here is the code:
//get destination to update file and set Uri
//TODO: First I wanted to store my update .apk file on internal storage for my app but apparently android does not allow you to open and install
//aplication with existing package from there. So for me, alternative solution is Download directory in external storage. If there is better
//solution, please inform us in comment
String destination = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/";
String fileName = "AppName.apk";
destination += fileName;
final Uri uri = Uri.parse("file://" + destination);
//Delete update file if exists
File file = new File(destination);
if (file.exists())
//file.delete() - test this, I think sometimes it doesnt work
file.delete();
//get url of app on server
String url = Main.this.getString(R.string.update_app_url);
//set downloadmanager
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
request.setDescription(Main.this.getString(R.string.notification_description));
request.setTitle(Main.this.getString(R.string.app_name));
//set destination
request.setDestinationUri(uri);
// get download service and enqueue file
final DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
final long downloadId = manager.enqueue(request);
//set BroadcastReceiver to install app when .apk is downloaded
BroadcastReceiver onComplete = new BroadcastReceiver() {
public void onReceive(Context ctxt, Intent intent) {
Intent install = new Intent(Intent.ACTION_VIEW);
install.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
install.setDataAndType(uri,
manager.getMimeTypeForDownloadedFile(downloadId));
startActivity(install);
unregisterReceiver(this);
finish();
}
};
//register receiver for when .apk download is compete
registerReceiver(onComplete, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
Set Session variable using javascript in PHP
One simple way to set session variable is by sending request to another PHP file. Here no need to use Jquery or any other library.
Consider I have index.php file where I am creating SESSION
variable (say $_SESSION['v']=0
) if SESSION
is not created otherwise I will load other file.
Code is like this:
session_start();
if(!isset($_SESSION['v']))
{
$_SESSION['v']=0;
}
else
{
header("Location:connect.php");
}
Now in count.html I want to set this session variable to 1.
Content in count.html
function doneHandler(result) {
window.location="setSession.php";
}
In count.html javascript part, send a request to another PHP file (say setSession.php
) where i can have access to session variable.
So in setSession.php will write
session_start();
$_SESSION['v']=1;
header('Location:index.php');
Mongoose (mongodb) batch insert?
Here are both way of saving data with insertMany and save
1) Mongoose save array of documents with insertMany
in bulk
/* write mongoose schema model and export this */
var Potato = mongoose.model('Potato', PotatoSchema);
/* write this api in routes directory */
router.post('/addDocuments', function (req, res) {
const data = [/* array of object which data need to save in db */];
Potato.insertMany(data)
.then((result) => {
console.log("result ", result);
res.status(200).json({'success': 'new documents added!', 'data': result});
})
.catch(err => {
console.error("error ", err);
res.status(400).json({err});
});
})
2) Mongoose save array of documents with .save()
These documents will save parallel.
/* write mongoose schema model and export this */
var Potato = mongoose.model('Potato', PotatoSchema);
/* write this api in routes directory */
router.post('/addDocuments', function (req, res) {
const saveData = []
const data = [/* array of object which data need to save in db */];
data.map((i) => {
console.log(i)
var potato = new Potato(data[i])
potato.save()
.then((result) => {
console.log(result)
saveData.push(result)
if (saveData.length === data.length) {
res.status(200).json({'success': 'new documents added!', 'data': saveData});
}
})
.catch((err) => {
console.error(err)
res.status(500).json({err});
})
})
})
How can I split a string with a string delimiter?
.Split(new string[] { "is Marco and" }, StringSplitOptions.None)
Consider the spaces surronding "is Marco and"
. Do you want to include the spaces in your result, or do you want them removed? It's quite possible that you want to use " is Marco and "
as separator...
How to import a jar in Eclipse
first of all you will go to your project what you are created
and next right click in your mouse and select properties in the bottom
and select build in path in the left corner and add external jar file add click apply .that's it
Include PHP file into HTML file
You would have to configure your webserver to utilize PHP as handler for .html
files. This is typically done by modifying your with AddHandler
to include .html
along with .php
.
Note that this could have a performance impact as this would cause ALL .html files to be run through PHP handler even if there is no PHP involved. So you might strongly consider using .php
extension on these files and adding a redirect as necessary to route requests to specific .html URL's to their .php equivalents.
Cloning a private Github repo
As everyone aware about the process of cloning, I would like to add few more things here.
Don't worry about special character or writing "@" as "%40" see character encoding
$ git clone https://username:[email protected]/user/repo
This line can do the job
- Suppose if I have a password containing special character ( I don't know what to replace for '@' in my password)
- What if I want to use other temporary password other than my original password
To solve this issue I encourage to use GitHub Developer option to generate Access token.
I believe Access token is secure and you wont find any special character.
creating-a-personal-access-token
Now I will write the below code to access my repository.
$ git clone https://username:[email protected]/user/repo
I am just replacing my original password with Access-token,
Now I am not worried if some one see my access credential , I can regenerate the token when ever I feel.
Make sure you have checked repo Full control of private repositories
React : difference between <Route exact path="/" /> and <Route path="/" />
In this example, nothing really. The exact
param comes into play when you have multiple paths that have similar names:
For example, imagine we had a Users
component that displayed a list of users. We also have a CreateUser
component that is used to create users. The url for CreateUsers
should be nested under Users
. So our setup could look something like this:
<Switch>
<Route path="/users" component={Users} />
<Route path="/users/create" component={CreateUser} />
</Switch>
Now the problem here, when we go to http://app.com/users
the router will go through all of our defined routes and return the FIRST match it finds. So in this case, it would find the Users
route first and then return it. All good.
But, if we went to http://app.com/users/create
, it would again go through all of our defined routes and return the FIRST match it finds. React router does partial matching, so /users
partially matches /users/create
, so it would incorrectly return the Users
route again!
The exact
param disables the partial matching for a route and makes sure that it only returns the route if the path is an EXACT match to the current url.
So in this case, we should add exact
to our Users
route so that it will only match on /users
:
<Switch>
<Route exact path="/users" component={Users} />
<Route path="/users/create" component={CreateUser} />
</Switch>
The docs explain exact
in detail and give other examples.
Android Fragment no view found for ID?
Another scenario I have met.
If you use nested fragments, say a ViewPager in a Fragment with it's pages also Fragments.
When you do Fragment transaction in the inner fragment(page of ViewPager), you will need
FragmentManager fragmentManager = getActivity().getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
getActivity() is the key here.
...
How to read the post request parameters using JavaScript
One option is to set a cookie in PHP.
For example: a cookie named invalid with the value of $invalid
expiring in 1 day:
setcookie('invalid', $invalid, time() + 60 * 60 * 24);
Then read it back out in JS (using the JS Cookie plugin):
var invalid = Cookies.get('invalid');
if(invalid !== undefined) {
Cookies.remove('invalid');
}
You can now access the value from the invalid
variable in JavaScript.
Razor/CSHTML - Any Benefit over what we have?
Ex Microsoft Developer's Opinion
I worked on a core team for the MSDN website. Now, I use c# razor for ecommerce sites with my programming team and we focus heavy on jQuery front end with back end c# razor pages and LINQ-Entity memory database so the pages are 1-2 millisecond response times even on nested for loops with queries and no page caching. We don't use MVC, just plain ASP.NET with razor pages being mapped with URL Rewrite module for IIS 7, no ASPX pages or ViewState or server-side event programming at all. It doesn't have the extra (unnecessary) layers MVC puts in code constructs for the regex challenged. Less is more for us. Its all lean and mean but I give props to MVC for its testability but that's all.
Razor pages have no event life cycle like ASPX pages. Its just rendering as one requested page. C# is such a great language and Razor gets out of its way nicely to let it do its job. The anonymous typing with generics and linq make life so easy with c# and razor pages. Using Razor pages will help you think and code lighter.
One of the drawback of Razor and MVC is there is no ViewState-like persistence. I needed to implement a solution for that so I ended up writing a jQuery plugin for that here -> http://www.jasonsebring.com/dumbFormState which is an HTML 5 offline storage supported plugin for form state that is working in all major browsers now. It is just for form state currently but you can use window.sessionStorage or window.localStorage very simply to store any kind of state across postbacks or even page requests, I just bothered to make it autosave and namespace it based on URL and form index so you don't have to think about it.
How to set an "Accept:" header on Spring RestTemplate request?
I suggest using one of the exchange
methods that accepts an HttpEntity
for which you can also set the HttpHeaders
. (You can also specify the HTTP method you want to use.)
For example,
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
HttpEntity<String> entity = new HttpEntity<>("body", headers);
restTemplate.exchange(url, HttpMethod.POST, entity, String.class);
I prefer this solution because it's strongly typed, ie. exchange
expects an HttpEntity
.
However, you can also pass that HttpEntity
as a request
argument to postForObject
.
HttpEntity<String> entity = new HttpEntity<>("body", headers);
restTemplate.postForObject(url, entity, String.class);
This is mentioned in the RestTemplate#postForObject
Javadoc.
The request
parameter can be a HttpEntity
in order to add additional
HTTP headers to the request.
iPhone get SSID without private library
For iOS 13
As from iOS 13 your app also needs Core Location access in order to use the CNCopyCurrentNetworkInfo
function unless it configured the current network or has VPN configurations:
So this is what you need (see apple documentation):
- Link the CoreLocation.framework
library
- Add location-services
as a UIRequiredDeviceCapabilities
Key/Value in Info.plist
- Add a NSLocationWhenInUseUsageDescription
Key/Value in Info.plist describing why your app requires Core Location
- Add the "Access WiFi Information" entitlement for your app
Now as an Objective-C example, first check if location access has been accepted before reading the network info using CNCopyCurrentNetworkInfo
:
- (void)fetchSSIDInfo {
NSString *ssid = NSLocalizedString(@"not_found", nil);
if (@available(iOS 13.0, *)) {
if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusDenied) {
NSLog(@"User has explicitly denied authorization for this application, or location services are disabled in Settings.");
} else {
CLLocationManager* cllocation = [[CLLocationManager alloc] init];
if(![CLLocationManager locationServicesEnabled] || [CLLocationManager authorizationStatus] == kCLAuthorizationStatusNotDetermined){
[cllocation requestWhenInUseAuthorization];
usleep(500);
return [self fetchSSIDInfo];
}
}
}
NSArray *ifs = (__bridge_transfer id)CNCopySupportedInterfaces();
id info = nil;
for (NSString *ifnam in ifs) {
info = (__bridge_transfer id)CNCopyCurrentNetworkInfo(
(__bridge CFStringRef)ifnam);
NSDictionary *infoDict = (NSDictionary *)info;
for (NSString *key in infoDict.allKeys) {
if ([key isEqualToString:@"SSID"]) {
ssid = [infoDict objectForKey:key];
}
}
}
...
...
}
C# removing items from listbox
You can't modify a collection while you're iterating over it with foreach. You might try using a regular for() statement.
You may need to iterate backwards from the end of the collection to make sure you cover every item in the collection and don't accidentally overrun the end of the collection after removing an item (since the length would change). I can't remember if .NET accounts for that possibility or not.
Could not find or load main class with a Jar File
I know this is an old question, but I had this problem recently and none of the answers helped me. However, Corral's comment on Ryan Atkinson's answer did tip me off to the problem.
I had all my compiled class files in target/classes
, which are not packages in my case. I was trying to package it with jar cvfe App.jar target/classes App
, from the root directory of my project, as my App class was in the default unnamed package.
This doesn't work, as the newly created App.jar
will have the class App.class
in the directory target/classes
. If you try to run this jar with java -jar App.jar
, it will complain that it cannot find the App
class. This is because the packages inside App.jar
don't match the actual packages in the project.
This could be solved by creating the jar directly from the target/classes
directory, using jar cvfe App.jar . App
. This is rather cumbersome in my opinion.
The simple solution is to list the folders you want to add with the -C
option instead of using the default way of listing folders. So, in my case, the correct command is java cvfe App.jar App -C target/classes .
. This will directly add all files in the target/classes
directory to the root of App.jar
, thus solving the problem.
How to delete specific columns with VBA?
You were just missing the second half of the column statement telling it to remove the entire column, since most normal Ranges start with a Column Letter, it was looking for a number and didn't get one. The ":" gets the whole column, or row.
I think what you were looking for in your Range was this:
Range("C:C,F:F,I:I,L:L,O:O,R:R").Delete
Just change the column letters to match your needs.
Pandas: Appending a row to a dataframe and specify its index label
There is another solution. The next code is bad (although I think pandas needs this feature):
import pandas as pd
# empty dataframe
a = pd.DataFrame()
a.loc[0] = {'first': 111, 'second': 222}
But the next code runs fine:
import pandas as pd
# empty dataframe
a = pd.DataFrame()
a = a.append(pd.Series({'first': 111, 'second': 222}, name=0))
How to check if an email address exists without sending an email?
Assuming it's the user's address, some mail servers do allow the SMTP VRFY command to actually verify the email address against its mailboxes. Most of the major site won't give you much information; the gmail response is "if you try to mail it, we'll try to deliver it" or something clever like that.
Apache Server (xampp) doesn't run on Windows 10 (Port 80)
I know that maybe this problem was resolved but I had the same problem with different solution. For that, I am going to explain another possible solution. In my case, the port 80 was occupied by Skype (pid: 25252) and I did not know what programme was.
To see the program's pid which is using the port 80 you can use the command that other people said before:
netstat -aon | findstr 0.0:80
To kill the process using the pid (in the case that you do not know the programme) you have to open the CMD with administrator permission and use the next command:
taskkill /pid 25252
Other options with this command are here.
How to unpublish an app in Google Play Developer Console
There are two ways to delete an application you have uploaded from the Google Play Developer Console based off of the application's status within the Console. An app's status can be viewed from the "All Applications" tab listed in the furthest column. (See below)
- If your app has not yet been published to the Google Play store (ie. Is still a draft):
Select your app from the list and at the top of the page, underneath your application name, it will say DRAFT in blue with the super low-profile option to delete it just to the right. Observe below:
Click that and you're done! Keep in mind: all of the work you have put into this application so far will be deleted from the Google Play Developer Console.
- If your app has already been published and you want to remove it from the app store:
This method is similar, however it should be noted that it is not possible to permanently delete an app from your Developer Console once it has been published to the Play Store.
1) Select the application you would like to publish from the "All Applications" tab on the right of the screen
2) Below the title of the app, similar to how it was with the DRAFT application, there will be super low-profile text allowing you the option to unpublish your app from the Play Store. This process "may take a few hours to complete" as it is said by the Developer Console.
(Pictures on the way. As you have seen, my example app is still pending publication, lol)
I hope this helps to answer some people's questions.
python exception message capturing
You have to define which type of exception you want to catch. So write except Exception, e:
instead of except, e:
for a general exception (that will be logged anyway).
Other possibility is to write your whole try/except code this way:
try:
with open(filepath,'rb') as f:
con.storbinary('STOR '+ filepath, f)
logger.info('File successfully uploaded to '+ FTPADDR)
except Exception, e: # work on python 2.x
logger.error('Failed to upload to ftp: '+ str(e))
in Python 3.x and modern versions of Python 2.x use except Exception as e
instead of except Exception, e
:
try:
with open(filepath,'rb') as f:
con.storbinary('STOR '+ filepath, f)
logger.info('File successfully uploaded to '+ FTPADDR)
except Exception as e: # work on python 3.x
logger.error('Failed to upload to ftp: '+ str(e))
What is ROWS UNBOUNDED PRECEDING used for in Teradata?
It's the "frame" or "range" clause of window functions, which are part of the SQL standard and implemented in many databases, including Teradata.
A simple example would be to calculate the average amount in a frame of three days. I'm using PostgreSQL syntax for the example, but it will be the same for Teradata:
WITH data (t, a) AS (
VALUES(1, 1),
(2, 5),
(3, 3),
(4, 5),
(5, 4),
(6, 11)
)
SELECT t, a, avg(a) OVER (ORDER BY t ROWS BETWEEN 1 PRECEDING AND 1 FOLLOWING)
FROM data
ORDER BY t
... which yields:
t a avg
----------
1 1 3.00
2 5 3.00
3 3 4.33
4 5 4.00
5 4 6.67
6 11 7.50
As you can see, each average is calculated "over" an ordered frame consisting of the range between the previous row (1 preceding
) and the subsequent row (1 following
).
When you write ROWS UNBOUNDED PRECEDING
, then the frame's lower bound is simply infinite. This is useful when calculating sums (i.e. "running totals"), for instance:
WITH data (t, a) AS (
VALUES(1, 1),
(2, 5),
(3, 3),
(4, 5),
(5, 4),
(6, 11)
)
SELECT t, a, sum(a) OVER (ORDER BY t ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)
FROM data
ORDER BY t
yielding...
t a sum
---------
1 1 1
2 5 6
3 3 9
4 5 14
5 4 18
6 11 29
Here's another very good explanations of SQL window functions.
Verifying that a string contains only letters in C#
If You are a newbie then you can take reference from my code .. what i did was to put on a check so that i could only get the Alphabets and white spaces! You can Repeat the for loop after the second if statement to validate the string again
bool check = false;
Console.WriteLine("Please Enter the Name");
name=Console.ReadLine();
for (int i = 0; i < name.Length; i++)
{
if (name[i]>='a' && name[i]<='z' || name[i]==' ')
{
check = true;
}
else
{
check = false;
break;
}
}
if (check==false)
{
Console.WriteLine("Enter Valid Value");
name = Console.ReadLine();
}
How do I iterate over the words of a string?
#include<iostream>
#include<string>
#include<sstream>
#include<vector>
using namespace std;
vector<string> split(const string &s, char delim) {
vector<string> elems;
stringstream ss(s);
string item;
while (getline(ss, item, delim)) {
elems.push_back(item);
}
return elems;
}
int main() {
vector<string> x = split("thi is an sample test",' ');
unsigned int i;
for(i=0;i<x.size();i++)
cout<<i<<":"<<x[i]<<endl;
return 0;
}
Spark : how to run spark file from spark shell
You can run as you run your shell script.
This example to run from command line environment
example
./bin/spark-shell
:- this is the path of your spark-shell under bin
/home/fold1/spark_program.py
:- This is the path where your python program is there.
So:
./bin.spark-shell /home/fold1/spark_prohram.py
How to parse JSON string in Typescript
Yes it's a little tricky in TypeScript but you can do the below example like this
_x000D_
_x000D_
let decodeData = JSON.parse(`${jsonResponse}`);
_x000D_
_x000D_
_x000D_
data.frame rows to a list
Like this:
xy.list <- split(xy.df, seq(nrow(xy.df)))
And if you want the rownames of xy.df
to be the names of the output list, you can do:
xy.list <- setNames(split(xy.df, seq(nrow(xy.df))), rownames(xy.df))
Using python PIL to turn a RGB image into a pure black and white image
A simple way to do it using python :
Python
import numpy as np
import imageio
image = imageio.imread(r'[image-path]', as_gray=True)
# getting the threshold value
thresholdValue = np.mean(image)
# getting the dimensions of the image
xDim, yDim = image.shape
# turn the image into a black and white image
for i in range(xDim):
for j in range(yDim):
if (image[i][j] > thresholdValue):
image[i][j] = 255
else:
image[i][j] = 0
If input field is empty, disable submit button
Try this code
$(document).ready(function(){
$('.sendButton').attr('disabled',true);
$('#message').keyup(function(){
if($(this).val().length !=0){
$('.sendButton').attr('disabled', false);
}
else
{
$('.sendButton').attr('disabled', true);
}
})
});
Check demo Fiddle
You are missing the else part of the if statement (to disable the button again if textbox is empty) and parentheses ()
after val
function in if($(this).val.length !=0){
Verilog: How to instantiate a module
Be sure to check out verilog-mode and especially verilog-auto. http://www.veripool.org/wiki/verilog-mode/ It is a verilog mode for emacs, but plugins exist for vi(m?) for example.
An instantiation can be automated with AUTOINST. The comment is expanded with M-x verilog-auto
and can afterwards be manually edited.
subcomponent subcomponent_instance_name(/*AUTOINST*/);
Expanded
subcomponent subcomponent_instance_name (/*AUTOINST*/
//Inputs
.clk, (clk)
.rst_n, (rst_n)
.data_rx (data_rx_1[9:0]),
//Outputs
.data_tx (data_tx[9:0])
);
Implicit wires can be automated with /*AUTOWIRE*/
. Check the link for further information.
Spring cannot find bean xml configuration file when it does exist
I have stuck in this issue for a while and I have came to the following solution
- Create an ApplicationContextAware class (which is a class that implements the ApplicationContextAware)
In ApplicationContextAware we have to implement the one method only
public void setApplicationContext(ApplicationContext context) throws BeansException
Tell the spring context about this new bean (I call it SpringContext)
bean id="springContext" class="packe.of.SpringContext" />
Here is the code snippet
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
public class SpringContext implements ApplicationContextAware {
private static ApplicationContext context;
@Override
public void setApplicationContext(ApplicationContext context) throws BeansException {
this.context = context;
}
public static ApplicationContext getApplicationContext() {
return context;
}
}
Then you can call any method of application context outside the spring context for example
SomeServiceClassOrComponent utilityService SpringContext.getApplicationContext().getBean(SomeServiceClassOrComponent .class);
I hope this will solve the problem for many users