What is the purpose of the "role" attribute in HTML?
Is this role attribute necessary?
Answer: Yes.
- The role attribute is necessary to support Accessible Rich Internet Applications (WAI-ARIA) to define roles in XML-based languages, when the languages do not define their own role attribute.
- Although this is the reason the role attribute is published by the Protocols and Formats Working Group, the attribute has more general use cases as well.
It provides you:
- Accessibility
- Device adaptation
- Server-side processing
- Complex data description,...etc.
MongoDB "root" user
While out of the box, MongoDb has no authentication, you can create the equivalent of a root/superuser by using the "any" roles to a specific user to the admin
database.
Something like this:
use admin
db.addUser( { user: "<username>",
pwd: "<password>",
roles: [ "userAdminAnyDatabase",
"dbAdminAnyDatabase",
"readWriteAnyDatabase"
] } )
Update for 2.6+
While there is a new root user in 2.6, you may find that it doesn't meet your needs, as it still has a few limitations:
Provides access to the operations and all the resources of the
readWriteAnyDatabase, dbAdminAnyDatabase, userAdminAnyDatabase and
clusterAdmin roles combined.
root does not include any access to collections that begin with the
system. prefix.
Update for 3.0+
Use db.createUser
as db.addUser
was removed.
Update for 3.0.7+
root no longer has the limitations stated above.
The root has the validate privilege action on system. collections.
Previously, root does not include any access to collections that begin
with the system. prefix other than system.indexes and
system.namespaces.
Create PostgreSQL ROLE (user) if it doesn't exist
Bash alternative (for Bash scripting):
psql -h localhost -U postgres -tc \
"SELECT 1 FROM pg_user WHERE usename = 'my_user'" \
| grep -q 1 \
|| psql -h localhost -U postgres \
-c "CREATE ROLE my_user LOGIN PASSWORD 'my_password';"
(isn't the answer for the question! it is only for those who may be useful)
Allow multiple roles to access controller action
Using AspNetCore 2.x, you have to go a little different way:
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true, AllowMultiple = true)]
public class AuthorizeRoleAttribute : AuthorizeAttribute
{
public AuthorizeRoleAttribute(params YourEnum[] roles)
{
Policy = string.Join(",", roles.Select(r => r.GetDescription()));
}
}
just use it like this:
[Authorize(YourEnum.Role1, YourEnum.Role2)]
Grant all on a specific schema in the db to a group role in PostgreSQL
My answer is similar to this one on ServerFault.com.
To Be Conservative
If you want to be more conservative than granting "all privileges", you might want to try something more like these.
GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO some_user_;
GRANT EXECUTE ON ALL FUNCTIONS IN SCHEMA public TO some_user_;
The use of public
there refers to the name of the default schema created for every new database/catalog. Replace with your own name if you created a schema.
Access to the Schema
To access a schema at all, for any action, the user must be granted "usage" rights. Before a user can select, insert, update, or delete, a user must first be granted "usage" to a schema.
You will not notice this requirement when first using Postgres. By default every database has a first schema named public
. And every user by default has been automatically been granted "usage" rights to that particular schema. When adding additional schema, then you must explicitly grant usage rights.
GRANT USAGE ON SCHEMA some_schema_ TO some_user_ ;
Excerpt from the Postgres doc:
For schemas, allows access to objects contained in the specified schema (assuming that the objects' own privilege requirements are also met). Essentially this allows the grantee to "look up" objects within the schema. Without this permission, it is still possible to see the object names, e.g. by querying the system tables. Also, after revoking this permission, existing backends might have statements that have previously performed this lookup, so this is not a completely secure way to prevent object access.
For more discussion see the Question, What GRANT USAGE ON SCHEMA exactly do?. Pay special attention to the Answer by Postgres expert Craig Ringer.
Existing Objects Versus Future
These commands only affect existing objects. Tables and such you create in the future get default privileges until you re-execute those lines above. See the other answer by Erwin Brandstetter to change the defaults thereby affecting future objects.
How to check for a valid URL in Java?
I'd love to post this as a comment to Tendayi Mawushe's answer, but I'm afraid there is not enough space ;)
This is the relevant part from the Apache Commons UrlValidator source:
/**
* This expression derived/taken from the BNF for URI (RFC2396).
*/
private static final String URL_PATTERN =
"/^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?/";
// 12 3 4 5 6 7 8 9
/**
* Schema/Protocol (ie. http:, ftp:, file:, etc).
*/
private static final int PARSE_URL_SCHEME = 2;
/**
* Includes hostname/ip and port number.
*/
private static final int PARSE_URL_AUTHORITY = 4;
private static final int PARSE_URL_PATH = 5;
private static final int PARSE_URL_QUERY = 7;
private static final int PARSE_URL_FRAGMENT = 9;
You can easily build your own validator from there.
How to use router.navigateByUrl and router.navigate in Angular
router.navigate vs router.navigateByUrl
router.navigate
is just a convenience method that wraps router.navigateByUrl
, it boils down to:
navigate(commands: any[], extras) {
return router.navigateByUrl(router.createUrlTree(commands, extras), extras);
}
As mentioned in other answers router.navigateByUrl
will only accept absolute URLs:
// This will work
router.navigateByUrl("http://localhost/team/33/user/11")
// This WON'T work even though relativeTo parameter is in the signature
router.navigateByUrl("../22", {relativeTo: route})
All the relative calculations are done by router.createUrlTree
and router.navigate
. Array syntax is used to treat every array element as a URL modifying "command". E.g. ".."
- go up, "path"
- go down, {expand: true}
- add query param, etc.. You can use it like this:
// create /team/33/user/11
router.navigate(['/team', 33, 'user', 11]);
// assuming the current url is `/team/33/user/11` and the route points to `user/11`
// navigate to /team/33/user/11/details
router.navigate(['details'], {relativeTo: route});
// navigate to /team/33/user/22
router.navigate(['../22'], {relativeTo: route});
// navigate to /team/44/user/22
router.navigate(['../../team/44/user/22'], {relativeTo: route});
That {relativeTo: route}
parameter is important as that's what router will use as the root for relative operations.
Get it through your component's constructor:
// In my-awesome.component.ts:
constructor(private route: ActivatedRoute, private router: Router) {}
// Example call
onNavigateClick() {
// Navigates to a parent component
this.router.navigate([..], { relativeTo: this.route })
}
routerLink directive
Nicest thing about this directive is that it will retrieve the ActivatedRoute
for you. Under the hood it's using already familiar:
router.navigateByUrl(router.createUrlTree(commands, { relativeTo: route }), { relativeTo: route });
Following variants will produce identical result:
[routerLink]="['../..']"
// if the string parameter is passed it will be wrapped into an array
routerLink="../.."
Making custom right-click context menus for my web-app
_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<title>Right Click</title>_x000D_
_x000D_
<link href="https://swisnl.github.io/jQuery-contextMenu/dist/jquery.contextMenu.css" rel="stylesheet" type="text/css" />_x000D_
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>_x000D_
<script src="https://swisnl.github.io/jQuery-contextMenu/dist/jquery.contextMenu.js" type="text/javascript"></script>_x000D_
_x000D_
<script src="https://swisnl.github.io/jQuery-contextMenu/dist/jquery.ui.position.min.js" type="text/javascript"></script>_x000D_
_x000D_
</head>_x000D_
<body>_x000D_
<span class="context-menu-one" style="border:solid 1px black; padding:5px;">Right Click Me</span>_x000D_
<script type="text/javascript">_x000D_
_x000D_
$(function() {_x000D_
$.contextMenu({_x000D_
selector: '.context-menu-one', _x000D_
callback: function(key, options) {_x000D_
var m = "clicked: " + key;_x000D_
window.console && console.log(m) || alert(m); _x000D_
},_x000D_
items: {_x000D_
"edit": {name: "Edit", icon: "edit"},_x000D_
"cut": {name: "Cut", icon: "cut"},_x000D_
copy: {name: "Copy", icon: "copy"},_x000D_
"paste": {name: "Paste", icon: "paste"},_x000D_
"delete": {name: "Delete", icon: "delete"},_x000D_
"sep1": "---------",_x000D_
"quit": {name: "Quit", icon: function(){_x000D_
return 'context-menu-icon context-menu-icon-quit';_x000D_
}}_x000D_
}_x000D_
});_x000D_
_x000D_
$('.context-menu-one').on('click', function(e){_x000D_
console.log('clicked', this);_x000D_
}) _x000D_
});_x000D_
</script>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_
MVC 4 Razor adding input type date
If you want to use @Html.EditorFor() you have to use jQuery ui and
update your Asp.net Mvc to 5.2.6.0 with NuGet Package Manager.
@Html.EditorFor(m => m.EntryDate, new { htmlAttributes = new { @class = "datepicker" } })
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
<script>
$(document).ready(function(){
$('.datepicker').datepicker();
});
</script>
}
Creating Scheduled Tasks
This works for me
https://www.nuget.org/packages/ASquare.WindowsTaskScheduler/
It is nicely designed Fluent API.
//This will create Daily trigger to run every 10 minutes for a duration of 18 hours
SchedulerResponse response = WindowTaskScheduler
.Configure()
.CreateTask("TaskName", "C:\\Test.bat")
.RunDaily()
.RunEveryXMinutes(10)
.RunDurationFor(new TimeSpan(18, 0, 0))
.SetStartDate(new DateTime(2015, 8, 8))
.SetStartTime(new TimeSpan(8, 0, 0))
.Execute();
TCPDF Save file to folder?
This worked for me, saving to child dir(temp_pdf
) under the root:
$sFilePath = $_SERVER['DOCUMENT_ROOT'] . '//temp_pdf/file.pdf' ;
$pdf->Output( $sFilePath , 'F');
Remember to make the dir writeable.
Index of duplicates items in a python list
Here is one that works for multiple duplicates and you don't need to specify any values:
List = ['A', 'B', 'A', 'C', 'E', 'B'] # duplicate two 'A's two 'B's
ix_list = []
for i in range(len(List)):
try:
dup_ix = List[(i+1):].index(List[i]) + (i + 1) # dup onwards + (i + 1)
ix_list.extend([i, dup_ix]) # if found no error, add i also
except:
pass
ix_list.sort()
print(ix_list)
[0, 1, 2, 5]
CodeIgniter removing index.php from url
You can remove index.php from url by placing some code in .htaccess
File path: root > .htacess
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?/$1 [L]
Hope it will works.
Instagram: Share photo from webpage
Updated June 2020
It is no longer possible... allegedly. If you have a Facebook or Instagram dedicated contact (because you work in either a big agency or with a big client) it may potentially be possible depending on your use case, but it's highly discouraged.
Before December 2019:
It is now "possible":
https://developers.facebook.com/docs/instagram-api/content-publishing
The Content Publishing API is a subset of Instagram Graph API endpoints that allow you to publish media objects. Publishing media objects with this API is a two step process — you first create a media object container, then publish the container on your Business Account.
Its worth noting that "The Content Publishing API is in closed beta with Facebook Marketing Partners and Instagram Partners only. We are not accepting new applicants at this time." from https://stackoverflow.com/a/49677468/445887
Jquery Ajax Call, doesn't call Success or Error
Try to encapsulate the ajax call into a function and set the async option to false. Note that this option is deprecated since jQuery 1.8.
function foo() {
var myajax = $.ajax({
type: "POST",
url: "CHService.asmx/SavePurpose",
dataType: "text",
data: JSON.stringify({ Vid: Vid, PurpId: PurId }),
contentType: "application/json; charset=utf-8",
async: false, //add this
});
return myajax.responseText;
}
You can do this also:
$.ajax({
type: "POST",
url: "CHService.asmx/SavePurpose",
dataType: "text",
data: JSON.stringify({ Vid: Vid, PurpId: PurId }),
contentType: "application/json; charset=utf-8",
async: false, //add this
}).done(function ( data ) {
Success = true;
}).fail(function ( data ) {
Success = false;
});
You can read more about the jqXHR jQuery Object
PersistentObjectException: detached entity passed to persist thrown by JPA and Hibernate
This is a typical bidirectional consistency problem. It is well discussed in this link as well as this link.
As per the articles in the previous 2 links you need to fix your setters in both sides of the bidirectional relationship. An example setter for the One side is in this link.
An example setter for the Many side is in this link.
After you correct your setters you want to declare the Entity access type to be "Property". Best practice to declare "Property" access type is to move ALL the annotations from the member properties to the corresponding getters. A big word of caution is not to mix "Field" and "Property" access types within the entity class otherwise the behavior is undefined by the JSR-317 specifications.
Understanding generators in Python
This post will use Fibonacci numbers as a tool to build up to explaining the usefulness of Python generators.
This post will feature both C++ and Python code.
Fibonacci numbers are defined as the sequence: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ....
Or in general:
F0 = 0
F1 = 1
Fn = Fn-1 + Fn-2
This can be transferred into a C++ function extremely easily:
size_t Fib(size_t n)
{
//Fib(0) = 0
if(n == 0)
return 0;
//Fib(1) = 1
if(n == 1)
return 1;
//Fib(N) = Fib(N-2) + Fib(N-1)
return Fib(n-2) + Fib(n-1);
}
But if you want to print the first six Fibonacci numbers, you will be recalculating a lot of the values with the above function.
For example: Fib(3) = Fib(2) + Fib(1)
, but Fib(2)
also recalculates Fib(1)
. The higher the value you want to calculate, the worse off you will be.
So one may be tempted to rewrite the above by keeping track of the state in main
.
// Not supported for the first two elements of Fib
size_t GetNextFib(size_t &pp, size_t &p)
{
int result = pp + p;
pp = p;
p = result;
return result;
}
int main(int argc, char *argv[])
{
size_t pp = 0;
size_t p = 1;
std::cout << "0 " << "1 ";
for(size_t i = 0; i <= 4; ++i)
{
size_t fibI = GetNextFib(pp, p);
std::cout << fibI << " ";
}
return 0;
}
But this is very ugly, and it complicates our logic in main
. It would be better to not have to worry about state in our main
function.
We could return a vector
of values and use an iterator
to iterate over that set of values, but this requires a lot of memory all at once for a large number of return values.
So back to our old approach, what happens if we wanted to do something else besides print the numbers? We'd have to copy and paste the whole block of code in main
and change the output statements to whatever else we wanted to do.
And if you copy and paste code, then you should be shot. You don't want to get shot, do you?
To solve these problems, and to avoid getting shot, we may rewrite this block of code using a callback function. Every time a new Fibonacci number is encountered, we would call the callback function.
void GetFibNumbers(size_t max, void(*FoundNewFibCallback)(size_t))
{
if(max-- == 0) return;
FoundNewFibCallback(0);
if(max-- == 0) return;
FoundNewFibCallback(1);
size_t pp = 0;
size_t p = 1;
for(;;)
{
if(max-- == 0) return;
int result = pp + p;
pp = p;
p = result;
FoundNewFibCallback(result);
}
}
void foundNewFib(size_t fibI)
{
std::cout << fibI << " ";
}
int main(int argc, char *argv[])
{
GetFibNumbers(6, foundNewFib);
return 0;
}
This is clearly an improvement, your logic in main
is not as cluttered, and you can do anything you want with the Fibonacci numbers, simply define new callbacks.
But this is still not perfect. What if you wanted to only get the first two Fibonacci numbers, and then do something, then get some more, then do something else?
Well, we could go on like we have been, and we could start adding state again into main
, allowing GetFibNumbers to start from an arbitrary point.
But this will further bloat our code, and it already looks too big for a simple task like printing Fibonacci numbers.
We could implement a producer and consumer model via a couple of threads. But this complicates the code even more.
Instead let's talk about generators.
Python has a very nice language feature that solves problems like these called generators.
A generator allows you to execute a function, stop at an arbitrary point, and then continue again where you left off.
Each time returning a value.
Consider the following code that uses a generator:
def fib():
pp, p = 0, 1
while 1:
yield pp
pp, p = p, pp+p
g = fib()
for i in range(6):
g.next()
Which gives us the results:
0
1
1
2
3
5
The yield
statement is used in conjuction with Python generators. It saves the state of the function and returns the yeilded value. The next time you call the next() function on the generator, it will continue where the yield left off.
This is by far more clean than the callback function code. We have cleaner code, smaller code, and not to mention much more functional code (Python allows arbitrarily large integers).
Source
App installation failed due to application-identifier entitlement
Delete any previous versions of App from your iPhone and then Clean->Build and Run again. Your app should run smoothly on your Device.
Also, please make sure you have not selected Distribution Certificate in your Project Settings while trying to run your project directly on your device.
Method to get all files within folder and subfolders that will return a list
Simply use this:
public static List<String> GetAllFiles(String directory)
{
return Directory.GetFiles(directory, "*.*", SearchOption.AllDirectories).ToList();
}
And if you want every file, even extensionless ones:
public static List<String> GetAllFiles(String directory)
{
return Directory.GetFiles(directory, "*", SearchOption.AllDirectories).ToList();
}
What is the functionality of setSoTimeout and how it works?
Does it mean that I'm blocking reading any input from the Server/Client for this socket for 2000 millisecond and after this time the socket is ready to read data?
No, it means that if no data arrives within 2000ms a SocketTimeoutException
will be thrown.
What does it mean timeout expire?
It means the 2000ms (in your case) elapses without any data arriving.
What is the option which must be enabled prior to blocking operation?
There isn't one that 'must be' enabled. If you mean 'may be enabled', this is one of them.
Infinite Timeout menas that the socket does't read anymore?
What a strange suggestion. It means that if no data ever arrives you will block in the read forever.
Apply style to cells of first row
Below works for first tr
of the table under thead
table thead tr:first-child {
background: #f2f2f2;
}
And this works for the first tr
of thead
and tbody
both:
table thead tbody tr:first-child {
background: #f2f2f2;
}
How to get current route
To reliably get the full current route you can use this
this.router.events.subscribe(
(event: any) => {
if (event instanceof NavigationEnd) {
console.log('this.router.url', this.router.url);
}
}
);
How to set the maxAllowedContentLength to 500MB while running on IIS7?
IIS v10 (but this should be the same also for IIS 7.x)
Quick addition for people which are looking for respective max values
Max for maxAllowedContentLength
is: UInt32.MaxValue
4294967295 bytes
: ~4GB
Max for maxRequestLength
is: Int32.MaxValue
2147483647 bytes
: ~2GB
web.config
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.web>
<!-- ~ 2GB -->
<httpRuntime maxRequestLength="2147483647" />
</system.web>
<system.webServer>
<security>
<requestFiltering>
<!-- ~ 4GB -->
<requestLimits maxAllowedContentLength="4294967295" />
</requestFiltering>
</security>
</system.webServer>
</configuration>
Check if two unordered lists are equal
Python has a built-in datatype for an unordered collection of (hashable) things, called a set
. If you convert both lists to sets, the comparison will be unordered.
set(x) == set(y)
Documentation on set
EDIT: @mdwhatcott points out that you want to check for duplicates. set
ignores these, so you need a similar data structure that also keeps track of the number of items in each list. This is called a multiset; the best approximation in the standard library is a collections.Counter
:
>>> import collections
>>> compare = lambda x, y: collections.Counter(x) == collections.Counter(y)
>>>
>>> compare([1,2,3], [1,2,3,3])
False
>>> compare([1,2,3], [1,2,3])
True
>>> compare([1,2,3,3], [1,2,2,3])
False
>>>
How to read value of a registry key c#
You need to first add using Microsoft.Win32;
to your code page.
Then you can begin to use the Registry
classes:
try
{
using (RegistryKey key = Registry.LocalMachine.OpenSubKey("Software\\Wow6432Node\\MySQL AB\\MySQL Connector\\Net"))
{
if (key != null)
{
Object o = key.GetValue("Version");
if (o != null)
{
Version version = new Version(o as String); //"as" because it's REG_SZ...otherwise ToString() might be safe(r)
//do what you like with version
}
}
}
}
catch (Exception ex) //just for demonstration...it's always best to handle specific exceptions
{
//react appropriately
}
BEWARE: unless you have administrator access, you are unlikely to be able to do much in LOCAL_MACHINE
. Sometimes even reading values can be a suspect operation without admin rights.
Populate nested array in mongoose
For someone who has the problem with populate
and also wants to do this:
- chat with simple text & quick replies (bubbles)
- 4 database collections for chat:
clients
, users
, rooms
, messasges
.
- same message DB structure for 3 types of senders: bot, users & clients
refPath
or dynamic reference
populate
with path
and model
options
- use
findOneAndReplace
/replaceOne
with $exists
- create a new document if the fetched document doesn't exist
CONTEXT
Goal
- Save a new simple text message to the database & populate it with the user or client data (2 different models).
- Save a new quickReplies message to the database and populate it with the user or client data.
- Save each message its sender type:
clients
, users
& bot
.
- Populate only the messages who have the sender
clients
or users
with its Mongoose Models. _sender type client models is clients
, for user is users
.
Message schema:
const messageSchema = new Schema({
room: {
type: Schema.Types.ObjectId,
ref: 'rooms',
required: [true, `Room's id`]
},
sender: {
_id: { type: Schema.Types.Mixed },
type: {
type: String,
enum: ['clients', 'users', 'bot'],
required: [true, 'Only 3 options: clients, users or bot.']
}
},
timetoken: {
type: String,
required: [true, 'It has to be a Nanosecond-precision UTC string']
},
data: {
lang: String,
// Format samples on https://docs.chatfuel.com/api/json-api/json-api
type: {
text: String,
quickReplies: [
{
text: String,
// Blocks' ids.
goToBlocks: [String]
}
]
}
}
mongoose.model('messages', messageSchema);
SOLUTION
My server side API request
My code
Utility function (on chatUtils.js
file) to get the type of message that you want to save:
/**
* We filter what type of message is.
*
* @param {Object} message
* @returns {string} The type of message.
*/
const getMessageType = message => {
const { type } = message.data;
const text = 'text',
quickReplies = 'quickReplies';
if (type.hasOwnProperty(text)) return text;
else if (type.hasOwnProperty(quickReplies)) return quickReplies;
};
/**
* Get the Mongoose's Model of the message's sender. We use
* the sender type to find the Model.
*
* @param {Object} message - The message contains the sender type.
*/
const getSenderModel = message => {
switch (message.sender.type) {
case 'clients':
return 'clients';
case 'users':
return 'users';
default:
return null;
}
};
module.exports = {
getMessageType,
getSenderModel
};
My server side (using Nodejs) to get the request of saving the message:
app.post('/api/rooms/:roomId/messages/new', async (req, res) => {
const { roomId } = req.params;
const { sender, timetoken, data } = req.body;
const { uuid, state } = sender;
const { type } = state;
const { lang } = data;
// For more info about message structure, look up Message Schema.
let message = {
room: new ObjectId(roomId),
sender: {
_id: type === 'bot' ? null : new ObjectId(uuid),
type
},
timetoken,
data: {
lang,
type: {}
}
};
// ==========================================
// CONVERT THE MESSAGE
// ==========================================
// Convert the request to be able to save on the database.
switch (getMessageType(req.body)) {
case 'text':
message.data.type.text = data.type.text;
break;
case 'quickReplies':
// Save every quick reply from quickReplies[].
message.data.type.quickReplies = _.map(
data.type.quickReplies,
quickReply => {
const { text, goToBlocks } = quickReply;
return {
text,
goToBlocks
};
}
);
break;
default:
break;
}
// ==========================================
// SAVE THE MESSAGE
// ==========================================
/**
* We save the message on 2 ways:
* - we replace the message type `quickReplies` (if it already exists on database) with the new one.
* - else, we save the new message.
*/
try {
const options = {
// If the quickRepy message is found, we replace the whole document.
overwrite: true,
// If the quickRepy message isn't found, we create it.
upsert: true,
// Update validators validate the update operation against the model's schema.
runValidators: true,
// Return the document already updated.
new: true
};
Message.findOneAndUpdate(
{ room: roomId, 'data.type.quickReplies': { $exists: true } },
message,
options,
async (err, newMessage) => {
if (err) {
throw Error(err);
}
// Populate the new message already saved on the database.
Message.populate(
newMessage,
{
path: 'sender._id',
model: getSenderModel(newMessage)
},
(err, populatedMessage) => {
if (err) {
throw Error(err);
}
res.send(populatedMessage);
}
);
}
);
} catch (err) {
logger.error(
`#API Error on saving a new message on the database of roomId=${roomId}. ${err}`,
{ message: req.body }
);
// Bad Request
res.status(400).send(false);
}
});
TIPs:
For the database:
- Every message is a document itself.
- Instead of using
refPath
, we use the util getSenderModel
that is used on populate()
. This is because of the bot. The sender.type
can be: users
with his database, clients
with his database and bot
without a database. The refPath
needs true Model reference, if not, Mongooose throw an error.
sender._id
can be type ObjectId
for users and clients, or null
for the bot.
For API request logic:
- We replace the
quickReply
message (Message DB has to have only one quickReply, but as many simple text messages as you want). We use the findOneAndUpdate
instead of replaceOne
or findOneAndReplace
.
- We execute the query operation (the
findOneAndUpdate
) and the populate
operation with the callback
of each one. This is important if you don't know if use async/await
, then()
, exec()
or callback(err, document)
. For more info look the Populate Doc.
- We replace the quick reply message with the
overwrite
option and without $set
query operator.
- If we don't find the quick reply, we create a new one. You have to tell to Mongoose this with
upsert
option.
- We populate only one time, for the replaced message or the new saved message.
- We return to callbacks, whatever is the message we've saved with
findOneAndUpdate
and for the populate()
.
- In
populate
, we create a custom dynamic Model reference with the getSenderModel
. We can use the Mongoose dynamic reference because the sender.type
for bot
hasn't any Mongoose Model. We use a Populating Across Database with model
and path
optins.
I've spend a lot of hours solving little problems here and there and I hope this will help someone!
Print raw string from variable? (not getting the answers)
I had a similar problem and stumbled upon this question, and know thanks to Nick Olson-Harris' answer that the solution lies with changing the string.
Two ways of solving it:
Get the path you want using native python functions, e.g.:
test = os.getcwd() # In case the path in question is your current directory
print(repr(test))
This makes it platform independent and it now works with .encode
. If this is an option for you, it's the more elegant solution.
If your string is not a path, define it in a way compatible with python strings, in this case by escaping your backslashes:
test = 'C:\\Windows\\Users\\alexb\\'
print(repr(test))
How do I deserialize a JSON string into an NSDictionary? (For iOS 5+)
I've made a category from @Abizern answer
@implementation NSString (Extensions)
- (NSDictionary *) json_StringToDictionary {
NSError *error;
NSData *objectData = [self dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:objectData options:NSJSONReadingMutableContainers error:&error];
return (!json ? nil : json);
}
@end
Use it like this,
NSString *jsonString = @"{\"2\":\"3\"}";
NSLog(@"%@",[jsonString json_StringToDictionary]);
Difference between Ctrl+Shift+F and Ctrl+I in Eclipse
Ctrl+Shift+F formats the selected line(s) or the whole source code if you haven't selected any line(s) as per the format specified in your Eclipse, while Ctrl+I gives proper indent to the selected line(s) or the current line if you haven't selected any line(s).
try this.
or more precisely
The Ant editor that ships with Eclipse can be used to reformat
XML/XHTML/HTML code (with a few configuration options in Window >
Preferences > Ant > Editor).
You can right-click a file then
Open With... > Other... > Internal Editors > Ant Editor
Or add a file association between .html (or .xhtml) and that editor with
Window > Preferences > General > Editors > File Associations
Once open in the editor, hit ESC then CTRL-F to reformat.
Html.Partial vs Html.RenderPartial & Html.Action vs Html.RenderAction
@Html.Partial
returns view in HTML-encoded string and use same view TextWriter
object.
@Html.RenderPartial
this method return void
.
@Html.RenderPartial
is faster than @Html.Partial
The syntax for PartialView
:
[HttpGet]
public ActionResult AnyActionMethod
{
return PartialView();
}
Add vertical scroll bar to panel
Add to your panel's style code something like this:
<asp:Panel ID="myPanel" runat="Server" CssClass="myPanelCSS" style="overflow-y:auto; overflow-x:hidden"></asp:Panel>
simulate background-size:cover on <video> or <img>
Based on Daniel de Wit's answer and comments, I searched a bit more. Thanks to him for the solution.
The solution is to use object-fit: cover;
which has a great support (every modern browser support it). If you really want to support IE, you can use a polyfill like object-fit-images or object-fit.
Demos :
_x000D_
_x000D_
img {_x000D_
float: left;_x000D_
width: 100px;_x000D_
height: 80px;_x000D_
border: 1px solid black;_x000D_
margin-right: 1em;_x000D_
}_x000D_
.fill {_x000D_
object-fit: fill;_x000D_
}_x000D_
.contain {_x000D_
object-fit: contain;_x000D_
}_x000D_
.cover {_x000D_
object-fit: cover;_x000D_
}_x000D_
.none {_x000D_
object-fit: none;_x000D_
}_x000D_
.scale-down {_x000D_
object-fit: scale-down;_x000D_
}
_x000D_
<img class="fill" src="http://www.peppercarrot.com/data/wiki/medias/img/chara_carrot.jpg"/>_x000D_
<img class="contain" src="http://www.peppercarrot.com/data/wiki/medias/img/chara_carrot.jpg"/>_x000D_
<img class="cover" src="http://www.peppercarrot.com/data/wiki/medias/img/chara_carrot.jpg"/>_x000D_
<img class="none" src="http://www.peppercarrot.com/data/wiki/medias/img/chara_carrot.jpg"/>_x000D_
<img class="scale-down" src="http://www.peppercarrot.com/data/wiki/medias/img/chara_carrot.jpg"/>
_x000D_
_x000D_
_x000D_
and with a parent:
_x000D_
_x000D_
div {_x000D_
float: left;_x000D_
width: 100px;_x000D_
height: 80px;_x000D_
border: 1px solid black;_x000D_
margin-right: 1em;_x000D_
}_x000D_
img {_x000D_
width: 100%;_x000D_
height: 100%;_x000D_
}_x000D_
.fill {_x000D_
object-fit: fill;_x000D_
}_x000D_
.contain {_x000D_
object-fit: contain;_x000D_
}_x000D_
.cover {_x000D_
object-fit: cover;_x000D_
}_x000D_
.none {_x000D_
object-fit: none;_x000D_
}_x000D_
.scale-down {_x000D_
object-fit: scale-down;_x000D_
}
_x000D_
<div>_x000D_
<img class="fill" src="http://www.peppercarrot.com/data/wiki/medias/img/chara_carrot.jpg"/>_x000D_
</div><div>_x000D_
<img class="contain" src="http://www.peppercarrot.com/data/wiki/medias/img/chara_carrot.jpg"/>_x000D_
</div><div>_x000D_
<img class="cover" src="http://www.peppercarrot.com/data/wiki/medias/img/chara_carrot.jpg"/>_x000D_
</div><div>_x000D_
<img class="none" src="http://www.peppercarrot.com/data/wiki/medias/img/chara_carrot.jpg"/>_x000D_
</div><div>_x000D_
<img class="scale-down" src="http://www.peppercarrot.com/data/wiki/medias/img/chara_carrot.jpg"/>_x000D_
</div>
_x000D_
_x000D_
_x000D_
How to create bitmap from byte array?
Guys thank you for your help. I think all of this answers works. However i think my byte array contains raw bytes. That's why all of those solutions didnt work for my code.
However i found a solution. Maybe this solution helps other coders who have problem like mine.
static byte[] PadLines(byte[] bytes, int rows, int columns) {
int currentStride = columns; // 3
int newStride = columns; // 4
byte[] newBytes = new byte[newStride * rows];
for (int i = 0; i < rows; i++)
Buffer.BlockCopy(bytes, currentStride * i, newBytes, newStride * i, currentStride);
return newBytes;
}
int columns = imageWidth;
int rows = imageHeight;
int stride = columns;
byte[] newbytes = PadLines(imageData, rows, columns);
Bitmap im = new Bitmap(columns, rows, stride,
PixelFormat.Format8bppIndexed,
Marshal.UnsafeAddrOfPinnedArrayElement(newbytes, 0));
im.Save("C:\\Users\\musa\\Documents\\Hobby\\image21.bmp");
This solutions works for 8bit 256 bpp (Format8bppIndexed). If your image has another format you should change PixelFormat
.
And there is a problem with colors right now. As soon as i solved this one i will edit my answer for other users.
*PS = I am not sure about stride value but for 8bit it should be equal to columns.
And also this function Works for me.. This function copies 8 bit greyscale image into a 32bit layout.
public void SaveBitmap(string fileName, int width, int height, byte[] imageData)
{
byte[] data = new byte[width * height * 4];
int o = 0;
for (int i = 0; i < width * height; i++)
{
byte value = imageData[i];
data[o++] = value;
data[o++] = value;
data[o++] = value;
data[o++] = 0;
}
unsafe
{
fixed (byte* ptr = data)
{
using (Bitmap image = new Bitmap(width, height, width * 4,
PixelFormat.Format32bppRgb, new IntPtr(ptr)))
{
image.Save(Path.ChangeExtension(fileName, ".jpg"));
}
}
}
}
How to delete projects in Intellij IDEA 14?
Deleting and Recreating a project with same name is tricky. If you try to follow above suggested steps and try to create a project with same name as the one you just deleted, you will run into error like
'C:/xxxxxx/pom.xml' already exists in VFS
Here is what I found would work.
- Remove module
- File -> Invalidate Cache (at this point the Intelli IDEA wants to restart)
- Close project
- Delete the folder form system explorer.
- Now you can create a project with same name as before.
Node.js global variables
I agree that using the global/GLOBAL namespace for setting anything global is bad practice and don't use it at all in theory (in theory being the operative word). However (yes, the operative) I do use it for setting custom Error classes:
// Some global/configuration file that gets called in initialisation
global.MyError = [Function of MyError];
Yes, it is taboo here, but if your site/project uses custom errors throughout the place, you would basically need to define it everywhere, or at least somewhere to:
- Define the Error class in the first place
- In the script where you're throwing it
- In the script where you're catching it
Defining my custom errors in the global namespace saves me the hassle of require'ing my customer error library. Imaging throwing a custom error where that custom error is undefined.
How can I loop through a C++ map of maps?
With C++17 (or later), you can use the "structured bindings" feature, which lets you define multiple variables, with different names, using a single tuple/pair. Example:
for (const auto& [name, description] : planet_descriptions) {
std::cout << "Planet " << name << ":\n" << description << "\n\n";
}
The original proposal (by luminaries Bjarne Stroustrup, Herb Sutter and Gabriel Dos Reis) is fun to read (and the suggested syntax is more intuitive IMHO); there's also the proposed wording for the standard which is boring to read but is closer to what will actually go in.
Best way to find the intersection of multiple sets?
Jean-François Fabre set.intesection(*list_of_sets) answer is definetly the most Pyhtonic and is rightly the accepted answer.
For those that want to use reduce, the following will also work:
reduce(set.intersection, list_of_sets)
Change MySQL default character set to UTF-8 in my.cnf?
Change MySQL character:
Client
default-character-set=utf8
mysqld
character_set_server=utf8
We should not write default-character-set=utf8
in mysqld, because that could result in an error like:
start: Job failed to start
At last:
+--------------------------+----------------------------+
| Variable_name | Value |
+--------------------------+----------------------------+
| character_set_client | utf8 |
| character_set_connection | utf8 |
| character_set_database | utf8 |
| character_set_filesystem | binary |
| character_set_results | utf8 |
| character_set_server | utf8 |
| character_set_system | utf8 |
| character_sets_dir | /usr/share/mysql/charsets/ |
+--------------------------+----------------------------+
Hidden Features of Java
The type params for generic methods can be specified explicitly like so:
Collections.<String,Integer>emptyMap()
Preventing console window from closing on Visual Studio C/C++ Console application
Here's a solution that (1) doesn't require any code changes or breakpoints, and (2) pauses after program termination so that you can see everything that was printed. It will pause after either F5 or Ctrl+F5. The major downside is that on VS2013 Express (as tested), it doesn't load symbols, so debugging is very restricted.
Create a batch file. I called mine runthenpause.bat
, with the following contents:
%1 %2 %3 %4 %5 %6 %7 %8 %9
pause
The first line will run whatever command you provide and up to eight arguments. The second line will... pause.
Open the project properties | Configuration properties | Debugging.
- Change "Command Arguments" to
$(TargetPath)
(or whatever is in "Command").
- Change "Command" to the full path to
runthenpause.bat
.
- Hit OK.
Now, when you run, runthenpause.bat
will launch your application, and after your application has terminated, will pause for you to see the console output.
I will post an update if I figure out how to get the symbols loaded. I tried /Z7
per this but without success.
Using event.target with React components
First argument in update
method is SyntheticEvent
object that contains common properties and methods to any event
, it is not reference to React component where there is property props
.
if you need pass argument to update method you can do it like this
onClick={ (e) => this.props.onClick(e, 'home', 'Home') }
and get these arguments inside update
method
update(e, space, txt){
console.log(e.target, space, txt);
}
Example
event.target
gives you the native DOMNode
, then you need to use the regular DOM APIs to access attributes. For instance getAttribute
or dataset
<button
data-space="home"
className="home"
data-txt="Home"
onClick={ this.props.onClick }
/>
Button
</button>
onClick(e) {
console.log(e.target.dataset.txt, e.target.dataset.space);
}
Example
How to put sshpass command inside a bash script?
I didn't understand how the accepted answer answers the actual question of how to run any commands on the server after sshpass is given from within the bash script file. For that reason, I'm providing an answer.
After your provided script commands, execute additional commands like below:
sshpass -p 'password' ssh user@host "ls; whois google.com;" #or whichever commands you would like to use, for multiple commands provide a semicolon ; after the command
In your script:
#! /bin/bash
sshpass -p 'password' ssh user@host "ls; whois google.com;"
Creating object with dynamic keys
In the new ES2015 standard for JavaScript (formerly called ES6), objects can be created with computed keys: Object Initializer spec.
The syntax is:
var obj = {
[myKey]: value,
}
If applied to the OP's scenario, it would turn into:
stuff = function (thing, callback) {
var inputs = $('div.quantity > input').map(function(){
return {
[this.attr('name')]: this.attr('value'),
};
})
callback(null, inputs);
}
Note: A transpiler is still required for browser compatiblity.
Using Babel or Google's traceur, it is possible to use this syntax today.
In earlier JavaScript specifications (ES5 and below), the key in an object literal is always interpreted literally, as a string.
To use a "dynamic" key, you have to use bracket notation:
var obj = {};
obj[myKey] = value;
In your case:
stuff = function (thing, callback) {
var inputs = $('div.quantity > input').map(function(){
var key = this.attr('name')
, value = this.attr('value')
, ret = {};
ret[key] = value;
return ret;
})
callback(null, inputs);
}
jQuery: How can I create a simple overlay?
By overlay do you mean content that overlaps/covers the rest of the page? In HTML, you could do this by using a div that uses absolute or fixed positioning. If it needed to be generated dynamically, jQuery could simply generate a div with the position style set appropriately.
What is an HttpHandler in ASP.NET
An ASP.NET HTTP
handler is the process (frequently referred to as the "endpoint") that runs in response to a request made to an ASP.NET Web application. The most common handler is an ASP.NET page handler that processes .aspx files. When users request an .aspx file
, the request is processed by the page via the page handler.
The ASP.NET page handler is only one type of handler. ASP.NET comes with several other built-in handlers such as the Web service handler for .asmx files
.
You can create custom HTTP handlers when you want special handling that you can identify using file name extensions in your application. For example, the following scenarios would be good uses of custom HTTP handlers:
RSS feeds To create an RSS feed for a site, you can create a handler that emits RSS-formatted XML. You can then bind the .rss extension (for example) in your application to the custom handler. When users send a request to your site that ends in .rss, ASP.NET will call your handler to process the request.
Image server If you want your Web application to serve images in a variety of sizes, you can write a custom handler to resize images and then send them back to the user as the handler's response.
HTTP handlers have access to the application context, including the requesting user's identity (if known), application state, and session information. When an HTTP handler is requested, ASP.NET calls the ProcessRequest
method on the appropriate handler. The handler's ProcessRequest
method creates a response, which is sent back to the requesting browser. As with any page request, the response goes through any HTTP modules that have subscribed to events that occur after the handler has run.
VBA - Select columns using numbers?
Try using the following, where n
is your variable and x is your offset (4 in this case):
LEFT(ADDRESS(1,n+x,4),1)
This will return the letter of that column (so for n=1 and x=4, it'll return A+4 = E). You can then use INDIRECT()
to reference this, as so:
COLUMNS(INDIRECT(LEFT(ADDRESS(1,n,4),1)&":"&LEFT(ADDRESS(1,n+x,4),1)))
which with n=1, x=4 becomes:
COLUMNS(INDIRECT("A"&":"&"E"))
and so:
COLUMNS(A:E)
Convert ArrayList<String> to String[] array
Use like this.
List<String> stockList = new ArrayList<String>();
stockList.add("stock1");
stockList.add("stock2");
String[] stockArr = new String[stockList.size()];
stockArr = stockList.toArray(stockArr);
for(String s : stockArr)
System.out.println(s);
How do I convert this list of dictionaries to a csv file?
Here is another, more general solution assuming you don't have a list of rows (maybe they don't fit in memory) or a copy of the headers (maybe the write_csv
function is generic):
def gen_rows():
yield OrderedDict(name='bob', age=25, weight=200)
yield OrderedDict(name='jim', age=31, weight=180)
def write_csv():
it = genrows()
first_row = it.next() # __next__ in py3
with open("people.csv", "w") as outfile:
wr = csv.DictWriter(outfile, fieldnames=list(first_row))
wr.writeheader()
wr.writerow(first_row)
wr.writerows(it)
Note: the OrderedDict constructor used here only preserves order in python >3.4. If order is important, use the OrderedDict([('name', 'bob'),('age',25)])
form.
Get column from a two dimensional array
This function works to arrays and objects.
obs: it works like array_column php function. It means that an optional third parameter can be passed to define what column will correspond to the indices of return.
function array_column(list, column, indice){
var result;
if(typeof indice != "undefined"){
result = {};
for(key in list)
result[list[key][indice]] = list[key][column];
}else{
result = [];
for(key in list)
result.push( list[key][column] );
}
return result;
}
This is a conditional version:
function array_column_conditional(list, column, indice){
var result;
if(typeof indice != "undefined"){
result = {};
for(key in list)
if(typeof list[key][column] !== 'undefined' && typeof list[key][indice] !== 'undefined')
result[list[key][indice]] = list[key][column];
}else{
result = [];
for(key in list)
if(typeof list[key][column] !== 'undefined')
result.push( list[key][column] );
}
return result;
}
usability:
var lista = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
var obj_list = [
{a: 1, b: 2, c: 3},
{a: 4, b: 5, c: 6},
{a: 8, c: 9}
];
var objeto = {
d: {a: 1, b: 3},
e: {a: 4, b: 5, c: 6},
f: {a: 7, b: 8, c: 9}
};
var list_obj = {
d: [1, 2, 3],
e: [4, 5],
f: [7, 8, 9]
};
console.log( "column list: ", array_column(lista, 1) );
console.log( "column obj_list: ", array_column(obj_list, 'b', 'c') );
console.log( "column objeto: ", array_column(objeto, 'c') );
console.log( "column list_obj: ", array_column(list_obj, 0, 0) );
console.log( "column list conditional: ", array_column_conditional(lista, 1) );
console.log( "column obj_list conditional: ", array_column_conditional(obj_list, 'b', 'c') );
console.log( "column objeto conditional: ", array_column_conditional(objeto, 'c') );
console.log( "column list_obj conditional: ", array_column_conditional(list_obj, 0, 0) );
Output:
/*
column list: Array [ 2, 5, 8 ]
column obj_list: Object { 3: 2, 6: 5, 9: undefined }
column objeto: Array [ undefined, 6, 9 ]
column list_obj: Object { 1: 1, 4: 4, 7: 7 }
column list conditional: Array [ 2, 5, 8 ]
column obj_list conditional: Object { 3: 2, 6: 5 }
column objeto conditional: Array [ 6, 9 ]
column list_obj conditional: Object { 1: 1, 4: 4, 7: 7 }
*/
Python wildcard search in string
Do you mean any specific syntax for wildcards? Usually *
stands for "one or many" characters and ?
stands for one.
The simplest way probably is to translate a wildcard expression into a regular expression, then use that for filtering the results.
How to build and fill pandas dataframe from for loop?
I may be wrong, but I think the accepted answer by @amit has a bug.
from pandas import DataFrame as df
x = [1,2,3]
y = [7,8,9,10]
# this gives me a syntax error at 'for' (Python 3.7)
d1 = df[[a, "A", b, "B"] for a in x for b in y]
# this works
d2 = df([a, "A", b, "B"] for a in x for b in y)
# and if you want to add the column names on the fly
# note the additional parentheses
d3 = df(([a, "A", b, "B"] for a in x for b in y), columns = ("l","m","n","o"))
Python: Fetch first 10 results from a list
Use the slicing operator:
list = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
list[:10]
How to deal with ModalDialog using selenium webdriver?
What you are using is not a model dialog, it is a separate window.
Use this code:
private static Object firstHandle;
private static Object lastHandle;
public static void switchToWindowsPopup() {
Set<String> handles = DriverManager.getCurrent().getWindowHandles();
Iterator<String> itr = handles.iterator();
firstHandle = itr.next();
lastHandle = firstHandle;
while (itr.hasNext()) {
lastHandle = itr.next();
}
DriverManager.getCurrent().switchTo().window(lastHandle.toString());
}
public static void switchToMainWindow() {
DriverManager.getCurrent().switchTo().window(firstHandle.toString());
How to convert a PIL Image into a numpy array?
The example, I have used today:
import PIL
import numpy
from PIL import Image
def resize_image(numpy_array_image, new_height):
# convert nympy array image to PIL.Image
image = Image.fromarray(numpy.uint8(numpy_array_image))
old_width = float(image.size[0])
old_height = float(image.size[1])
ratio = float( new_height / old_height)
new_width = int(old_width * ratio)
image = image.resize((new_width, new_height), PIL.Image.ANTIALIAS)
# convert PIL.Image into nympy array back again
return array(image)
How to execute .sql script file using JDBC
You should be able to parse the SQL file into statements. And run a single statement a time. If you know that your file consists of simple insert/update/delete statements you can use a semicolon as statement delimiter. In common case you have a task to create your specific SQL-dialect parser.
Batch Files - Error Handling
I guess this feature was added since the OP but for future reference errors that would output in the command window can be redirected to a file independent of the standard output
command 1> file - Write the standard output of command to file
command 2> file - Write the standard error of command to file
Padding or margin value in pixels as integer using jQuery
Here's how you can get the surrounding dimentions:
var elem = $('#myId');
var marginTopBottom = elem.outerHeight(true) - elem.outerHeight();
var marginLeftRight = elem.outerWidth(true) - elem.outerWidth();
var borderTopBottom = elem.outerHeight() - elem.innerHeight();
var borderLeftRight = elem.outerWidth() - elem.innerWidth();
var paddingTopBottom = elem.innerHeight() - elem.height();
var paddingLeftRight = elem.innerWidth() - elem.width();
Pay attention that each variable, paddingTopBottom
for example, contains the sum of the margins on the both sides of the element; i.e., paddingTopBottom == paddingTop + paddingBottom
. I wonder if there is a way to get them separately. Of course, if they are equal you can divide by 2 :)
What values for checked and selected are false?
The empty string is false as a rule.
Apparently the empty string is not respected as empty in all browsers and the presence of the checked attribute is taken to mean checked. So the entire attribute must either be present or omitted.
Can I use multiple "with"?
Try:
With DependencedIncidents AS
(
SELECT INC.[RecTime],INC.[SQL] AS [str] FROM
(
SELECT A.[RecTime] As [RecTime],X.[SQL] As [SQL] FROM [EventView] AS A
CROSS JOIN [Incident] AS X
WHERE
patindex('%' + A.[Col] + '%', X.[SQL]) > 0
) AS INC
),
lalala AS
(
SELECT INC.[RecTime],INC.[SQL] AS [str] FROM
(
SELECT A.[RecTime] As [RecTime],X.[SQL] As [SQL] FROM [EventView] AS A
CROSS JOIN [Incident] AS X
WHERE
patindex('%' + A.[Col] + '%', X.[SQL]) > 0
) AS INC
)
And yes, you can reference common table expression inside common table expression definition. Even recursively. Which leads to some very neat tricks.
Android textview usage as label and value
You can use <LinearLayout>
to group elements horizontaly. Also you should use style to set margins, background and other properties. This will allow you not to repeat code for every label you use.
Here is an example:
<LinearLayout
style="@style/FormItem"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
style="@style/FormLabel"
android:layout_width="wrap_content"
android:layout_height="@dimen/default_element_height"
android:text="@string/name_label"
/>
<EditText
style="@style/FormText.Editable"
android:id="@+id/cardholderName"
android:layout_width="wrap_content"
android:layout_height="@dimen/default_element_height"
android:layout_weight="1"
android:gravity="right|center_vertical"
android:hint="@string/card_name_hint"
android:imeOptions="actionNext"
android:singleLine="true"
/>
</LinearLayout>
Also you can create a custom view base on the layout above.
Have you looked at Creating custom view ?
Make browser window blink in task Bar
function blinkTab() {
const browserTitle = document.title;
let timeoutId;
let message = 'My New Title';
const stopBlinking = () => {
document.title = browserTitle;
clearInterval(timeoutId);
};
const startBlinking = () => {
document.title = document.title === message ? browserTitle : message;
};
function registerEvents() {
window.addEventListener("focus", function(event) {
stopBlinking();
});
window.addEventListener("blur", function(event) {
const timeoutId = setInterval(startBlinking, 500);
});
};
registerEvents();
};
blinkTab();
Simple tool to 'accept theirs' or 'accept mine' on a whole file using git
Based on kynan's answer, here are the same aliases, modified so they can handle spaces and initial dashes in filenames:
accept-ours = "!f() { [ -z \"$@\" ] && set - '.'; git checkout --ours -- \"$@\"; git add -u -- \"$@\"; }; f"
accept-theirs = "!f() { [ -z \"$@\" ] && set - '.'; git checkout --theirs -- \"$@\"; git add -u -- \"$@\"; }; f"
How do I force Postgres to use a particular index?
The question on itself is very much invalid. Forcing (by doing enable_seqscan=off for example) is very bad idea. It might be useful to check if it will be faster, but production code should never use such tricks.
Instead - do explain analyze of your query, read it, and find out why PostgreSQL chooses bad (in your opinion) plan.
There are tools on the web that help with reading explain analyze output - one of them is explain.depesz.com - written by me.
Another option is to join #postgresql channel on freenode irc network, and talking to guys there to help you out - as optimizing query is not a matter of "ask a question, get answer be happy". it's more like a conversation, with many things to check, many things to be learned.
Adding a rule in iptables in debian to open a new port
(I presume that you've concluded that it's an iptables problem by dropping the firewall completely (iptables -P INPUT ACCEPT; iptables -P OUTPUT ACCEPT; iptables -F) and confirmed that you can connect to the MySQL server from your Windows box?)
Some previous rule in the INPUT table is probably rejecting or dropping the packet. You can get around that by inserting the new rule at the top, although you might want to review your existing rules to see whether that's sensible:
iptables -I INPUT 1 -p tcp --dport 3306 -j ACCEPT
Note that iptables-save won't save the new rule persistently (i.e. across reboots) - you'll need to figure out something else for that. My usual route is to store the iptables-save output in a file (/etc/network/iptables.rules or similar) and then load then with a pre-up statement in /etc/network/interfaces).
java.lang.UnsupportedClassVersionError: Bad version number in .class file?
I also got the same error. Reason for that I was compiling the project using Maven. I had JAVA_HOME pointing to JDK7 and hence java 1.7 was being used for compilation and when running the project I was using JDK1.5. Changing the below entry in .classpath file or change in the eclipse as in the screenshot resolved the issue.
classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/J2SE-1.5
or change in the run configuarions of eclipse as
How to count down in for loop?
In python, when you have an iterable, usually you iterate without an index:
letters = 'abcdef' # or a list, tupple or other iterable
for l in letters:
print(l)
If you need to traverse the iterable in reverse order, you would do:
for l in letters[::-1]:
print(l)
When for any reason you need the index, you can use enumerate
:
for i, l in enumerate(letters, start=1): #start is 0 by default
print(i,l)
You can enumerate in reverse order too...
for i, l in enumerate(letters[::-1])
print(i,l)
ON ANOTHER NOTE...
Usually when we traverse an iterable we do it to apply the same procedure or function to each element. In these cases, it is better to use map
:
If we need to capitilize each letter:
map(str.upper, letters)
Or get the Unicode code of each letter:
map(ord, letters)
how to convert object into string in php
You can tailor how your object is represented as a string by implementing a __toString()
method in your class, so that when your object is type cast as a string (explicit type cast $str = (string) $myObject;
, or automatic echo $myObject
) you can control what is included and the string format.
If you only want to display your object's data, the method above would work. If you want to store your object in a session or database, you need to serialize it, so PHP knows how to reconstruct your instance.
Some code to demonstrate the difference:
class MyObject {
protected $name = 'JJ';
public function __toString() {
return "My name is: {$this->name}\n";
}
}
$obj = new MyObject;
echo $obj;
echo serialize($obj);
Output:
My name is: JJ
O:8:"MyObject":1:{s:7:"*name";s:2:"JJ";}
How do you split and unsplit a window/view in Eclipse IDE?
This is possible with the menu items Window>Editor>Toggle Split Editor.
Current shortcut for splitting is:
Azerty keyboard:
- Ctrl + _ for split horizontally, and
- Ctrl + { for split vertically.
Qwerty US keyboard:
- Ctrl + Shift + - (accessing _) for split horizontally, and
- Ctrl + Shift + [ (accessing {) for split vertically.
MacOS - Qwerty US keyboard:
- ⌘ + Shift + - (accessing _) for split horizontally, and
- ⌘ + Shift + [ (accessing {) for split vertically.
On any other keyboard if a required key is unavailable (like { on a german Qwertz keyboard), the following generic approach may work:
- Alt + ASCII code + Ctrl then release Alt
Example: ASCII for '{' = 123, so press 'Alt', '1', '2', '3', 'Ctrl' and release 'Alt', effectively typing '{' while 'Ctrl' is pressed, to split vertically.
Example of vertical split:
PS:
- The menu items Window>Editor>Toggle Split Editor were added with Eclipse Luna 4.4 M4, as mentioned by Lars Vogel in "Split editor implemented in Eclipse M4 Luna"
- The split editor is one of the oldest and most upvoted Eclipse bug! Bug 8009
- The split editor functionality has been developed in Bug 378298, and will be available as of Eclipse Luna M4. The Note & Newsworthy of Eclipse Luna M4 will contain the announcement.
force line break in html table cell
Try using
<table border="1" cellspacing="0" cellpadding="0" class="template-table"
style="table-layout: fixed; width: 100%">
as table style along with
<td style="word-break:break-word">long text</td>
for td
it works for normal/real scenario text with words, not for random typed letters without gaps
How to increase timeout for a single test case in mocha
(since I ran into this today)
Be careful when using ES2015 fat arrow syntax:
This will fail :
it('accesses the network', done => {
this.timeout(500); // will not work
// *this* binding refers to parent function scope in fat arrow functions!
// i.e. the *this* object of the describe function
done();
});
EDIT: Why it fails:
As @atoth mentions in the comments, fat arrow functions do not have their own this binding. Therefore, it's not possible for the it function to bind to this of the callback and provide a timeout function.
Bottom line: Don't use arrow functions for functions that need an increased timeout.
The network path was not found
Same problem with me. I solved this by adding @
before connection string (C# has a thing called 'String Literals') like so:
SqlConnection sconnection = new SqlConnection(@"Data Source=(Localdb)\v11.0; Initial Catalog=Mydatabase;Integrated Security=True");
sconnection.Open();
textarea character limit
I found a good solution that uses the maxlength attribute if the browser supports it, and falls back to an unobtrusive javascript pollyfill in unsupporting browsers.
Thanks to @Dan Tello's comment I fixed it up so it works in IE7+ as well:
HTML:
<textarea maxlength="50" id="text">This textarea has a character limit of 50.</textarea>
Javascript:
function maxLength(el) {
if (!('maxLength' in el)) {
var max = el.attributes.maxLength.value;
el.onkeypress = function () {
if (this.value.length >= max) return false;
};
}
}
maxLength(document.getElementById("text"));
Demo
There is no such thing as a minlength
attribute in HTML5.
For the following input types: number
, range
, date
, datetime
, datetime-local
, month
, time
, and week
(which aren't fully supported yet) use the min
and max
attributes.
ORA-01950: no privileges on tablespace 'USERS'
You cannot insert data because you have a quota of 0 on the tablespace. To fix this, run
ALTER USER <user> quota unlimited on <tablespace name>;
or
ALTER USER <user> quota 100M on <tablespace name>;
as a DBA user (depending on how much space you need / want to grant).
Get last n lines of a file, similar to tail
Posting an answer at the behest of commenters on my answer to a similar question where the same technique was used to mutate the last line of a file, not just get it.
For a file of significant size, mmap
is the best way to do this. To improve on the existing mmap
answer, this version is portable between Windows and Linux, and should run faster (though it won't work without some modifications on 32 bit Python with files in the GB range, see the other answer for hints on handling this, and for modifying to work on Python 2).
import io # Gets consistent version of open for both Py2.7 and Py3.x
import itertools
import mmap
def skip_back_lines(mm, numlines, startidx):
'''Factored out to simplify handling of n and offset'''
for _ in itertools.repeat(None, numlines):
startidx = mm.rfind(b'\n', 0, startidx)
if startidx < 0:
break
return startidx
def tail(f, n, offset=0):
# Reopen file in binary mode
with io.open(f.name, 'rb') as binf, mmap.mmap(binf.fileno(), 0, access=mmap.ACCESS_READ) as mm:
# len(mm) - 1 handles files ending w/newline by getting the prior line
startofline = skip_back_lines(mm, offset, len(mm) - 1)
if startofline < 0:
return [] # Offset lines consumed whole file, nothing to return
# If using a generator function (yield-ing, see below),
# this should be a plain return, no empty list
endoflines = startofline + 1 # Slice end to omit offset lines
# Find start of lines to capture (add 1 to move from newline to beginning of following line)
startofline = skip_back_lines(mm, n, startofline) + 1
# Passing True to splitlines makes it return the list of lines without
# removing the trailing newline (if any), so list mimics f.readlines()
return mm[startofline:endoflines].splitlines(True)
# If Windows style \r\n newlines need to be normalized to \n, and input
# is ASCII compatible, can normalize newlines with:
# return mm[startofline:endoflines].replace(os.linesep.encode('ascii'), b'\n').splitlines(True)
This assumes the number of lines tailed is small enough you can safely read them all into memory at once; you could also make this a generator function and manually read a line at a time by replacing the final line with:
mm.seek(startofline)
# Call mm.readline n times, or until EOF, whichever comes first
# Python 3.2 and earlier:
for line in itertools.islice(iter(mm.readline, b''), n):
yield line
# 3.3+:
yield from itertools.islice(iter(mm.readline, b''), n)
Lastly, this read in binary mode (necessary to use mmap
) so it gives str
lines (Py2) and bytes
lines (Py3); if you want unicode
(Py2) or str
(Py3), the iterative approach could be tweaked to decode for you and/or fix newlines:
lines = itertools.islice(iter(mm.readline, b''), n)
if f.encoding: # Decode if the passed file was opened with a specific encoding
lines = (line.decode(f.encoding) for line in lines)
if 'b' not in f.mode: # Fix line breaks if passed file opened in text mode
lines = (line.replace(os.linesep, '\n') for line in lines)
# Python 3.2 and earlier:
for line in lines:
yield line
# 3.3+:
yield from lines
Note: I typed this all up on a machine where I lack access to Python to test. Please let me know if I typoed anything; this was similar enough to my other answer that I think it should work, but the tweaks (e.g. handling an offset
) could lead to subtle errors. Please let me know in the comments if there are any mistakes.
Reading a file character by character in C
The problem here is twofold
- a) you increment the pointer before you check the value read in, and
- b) you ignore the fact that
fgetc()
returns an int instead of a char.
The first is easily fixed:
char *orig = code; // the beginning of the array
// ...
do {
*code = fgetc(file);
} while(*code++ != EOF);
*code = '\0'; // nul-terminate the string
return orig; // don't return a pointer to the end
The second problem is more subtle -fgetc
returns an int so that the EOF
value can be distinguished from any possible char value. Fixing this uses a temporary int for the EOF
check and probably a regular while loop instead of do / while.
Regular expression to find two strings anywhere in input
you don't have to use regex. In your favourite language, split on spaces, go over the splitted words, check for cat and mat. eg in Python
>>> for line in open("file"):
... g=0;f=0
... s = line.split()
... for item in s:
... if item =="cat": f=1
... if item =="mat": g=1
... if (g,f)==(1,1): print "found: " ,line.rstrip()
found: The cat slept on the mat in front of the fire.
found: At 5:00 pm, I found the cat scratching the wool off the mat.
Ruby Array find_first object?
use array detect
method if you wanted to return first value where block returns true
[1,2,3,11,34].detect(&:even?) #=> 2
OR
[1,2,3,11,34].detect{|i| i.even?} #=> 2
If you wanted to return all values where block returns true then use select
[1,2,3,11,34].select(&:even?) #=> [2, 34]
How do I get my Maven Integration tests to run
You can set up Maven's Surefire to run unit tests and integration tests separately. In the standard unit test phase you run everything that does not pattern match an integration test. You then create a second test phase that runs just the integration tests.
Here is an example:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<excludes>
<exclude>**/*IntegrationTest.java</exclude>
</excludes>
</configuration>
<executions>
<execution>
<id>integration-test</id>
<goals>
<goal>test</goal>
</goals>
<phase>integration-test</phase>
<configuration>
<excludes>
<exclude>none</exclude>
</excludes>
<includes>
<include>**/*IntegrationTest.java</include>
</includes>
</configuration>
</execution>
</executions>
</plugin>
How do I find which rpm package supplies a file I'm looking for?
The most popular answer is incomplete:
Since this search will generally be performed only for files from installed packages, yum whatprovides is made blisteringly fast by disabling all external repos (the implicit "installed" repo can't be disabled).
yum --disablerepo=* whatprovides <file>
Excel column number from column name
You could skip all this and just put your data in a table. Then refer to the table and header and it will be completely dynamic. I know this is from 3 years ago but someone may still find this useful.
Example code:
Activesheet.Range("TableName[ColumnName]").Copy
You can also use :
activesheet.listobjects("TableName[ColumnName]").Copy
You can even use this reference system in worksheet formulas as well. Its very dynamic.
Hope this helps!
Call JavaScript function from C#
This may be helpful to you:
<script type="text/javascript">
function Showalert() {
alert('Profile not parsed!!');
window.parent.parent.parent.location.reload();
}
function ImportingDone() {
alert('Importing done successfull.!');
window.parent.parent.parent.location.reload();
}
</script>
if (SelectedRowCount == 0)
{
ScriptManager.RegisterStartupScript(this, GetType(), "displayalertmessage", "Showalert();", true);
}
else
{
ScriptManager.RegisterStartupScript(this, GetType(), "importingdone", "ImportingDone();", true);
}
Get Wordpress Category from Single Post
For the lazy and the learning, to put it into your theme, Rfvgyhn's full code
<?php $category = get_the_category();
$firstCategory = $category[0]->cat_name; echo $firstCategory;?>
else & elif statements not working in Python
The problem is the blank line you are typing before the else
or elif
. Pay attention to the prompt you're given. If it is >>>
, then Python is expecting the start of a new statement. If it is ...
, then it's expecting you to continue a previous statement.
Any way of using frames in HTML5?
Now, there are plenty of example of me answering questions with essays on why following validation rules are important. I've also said that sometimes you just have to be a rebel and break the rules, and document the reasons.
You can see in this example that framesets do work in HTML5 still. I had to download the code and add an HTML5 doctype at the top, however. But the frameset element was still recognized, and the desired result was achieved.
Therefore, knowing that using framesets is completely absurd, and knowing that you have to use this as dictated by your professor/teacher, you could just deal with the single validation error in the W3C validator and use both the HTML5 video element as well as the deprecated frameset element.
<!DOCTYPE html>
<html>
<head>
</head>
<!-- frameset is deprecated in html5, but it still works. -->
<frameset framespacing="0" rows="150,*" frameborder="0" noresize>
<frame name="top" src="http://www.npscripts.com/framer/demo-top.html" target="top">
<frame name="main" src="http://www.google.com" target="main">
</frameset>
</html>
Keep in mind that if it's a project for school, it's most likely not going to be something that will be around in a year or two once the browser vendors remove frameset support for HTML5 completely. Just know that you are right and just do what your teacher/professor asks just to get the grade :)
UPDATE:
The toplevel parent doc uses XHTML and the frame uses HTML5. The validator did not complain about the frameset being illegal, and it didn't complain about the video element.
index.php:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd">
<html>
<head>
</head>
<frameset framespacing="0" rows="150,*" frameborder="0" noresize>
<frame name="top" src="http://www.npscripts.com/framer/demo-top.html" target="top">
<frame name="main" src="video.html" target="main">
</frameset>
</html>
video.html:
<!doctype html>
<html>
<head>
</head>
<body>
<div id="player-container">
<div class="arrow"></div>
<div class="player">
<video id="vid1" width="480" height="267"
poster="http://cdn.kaltura.org/apis/html5lib/kplayer-examples/media/bbb480.jpg"
durationHint="33" controls>
<source src="http://cdn.kaltura.org/apis/html5lib/kplayer-examples/media/bbb_trailer_iphone.m4v" />
<source src="http://cdn.kaltura.org/apis/html5lib/kplayer-examples/media/bbb400p.ogv" />
</video>
</div>
</body>
</html>
Want to show/hide div based on dropdown box selection
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function(){
$('#purpose').on('change', function() {
if ( this.value == '1')
//.....................^.......
{
$("#business_new").hide();
$("#business").show();
}
else if ( this.value == '2')
{
$("#business").hide();
$("#business_new").show();
}
else
{
$("#business").hide();
}
});
});
</script>
<body>
<select id='purpose'>
<option value="0">Personal use</option>
<option value="1">Business use</option>
<option value="2">Passing on to a client</option>
</select>
<div style='display:none;' id='business'>Business Name<br/>
<br/>
<input type='text' class='text' name='business' value size='20' />
<input type='text' class='text' name='business' value size='20' />
<br/>
</div>
<div style='display:none;' id='business_new'>Business Name<br/>
<br/>
<input type='text' class='text' name='business' value="1254" size='20' />
<input type='text' class='text' name='business' value size='20' />
<br/>
</div>
</body>
What rules does software version numbering follow?
The usual method I have seen is X.Y.Z, which generally corresponds to major.minor.patch:
- Major version numbers change whenever there is some significant change being introduced. For example, a large or potentially backward-incompatible change to a software package.
- Minor version numbers change when a new, minor feature is introduced or when a set of smaller features is rolled out.
- Patch numbers change when a new build of the software is released to customers. This is normally for small bug-fixes or the like.
Other variations use build numbers as an additional identifier. So you may have a large number for X.Y.Z.build if you have many revisions that are tested between releases. I use a couple of packages that are identified by year/month or year/release. Thus, a release in the month of September of 2010 might be 2010.9 or 2010.3 for the 3rd release of this year.
There are many variants to versioning. It all boils down to personal preference.
For the "1.3v1.1", that may be two different internal products, something that would be a shared library / codebase that is rev'd differently from the main product; that may indicate version 1.3 for the main product, and version 1.1 of the internal library / package.
Highlight text similar to grep, but don't filter out text
You can do it using only grep by:
- reading the file line by line
- matching a pattern in each line and highlighting pattern by grep
- if there is no match, echo the line as is
which gives you the following:
while read line ; do (echo $line | grep PATTERN) || echo $line ; done < inputfile
check if jquery has been loaded, then load it if false
var f = ()=>{
if (!window.jQuery) {
var e = document.createElement('script');
e.src = "https://code.jquery.com/jquery-3.2.1.min.js";
e.onload = function () {
jQuery.noConflict();
console.log('jQuery ' + jQuery.fn.jquery + ' injected.');
};
document.head.appendChild(e);
} else {
console.log('jQuery ' + jQuery.fn.jquery + '');
}
};
f();
Locate current file in IntelliJ
Do following will select your file automatically all time.
- Right click on Project/Packages area > Autoscroll to Source.
- Right click on Project/Packages area > Autoscroll from Source.
Please find image below.
How do I iterate through children elements of a div using jQuery?
It is also possible to iterate through all elements within a specific context, no mattter how deeply nested they are:
$('input', $('#mydiv')).each(function () {
console.log($(this)); //log every element found to console output
});
The second parameter $('#mydiv') which is passed to the jQuery 'input' Selector is the context. In this case the each() clause will iterate through all input elements within the #mydiv container, even if they are not direct children of #mydiv.
Setting the MySQL root user password on OS X
I solved this by:
- Shutting down my MySQL server:
mysql.server stop
- Running MySQL in safe mode:
mysqld_safe --skip-grant-tables
- In another terminal, login with
mysql -u root
- In the same terminal, run
UPDATE mysql.user SET authentication_string=null WHERE User='root';
, then FLUSH PRIVILEGES;
and then exit with exit;
- Stop the safe mode server with
mysql.server stop
and then start the normal one; mysql.server start
Now you can set your new password with
ALTER USER 'root'@'localhost' IDENTIFIED WITH caching_sha2_password BY 'yourpasswd';
React.js create loop through Array
In CurrentGame
component you need to change initial state because you are trying use loop for participants
but this property is undefined
that's why you get error.,
getInitialState: function(){
return {
data: {
participants: []
}
};
},
also, as player
in .map
is Object
you should get properties from it
this.props.data.participants.map(function(player) {
return <li key={player.championId}>{player.summonerName}</li>
// -------------------^^^^^^^^^^^---------^^^^^^^^^^^^^^
})
Example
Reason to Pass a Pointer by Reference in C++?
David's answer is correct, but if it's still a little abstract, here are two examples:
You might want to zero all freed pointers to catch memory problems earlier. C-style you'd do:
void freeAndZero(void** ptr)
{
free(*ptr);
*ptr = 0;
}
void* ptr = malloc(...);
...
freeAndZero(&ptr);
In C++ to do the same, you might do:
template<class T> void freeAndZero(T* &ptr)
{
delete ptr;
ptr = 0;
}
int* ptr = new int;
...
freeAndZero(ptr);
When dealing with linked-lists - often simply represented as pointers to a next node:
struct Node
{
value_t value;
Node* next;
};
In this case, when you insert to the empty list you necessarily must change the incoming pointer because the result is not the NULL
pointer anymore. This is a case where you modify an external pointer from a function, so it would have a reference to pointer in its signature:
void insert(Node* &list)
{
...
if(!list) list = new Node(...);
...
}
There's an example in this question.
How to read keyboard-input?
It seems that you are mixing different Pythons here (Python 2.x vs. Python 3.x)...
This is basically correct:
nb = input('Choose a number: ')
The problem is that it is only supported in Python 3. As @sharpner answered, for older versions of Python (2.x), you have to use the function raw_input
:
nb = raw_input('Choose a number: ')
If you want to convert that to a number, then you should try:
number = int(nb)
... though you need to take into account that this can raise an exception:
try:
number = int(nb)
except ValueError:
print("Invalid number")
And if you want to print the number using formatting, in Python 3 str.format()
is recommended:
print("Number: {0}\n".format(number))
Instead of:
print('Number %s \n' % (nb))
But both options (str.format()
and %
) do work in both Python 2.7 and Python 3.
ValueError: math domain error
You are trying to do a logarithm of something that is not positive.
Logarithms figure out the base after being given a number and the power it was raised to. log(0)
means that something raised to the power of 2
is 0
. An exponent can never result in 0
*, which means that log(0)
has no answer, thus throwing the math domain error
*Note: 0^0
can result in 0
, but can also result in 1
at the same time. This problem is heavily argued over.
How to avoid Number Format Exception in java?
I don't know about the runtime disadvantages about the following but you could run a regexp match on your string to make sure it is a number before trying to parse it, thus
cost.matches("-?\\d+\\.?\\d+")
for a float
and
cost.matches("-?\\d+")
for an integer
EDIT
please notices @Voo's comment about max int
How to add a search box with icon to the navbar in Bootstrap 3?
I tried @PhilNicholas 's code and got the same problem of @its_me said in the comments that search bar show up on the next line of navbar, and I found that form
need to be added an attribute width
.
<form role="search" style="width: 15em; margin: 0.3em 2em;">
<div class="input-group">
<input type="text" class="form-control" placeholder="Search">
<div class="input-group-btn">
<button type="submit" class="btn btn-default">
<span class="glyphicon glyphicon-search"></span>
</button>
</div>
</div>
</form>
What is the syntax to insert one list into another list in python?
The question does not make clear what exactly you want to achieve.
List has the append
method, which appends its argument to the list:
>>> list_one = [1,2,3]
>>> list_two = [4,5,6]
>>> list_one.append(list_two)
>>> list_one
[1, 2, 3, [4, 5, 6]]
There's also the extend
method, which appends items from the list you pass as an argument:
>>> list_one = [1,2,3]
>>> list_two = [4,5,6]
>>> list_one.extend(list_two)
>>> list_one
[1, 2, 3, 4, 5, 6]
And of course, there's the insert
method which acts similarly to append
but allows you to specify the insertion point:
>>> list_one.insert(2, list_two)
>>> list_one
[1, 2, [4, 5, 6], 3, 4, 5, 6]
To extend a list at a specific insertion point you can use list slicing (thanks, @florisla):
>>> l = [1, 2, 3, 4, 5]
>>> l[2:2] = ['a', 'b', 'c']
>>> l
[1, 2, 'a', 'b', 'c', 3, 4, 5]
List slicing is quite flexible as it allows to replace a range of entries in a list with a range of entries from another list:
>>> l = [1, 2, 3, 4, 5]
>>> l[2:4] = ['a', 'b', 'c'][1:3]
>>> l
[1, 2, 'b', 'c', 5]
Redirect Windows cmd stdout and stderr to a single file
Correct, file handle 1 for the process is STDOUT, redirected by the 1>
or by >
(1 can be omitted, by convention, the command interpreter [cmd.exe] knows to handle that).
File handle 2 is STDERR, redirected by 2>
.
Note that if you're using these to make log files, then unless you're sending the outut to _uniquely_named_ (eg date-and-time-stamped) log files, then if you run the same process twice, the redirected will overwrite (replace) the previous log file.
The >>
(for either STDOUT or STDERR) will APPEND not REPLACE the file. So you get a cumulative logfile, showwing the results from all runs of the process - typically more useful.
Happy trails...
mySQL select IN range
To select data in numerical range you can use BETWEEN
which is inclusive.
SELECT JOB FROM MYTABLE WHERE ID BETWEEN 10 AND 15;
Disable submit button ONLY after submit
$(document).ready(function() {
$(body).submit(function () {
var btn = $(this).find("input[type=submit]:focus");
if($(btn).prop("id") == "YourButtonID")
$(btn).attr("disabled", "true");
});
}
Logout button php
Instead of a button, put a link and navigate it to another page
<a href="logout.php">Logout</a>
Then in logout.php
page, use
session_start();
session_destroy();
header('Location: login.php');
exit;
How to generate UL Li list from string array using jquery?
var countries = ['United States', 'Canada', 'Argentina', 'Armenia'];
var cList = $('ul.mylist')
$.each(countries, function(i)
{
var li = $('<li/>')
.addClass('ui-menu-item')
.attr('role', 'menuitem')
.appendTo(cList);
var aaa = $('<a/>')
.addClass('ui-all')
.text(countries[i])
.appendTo(li);
});
Importing from a relative path in Python
Doing a relative import is absolulutely OK! Here's what little 'ol me does:
#first change the cwd to the script path
scriptPath = os.path.realpath(os.path.dirname(sys.argv[0]))
os.chdir(scriptPath)
#append the relative location you want to import from
sys.path.append("../common")
#import your module stored in '../common'
import common.py
Android: where are downloaded files saved?
Most devices have some form of emulated storage. if they support sd cards they are usually mounted to /sdcard
(or some variation of that name) which is usually symlinked to to a directory in /storage
like /storage/sdcard0
or /storage/0
sometimes the emulated storage is mounted to /sdcard
and the actual path is something like /storage/emulated/legacy. You should be able to use to get the downloads directory. You are best off using the api calls to get directories.
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
Since the filesystems and sdcard support varies among devices.
see similar question for more info how to access downloads folder in android?
Usually the DownloadManager handles downloads and the files are then accessed by requesting the file's uri fromthe download manager using a file id to get where file was places which would usually be somewhere in the sdcard/ real or emulated since apps can only read data from certain places on the filesystem outside of their data directory like the sdcard
getElementById in React
You may have to perform a diff and put document.getElementById('name')
code inside a condition, in case your component is something like this:
// using the new hooks API
function Comp(props) {
const { isLoading, data } = props;
useEffect(() => {
if (data) {
var name = document.getElementById('name').value;
}
}, [data]) // this diff is necessary
if (isLoading) return <div>isLoading</div>
return (
<div id='name'>Comp</div>
);
}
If diff is not performed then, you will get null
.
What's the best way to determine the location of the current PowerShell script?
PowerShell 3+
# This is an automatic variable set to the current file's/module's directory
$PSScriptRoot
PowerShell 2
Prior to PowerShell 3, there was not a better way than querying the
MyInvocation.MyCommand.Definition
property for general scripts. I had the following line at the top of essentially every PowerShell script I had:
$scriptPath = split-path -parent $MyInvocation.MyCommand.Definition
GetType used in PowerShell, difference between variables
Select-Object returns a custom PSObject with just the properties specified. Even with a single property, you don't get the ACTUAL variable; it is wrapped inside the PSObject.
Instead, do:
Get-Date | Select-Object -ExpandProperty DayOfWeek
That will get you the same result as:
(Get-Date).DayOfWeek
The difference is that if Get-Date returns multiple objects, the pipeline way works better than the parenthetical way as (Get-ChildItem)
, for example, is an array of items. This has changed in PowerShell v3 and (Get-ChildItem).FullPath
works as expected and returns an array of just the full paths.
Call an angular function inside html
Yep, just add parenthesis (calling the function). Make sure the function is in scope and actually returns something.
<ul class="ui-listview ui-radiobutton" ng-repeat="meter in meters">
<li class = "ui-divider">
{{ meter.DESCRIPTION }}
{{ htmlgeneration() }}
</li>
</ul>
How do I trim leading/trailing whitespace in a standard way?
void trim(char* const str)
{
char* begin = str;
char* end = str;
while (isspace(*begin))
{
++begin;
}
char* s = begin;
while (*s != '\0')
{
if (!isspace(*s++))
{
end = s;
}
}
*end = '\0';
const int dist = end - begin;
if (begin > str && dist > 0)
{
memmove(str, begin, dist + 1);
}
}
Modifies string in place, so you can still delete it.
Doesn't use fancy pants library functions (unless you consider memmove fancy).
Handles string overlap.
Trims front and back (not middle, sorry).
Fast if string is large (memmove often written in assembly).
Only moves characters if required (I find this true in most use cases because strings rarely have leading spaces and often don't have tailing spaces)
I would like to test this but I'm running late. Enjoy finding bugs... :-)
Can I draw rectangle in XML?
Create rectangle.xml
using Shape Drawable Like this put in to your Drawable Folder...
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
<solid android:color="@android:color/transparent"/>
<corners android:radius="12px"/>
<stroke android:width="2dip" android:color="#000000"/>
</shape>
put it in to an ImageView
<ImageView
android:id="@+id/rectimage"
android:layout_height="150dp"
android:layout_width="150dp"
android:src="@drawable/rectangle">
</ImageView>
Hope this will help you.
Convert cells(1,1) into "A1" and vice versa
The Address property of a cell can get this for you:
MsgBox Cells(1, 1).Address(RowAbsolute:=False, ColumnAbsolute:=False)
returns A1
.
The other way around can be done with the Row
and Column
property of Range
:
MsgBox Range("A1").Row & ", " & Range("A1").Column
returns 1,1
.
FPDF error: Some data has already been output, can't send PDF
For fpdf to work properly, there cannot be any output at all beside what fpdf generates. For example, this will work:
<?php
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');
$pdf->Output();
?>
While this will not (note the leading space before the opening <?
tag)
<?php
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');
$pdf->Output();
?>
Also, this will not work either (the echo
will break it):
<?php
echo "About to create pdf";
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');
$pdf->Output();
?>
I'm not sure about the drupal side of things, but I know that absolutely zero non-fpdf output is a requirement for fpdf to work.
add ob_start ();
at the top and at the end add ob_end_flush();
<?php
ob_start();
require('fpdf.php');
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');
$pdf->Output();
ob_end_flush();
?>
give me an error as below:
FPDF error: Some data has already been output, can't send PDF
to over come this error:
go to fpdf.php
in that,goto line number 996
function Output($name='', $dest='')
after that make changes like this:
function Output($name='', $dest='') {
ob_clean();
Hi do you have a session header on the top of your page.
or any includes
If you have then try to add this codes on top pf your page it should works fine.
<?
while (ob_get_level())
ob_end_clean();
header("Content-Encoding: None", true);
?>
cheers :-)
In my case i had set:
ini_set('display_errors', 'on');
error_reporting(E_ALL | E_STRICT);
When i made the request to generate the report, some warnings were displayed in the browser (like the usage of deprecated functions).
Turning off
the display_errors
option, the report was generated successfully.
How to update primary key
You could use this recursive function for generate necessary T-SQL script.
CREATE FUNCTION dbo.Update_Delete_PrimaryKey
(
@TableName NVARCHAR(255),
@ColumnName NVARCHAR(255),
@OldValue NVARCHAR(MAX),
@NewValue NVARCHAR(MAX),
@Del BIT
)
RETURNS NVARCHAR
(
MAX
)
AS
BEGIN
DECLARE @fks TABLE
(
constraint_name NVARCHAR(255),
table_name NVARCHAR(255),
col NVARCHAR(255)
);
DECLARE @Sql NVARCHAR(MAX),
@EnableConstraints NVARCHAR(MAX);
SET @Sql = '';
SET @EnableConstraints = '';
INSERT INTO @fks
(
constraint_name,
table_name,
col
)
SELECT oConstraint.name constraint_name,
oParent.name table_name,
oParentCol.name col
FROM sys.foreign_key_columns sfkc
--INNER JOIN sys.foreign_keys sfk
-- ON sfk.[object_id] = sfkc.constraint_object_id
INNER JOIN sys.sysobjects oConstraint
ON sfkc.constraint_object_id = oConstraint.id
INNER JOIN sys.sysobjects oParent
ON sfkc.parent_object_id = oParent.id
INNER JOIN sys.all_columns oParentCol
ON sfkc.parent_object_id = oParentCol.object_id
AND sfkc.parent_column_id = oParentCol.column_id
INNER JOIN sys.sysobjects oReference
ON sfkc.referenced_object_id = oReference.id
INNER JOIN sys.all_columns oReferenceCol
ON sfkc.referenced_object_id = oReferenceCol.object_id
AND sfkc.referenced_column_id = oReferenceCol.column_id
WHERE oReference.name = @TableName
AND oReferenceCol.name = @ColumnName
--AND (@Del <> 1 OR sfk.delete_referential_action = 0)
--AND (@Del = 1 OR sfk.update_referential_action = 0)
IF EXISTS(
SELECT 1
FROM @fks
)
BEGIN
DECLARE @Constraint NVARCHAR(255),
@Table NVARCHAR(255),
@Col NVARCHAR(255)
DECLARE Table_Cursor CURSOR LOCAL
FOR
SELECT f.constraint_name,
f.table_name,
f.col
FROM @fks AS f
OPEN Table_Cursor FETCH NEXT FROM Table_Cursor INTO @Constraint, @Table,@Col
WHILE (@@FETCH_STATUS = 0)
BEGIN
IF @Del <> 1
BEGIN
SET @Sql = @Sql + 'ALTER TABLE ' + @Table + ' NOCHECK CONSTRAINT ' + @Constraint + CHAR(13) + CHAR(10);
SET @EnableConstraints = @EnableConstraints + 'ALTER TABLE ' + @Table + ' CHECK CONSTRAINT ' + @Constraint
+ CHAR(13) + CHAR(10);
END
SET @Sql = @Sql + dbo.Update_Delete_PrimaryKey(@Table, @Col, @OldValue, @NewValue, @Del);
FETCH NEXT FROM Table_Cursor INTO @Constraint, @Table,@Col
END
CLOSE Table_Cursor DEALLOCATE Table_Cursor
END
DECLARE @DataType NVARCHAR(30);
SELECT @DataType = t.name +
CASE
WHEN t.name IN ('char', 'varchar', 'nchar', 'nvarchar') THEN '(' +
CASE
WHEN c.max_length = -1 THEN 'MAX'
ELSE CONVERT(
VARCHAR(4),
CASE
WHEN t.name IN ('nchar', 'nvarchar') THEN c.max_length / 2
ELSE c.max_length
END
)
END + ')'
WHEN t.name IN ('decimal', 'numeric') THEN '(' + CONVERT(VARCHAR(4), c.precision) + ','
+ CONVERT(VARCHAR(4), c.Scale) + ')'
ELSE ''
END
FROM sys.columns c
INNER JOIN sys.types t
ON c.user_type_id = t.user_type_id
WHERE c.object_id = OBJECT_ID(@TableName)
AND c.name = @ColumnName
IF @Del <> 1
BEGIN
SET @Sql = @Sql + 'UPDATE [' + @TableName + '] SET [' + @ColumnName + '] = CONVERT(' + @DataType + ', ' + ISNULL('N''' + @NewValue + '''', 'NULL')
+ ') WHERE [' + @ColumnName + '] = CONVERT(' + @DataType + ', ' + ISNULL('N''' + @OldValue + '''', 'NULL') +
');' + CHAR(13) + CHAR(10);
SET @Sql = @Sql + @EnableConstraints;
END
ELSE
SET @Sql = @Sql + 'DELETE [' + @TableName + '] WHERE [' + @ColumnName + '] = CONVERT(' + @DataType + ', N''' + @OldValue
+ ''');' + CHAR(13) + CHAR(10);
RETURN @Sql;
END
GO
DECLARE @Result NVARCHAR(MAX);
SET @Result = dbo.Update_Delete_PrimaryKey('@TableName', '@ColumnName', '@OldValue', '@NewValue', 0);/*Update*/
EXEC (@Result)
SET @Result = dbo.Update_Delete_PrimaryKey('@TableName', '@ColumnName', '@OldValue', NULL, 1);/*Delete*/
EXEC (@Result)
GO
DROP FUNCTION Update_Delete_PrimaryKey;
Colspan all columns
Maybe I'm a straight thinker but I'm a bit puzzled, don't you know the column number of your table?
By the way IE6 doesn't honor the colspan="0", with or without a colgroup defined.
I tried also to use thead and th to generate the groups of columns but the browser doesn't recognlise the form colspan="0".
I've tried with Firefox 3.0 on windows and linux and it works only with a strict doctype.
You can check a test on several bowser at
http://browsershots.org/http://hsivonen.iki.fi/test/wa10/tables/colspan-0.html
I found the test page here http://hsivonen.iki.fi/test/wa10/tables/colspan-0.html
Edit: Please copy and paste the link, the formatting won't accept the double protocol parts in the link (or I am not so smart to correctly format it).
How do I add an "Add to Favorites" button or link on my website?
I have faced some problems with rel="sidebar". when I add it in link tag bookmarking will work on FF but stop working in other browser. so I fix that by adding rel="sidebar" dynamic by code:
jQuery('.bookmarkMeLink').click(function() {
if (window.sidebar && window.sidebar.addPanel) {
// Mozilla Firefox Bookmark
window.sidebar.addPanel(document.title,window.location.href,'');
}
else if(window.sidebar && jQuery.browser.mozilla){
//for other version of FF add rel="sidebar" to link like this:
//<a id="bookmarkme" href="#" rel="sidebar" title="bookmark this page">Bookmark This Page</a>
jQuery(this).attr('rel', 'sidebar');
}
else if(window.external && ('AddFavorite' in window.external)) {
// IE Favorite
window.external.AddFavorite(location.href,document.title);
} else if(window.opera && window.print) {
// Opera Hotlist
this.title=document.title;
return true;
} else {
// webkit - safari/chrome
alert('Press ' + (navigator.userAgent.toLowerCase().indexOf('mac') != - 1 ? 'Command/Cmd' : 'CTRL') + ' + D to bookmark this page.');
}
});
What is the difference between exit(0) and exit(1) in C?
exit
in the C language takes an integer representing an exit status.
Exit Success
Typically, an exit status of 0 is considered a success, or an intentional exit caused by the program's successful execution.
Exit Failure
An exit status of 1 is considered a failure, and most commonly means that the program had to exit for some reason, and was not able to successfully complete everything in the normal program flow.
Here's a GNU Resource talking about Exit Status.
As @Als has stated, two constants should be used in place of 0 and 1.
EXIT_SUCCESS
is defined by the standard to be zero.
EXIT_FAILURE
is not restricted by the standard to be one, but many systems do implement it as one.
The localhost page isn’t working localhost is currently unable to handle this request. HTTP ERROR 500
If you are using the codeigniter framework and are testing the project on a localhost, open the main Index.php file of your project folder and find this code:
define('ENVIRONMENT', 'production');
Change it to
define ('ENVIRONMENT', 'development');
Because same this ENVIRONMENT is in your database.php file under config folder.
like this:
'db_debug' => (ENVIRONMENT! == 'development')
So the environment should be the same in both places and problem will be solved.
Entity Framework. Delete all rows in table
In my code I didn't really have nice access to the Database object, so you can do it on the DbSet where you also is allowed to use any kind of sql. It will sort of end out like this:
var p = await _db.Persons.FromSql("truncate table Persons;select top 0 * from Persons").ToListAsync();
Java :Add scroll into text area
After adding JTextArea into JScrollPane here:
scroll = new JScrollPane(display);
You don't need to add it again into other container like you do:
middlePanel.add(display);
Just remove that last line of code and it will work fine. Like this:
middlePanel=new JPanel();
middlePanel.setBorder(new TitledBorder(new EtchedBorder(), "Display Area"));
// create the middle panel components
display = new JTextArea(16, 58);
display.setEditable(false); // set textArea non-editable
scroll = new JScrollPane(display);
scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
//Add Textarea in to middle panel
middlePanel.add(scroll);
JScrollPane is just another container that places scrollbars around your component when its needed and also has its own layout. All you need to do when you want to wrap anything into a scroll just pass it into JScrollPane constructor:
new JScrollPane( myComponent )
or set view like this:
JScrollPane pane = new JScrollPane ();
pane.getViewport ().setView ( myComponent );
Additional:
Here is fully working example since you still did not get it working:
public static void main ( String[] args )
{
JPanel middlePanel = new JPanel ();
middlePanel.setBorder ( new TitledBorder ( new EtchedBorder (), "Display Area" ) );
// create the middle panel components
JTextArea display = new JTextArea ( 16, 58 );
display.setEditable ( false ); // set textArea non-editable
JScrollPane scroll = new JScrollPane ( display );
scroll.setVerticalScrollBarPolicy ( ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS );
//Add Textarea in to middle panel
middlePanel.add ( scroll );
// My code
JFrame frame = new JFrame ();
frame.add ( middlePanel );
frame.pack ();
frame.setLocationRelativeTo ( null );
frame.setVisible ( true );
}
And here is what you get:
Purpose of ESI & EDI registers?
Opcodes like MOVSB and MOVSW that efficiently copy data from the memory pointed to by ESI to the memory pointed to by EDI. Thus,
mov esi, source_address
mov edi, destination_address
mov ecx, byte_count
cld
rep movsb ; fast!
Plot multiple lines (data series) each with unique color in R
In case the x-axis is a factor / discrete variable, and one would like to keep the order of the variable (different values corresponding to different groups) to visualise the group effect. The following code wold do:
library(ggplot2)
set.seed(45)
# dummy data
df <- data.frame(x=rep(letters[1:5], 9), val=sample(1:100, 45),
variable=rep(paste0("category", 1:9), each=5))
# This ensures that x-axis (which is a factor variable) will be ordered appropriately
df$x <- ordered(df$x, levels=letters[1:5])
ggplot(data = df, aes(x=x, y=val, group=variable, color=variable)) + geom_line() + geom_point() + ggtitle("Multiple lines with unique color")
Also note that: adding group=variable remove the warning information: "geom_path: Each group consists of only one observation. Do you need to adjust
the group aesthetic?"
Call to undefined function mysql_query() with Login
I would recommend that start using mysqli_() and stop using mysql_()
Check the following page: LINK
Warning
This extension was deprecated in PHP 5.5.0, and it was removed
in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be
used. See also MySQL: choosing an API guide and related FAQ for more
information. Alternatives to this function include:
mysqli_affected_rows() PDOStatement::rowCount()
Try and use mysqli_() Or PDO
yii2 hidden input value
Hello World!
You see, the main question while using hidden input is what kind of data you want to pass?
I will assume that you are trying to pass the user ID.
Which is not a really good idea to pass it here because field() method will generate input
and the value will be shown to user as we can't hide html from the users browser. This if you really care about security of your website.
please check this link, and you will see that it's impossible to hide value attribute from users to see.
so what to do then?
See, this is the core of OOP in PHP.
and I quote from Matt Zandstr in his great book PHP Objects, Patterns, and Practice fifth edition
I am still stuck with a great deal of unwanted flexibility, though. I rely on the client coder to change a ShopProduct object’s properties from their default values. This is problematic in two ways. First, it takes five lines to properly initialize a ShopProduct object, and no coder will thank you for that. Second, I have no way of ensuring that any of the properties are set when a ShopProduct object is initialized. What I need is a method that is called automatically when an object is instantiated from a class.
Please check this example of using __construct() method which is mentioned in his book too.
class ShopProduct {
public $title;
public $producerMainName;
public $producerFirstName;
public $price = 0;
public function __construct($title,$firstName,$mainName,$price) {
$this->title = $title;
$this->producerFirstName = $firstName;
$this->producerMainName = $mainName;
$this->price = $price;
}
}
And you can simply do this magic.
$product1 = new ShopProduct("My Antonia","Willa","Cather",5.99 );
print "author: {$product1->getProducer()}\n";
This produces the following:
author: Willa Cather
In your case it will be something semilar to this, every time you create an object just pass the user ID to the user_id property, and save yourself a lot of coding.
Class Car {
private $user_id;
//.. your properties
public function __construct($title,$firstName,$mainName,$price){
$this->user_id = \Yii::$app->user->id;
//..Your magic
}
}
Good luck! And Happy Coding!
How to reset Jenkins security settings from the command line?
We can reset the password while leaving security on.
The config.xml file in /var/lib/Jenkins/users/admin/ acts sort of like the /etc/shadow file Linux or UNIX-like systems or the SAM file in Windows, in the sense that it stores the hash of the account's password.
If you need to reset the password without logging in, you can edit this file and replace the old hash with a new one generated from bcrypt:
$ pip install bcrypt
$ python
>>> import bcrypt
>>> bcrypt.hashpw("yourpassword", bcrypt.gensalt(rounds=10, prefix=b"2a"))
'YOUR_HASH'
This will output your hash, with prefix 2a, the correct prefix for Jenkins hashes.
Now, edit the config.xml file:
...
<passwordHash>#jbcrypt:REPLACE_THIS</passwordHash>
...
Once you insert the new hash, reset Jenkins:
(if you are on a system with systemd):
sudo systemctl restart Jenkins
You can now log in, and you didn't leave your system open for a second.
Custom exception type
You could implement your own exceptions and their handling for example like here:
// define exceptions "classes"
function NotNumberException() {}
function NotPositiveNumberException() {}
// try some code
try {
// some function/code that can throw
if (isNaN(value))
throw new NotNumberException();
else
if (value < 0)
throw new NotPositiveNumberException();
}
catch (e) {
if (e instanceof NotNumberException) {
alert("not a number");
}
else
if (e instanceof NotPositiveNumberException) {
alert("not a positive number");
}
}
There is another syntax for catching a typed exception, although this won't work in every browser (for example not in IE):
// define exceptions "classes"
function NotNumberException() {}
function NotPositiveNumberException() {}
// try some code
try {
// some function/code that can throw
if (isNaN(value))
throw new NotNumberException();
else
if (value < 0)
throw new NotPositiveNumberException();
}
catch (e if e instanceof NotNumberException) {
alert("not a number");
}
catch (e if e instanceof NotPositiveNumberException) {
alert("not a positive number");
}
List all environment variables from the command line
As mentioned in other answers, you can use set
to list all the environment variables or use
set [environment_variable]
to get a specific variable with its value.
set [environment_variable]=
can be used to remove a variable from the workspace.
How to implement a ViewPager with different Fragments / Layouts
Create new instances in your fragments and do like so in your Activity
private class SlidePagerAdapter extends FragmentStatePagerAdapter {
public SlidePagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
switch(position){
case 0:
return Fragment1.newInstance();
case 1:
return Fragment2.newInstance();
case 2:
return Fragment3.newInstance();
case 3:
return Fragment4.newInstance();
default: break;
}
return null;
}
What's NSLocalizedString equivalent in Swift?
When you are developing an SDK. You need some extra operation.
1) create Localizable.strings as usual in YourLocalizeDemoSDK.
2) create the same Localizable.strings in YourLocalizeDemo.
3) find your Bundle Path of YourLocalizeDemoSDK.
Swift4:
// if you use NSLocalizeString in NSObject, you can use it like this
let value = NSLocalizedString("key", tableName: nil, bundle: Bundle(for: type(of: self)), value: "", comment: "")
Bundle(for: type(of: self))
helps you to find the bundle in YourLocalizeDemoSDK. If you use Bundle.main
instead, you will get a wrong value(in fact it will be the same string with the key).
But if you want to use the String extension mentioned by dr OX. You need to do some more. The origin extension looks like this.
extension String {
var localized: String {
return NSLocalizedString(self, tableName: nil, bundle: Bundle.main, value: "", comment: "")
}
}
As we know, we are developing an SDK, Bundle.main
will get the bundle of YourLocalizeDemo's bundle. That's not what we want. We need the bundle in YourLocalizeDemoSDK. This is a trick to find it quickly.
Run the code below in a NSObject instance in YourLocalizeDemoSDK. And you will get the URL of YourLocalizeDemoSDK.
let bundleURLOfSDK = Bundle(for: type(of: self)).bundleURL
let mainBundleURL = Bundle.main.bundleURL
Print both of the two url, you will find that we can build bundleURLofSDK base on mainBundleURL. In this case, it will be:
let bundle = Bundle(url: Bundle.main.bundleURL.appendingPathComponent("Frameworks").appendingPathComponent("YourLocalizeDemoSDK.framework")) ?? Bundle.main
And the String extension will be:
extension String {
var localized: String {
let bundle = Bundle(url: Bundle.main.bundleURL.appendingPathComponent("Frameworks").appendingPathComponent("YourLocalizeDemoSDK.framework")) ?? Bundle.main
return NSLocalizedString(self, tableName: nil, bundle: bundle, value: "", comment: "")
}
}
Hope it helps.
Updating user data - ASP.NET Identity
I am using the new EF & Identity Core and I have the same issue, with the addition that I've got this error:
The instance of entity type cannot be tracked because another instance
of this type with the same key is already being tracked.
With the new DI model I added the constructor's Controller the context to the DB.
I tried to see what are the conflict with _conext.ChangeTracker.Entries()
and adding AsNoTracking()
to my calls without success.
I only need to change the state of my object (in this case Identity)
_context.Entry(user).State = EntityState.Modified;
var result = await _userManager.UpdateAsync(user);
And worked without create another store or object and mapping.
I hope someone else is useful my two cents.
Artisan migrate could not find driver
If you are matching with sqlite database:
In your php folder open php.ini file, go to:
;extension=pdo_sqlite
Just remove the semicolon and it will work.
How to step through Python code to help debug issues?
Let's take look at what breakpoint()
can do for you in 3.7+.
I have installed ipdb and pdbpp, which are both enhanced debuggers, via
pip install pdbpp
pip install ipdb
My test script, really doesn't do much, just calls breakpoint()
.
#test_188_breakpoint.py
myvars=dict(foo="bar")
print("before breakpoint()")
breakpoint() #
print(f"after breakpoint myvars={myvars}")
breakpoint() is linked to the PYTHONBREAKPOINT environment variable.
CASE 1: disabling breakpoint()
You can set the variable via bash
as usual
export PYTHONBREAKPOINT=0
This turns off breakpoint() where it does nothing (as long as you haven't modified sys.breakpointhook()
which is outside of the scope of this answer).
This is what a run of the program looks like:
(venv38) myuser@explore$ export PYTHONBREAKPOINT=0
(venv38) myuser@explore$ python test_188_breakpoint.py
before breakpoint()
after breakpoint myvars={'foo': 'bar'}
(venv38) myuser@explore$
Didn't stop, because I disabled breakpoint. Something that pdb.set_trace()
can't do !
CASE 2: using the default pdb behavior:
Now, let's unset PYTHONBREAKPOINT
which puts us back to normal, enabled-breakpoint behavior (it's only disabled when 0
not when empty).
(venv38) myuser@explore$ unset PYTHONBREAKPOINT
(venv38) myuser@explore$ python test_188_breakpoint.py
before breakpoint()
[0] > /Users/myuser/kds2/wk/explore/test_188_breakpoint.py(6)<module>()
-> print(f"after breakpoint myvars={myvars}")
(Pdb++) print("pdbpp replaces pdb because it was installed")
pdbpp replaces pdb because it was installed
(Pdb++) c
after breakpoint myvars={'foo': 'bar'}
It stopped, but I actually got pdbpp
because it replaces pdb
entirely while installed. If I unistalled pdbpp
, I'd be back to normal pdb
.
Note: a standard pdb.set_trace()
would still get me pdbpp
CASE 3: calling a custom debugger
But let's call ipdb
instead. This time, instead of setting the environment variable, we can use bash
to set it only for this one command.
(venv38) myuser@explore$ PYTHONBREAKPOINT=ipdb.set_trace py test_188_breakpoint.py
before breakpoint()
> /Users/myuser/kds2/wk/explore/test_188_breakpoint.py(6)<module>()
5 breakpoint()
----> 6 print(f"after breakpoint myvars={myvars}")
7
ipdb> print("and now I invoked ipdb instead")
and now I invoked ipdb instead
ipdb> c
after breakpoint myvars={'foo': 'bar'}
Essentially, what it does, when looking at $PYTHONBREAKPOINT:
from ipdb import set_trace # function imported on the right-most `.`
set_trace()
Again, much cleverer than a plain old pdb.set_trace()
in practice? I'd probably settle on a debugger.
Say I want ipdb always, I would:
export
it via .profile
or similar.
- disable on a command by command basis, without modifying the normal value
Example (pytest
and debuggers often make for unhappy couples):
(venv38) myuser@explore$ export PYTHONBREAKPOINT=ipdb.set_trace
(venv38) myuser@explore$ echo $PYTHONBREAKPOINT
ipdb.set_trace
(venv38) myuser@explore$ PYTHONBREAKPOINT=0 pytest test_188_breakpoint.py
=================================== test session starts ====================================
platform darwin -- Python 3.8.6, pytest-5.1.2, py-1.9.0, pluggy-0.13.1
rootdir: /Users/myuser/kds2/wk/explore
plugins: celery-4.4.7, cov-2.10.0
collected 0 items
================================== no tests ran in 0.03s ===================================
(venv38) myuser@explore$ echo $PYTHONBREAKPOINT
ipdb.set_trace
p.s.
I'm using bash
under macos
, any posix shell will behave substantially the same. Windows, either powershell or DOS, may have different capabilities, especially around PYTHONBREAKPOINT=<some value> <some command>
to set a environment variable only for one command.
http://localhost/phpMyAdmin/ unable to connect
You dont start phpmyadmin from your webbrowser.
When you want to start PHPMyAdmin you have to do so from the XAMPP control-panel.
When you've started phpmyadmin from your control-panel you can access it from the web-browser.
Foreach value from POST from form
First, please do not use extract(), it can be a security problem because it is easy to manipulate POST parameters
In addition, you don't have to use variable variable names (that sounds odd), instead:
foreach($_POST as $key => $value) {
echo "POST parameter '$key' has '$value'";
}
To ensure that you have only parameters beginning with 'item_name' you can check it like so:
$param_name = 'item_name';
if(substr($key, 0, strlen($param_name)) == $param_name) {
// do something
}
How can I drop a table if there is a foreign key constraint in SQL Server?
You have to drop the constraint before drop your table.
You can use those queries to find all FKs in your table and find the FKs in the tables in which your table is used.
Declare @SchemaName VarChar(200) = 'Your Schema name'
Declare @TableName VarChar(200) = 'Your Table Name'
-- Find FK in This table.
SELECT
' IF EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id =
OBJECT_ID(N''' +
'[' + OBJECT_SCHEMA_NAME(FK.parent_object_id) + '].[' + FK.name + ']'
+ ''') AND parent_object_id = OBJECT_ID(N''' +
'[' + OBJECT_SCHEMA_NAME(FK.parent_object_id) + '].[' +
OBJECT_NAME(FK.parent_object_id) + ']' + ''')) ' +
'ALTER TABLE ' + OBJECT_SCHEMA_NAME(FK.parent_object_id) +
'.[' + OBJECT_NAME(FK.parent_object_id) +
'] DROP CONSTRAINT ' + FK.name
, S.name , O.name, OBJECT_NAME(FK.parent_object_id)
FROM sys.foreign_keys AS FK
INNER JOIN Sys.objects As O
ON (O.object_id = FK.parent_object_id )
INNER JOIN SYS.schemas AS S
ON (O.schema_id = S.schema_id)
WHERE
O.name = @TableName
And S.name = @SchemaName
-- Find the FKs in the tables in which this table is used
SELECT
' IF EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id =
OBJECT_ID(N''' +
'[' + OBJECT_SCHEMA_NAME(FK.parent_object_id) + '].[' + FK.name + ']'
+ ''') AND parent_object_id = OBJECT_ID(N''' +
'[' + OBJECT_SCHEMA_NAME(FK.parent_object_id) + '].[' +
OBJECT_NAME(FK.parent_object_id) + ']' + ''')) ' +
' ALTER TABLE ' + OBJECT_SCHEMA_NAME(FK.parent_object_id) +
'.[' + OBJECT_NAME(FK.parent_object_id) +
'] DROP CONSTRAINT ' + FK.name
, S.name , O.name, OBJECT_NAME(FK.parent_object_id)
FROM sys.foreign_keys AS FK
INNER JOIN Sys.objects As O
ON (O.object_id = FK.referenced_object_id )
INNER JOIN SYS.schemas AS S
ON (O.schema_id = S.schema_id)
WHERE
O.name = @TableName
And S.name = @SchemaName
Kotlin unresolved reference in IntelliJ
For me, it was due to the project missing Gradle Libraries in its project structure.
Just add in build.gradle:
apply plugin: 'idea'
And then run:
$ gradle idea
After that gradle rebuilds dependencies libraries and the references are recognized!
Recommended SQL database design for tags or tagging
I've always kept the tags in a separate table and then had a mapping table. Of course I've never done anything on a really large scale either.
Having a "tags" table and a map table makes it pretty trivial to generate tag clouds & such since you can easily put together SQL to get a list of tags with counts of how often each tag is used.
Change GridView row color based on condition
protected void DrugGridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
// To check condition on integer value
if (Convert.ToInt16(DataBinder.Eval(e.Row.DataItem, "Dosage")) == 50)
{
e.Row.BackColor = System.Drawing.Color.Cyan;
}
}
How to push both value and key into PHP array
You can use the union operator (+
) to combine arrays and keep the keys of the added array. For example:
<?php
$arr1 = array('foo' => 'bar');
$arr2 = array('baz' => 'bof');
$arr3 = $arr1 + $arr2;
print_r($arr3);
// prints:
// array(
// 'foo' => 'bar',
// 'baz' => 'bof',
// );
So you could do $_GET += array('one' => 1);
.
There's more info on the usage of the union operator vs array_merge
in the documentation at http://php.net/manual/en/function.array-merge.php.
Is this a good way to clone an object in ES6?
Following on from the answer by @marcel I found some functions were still missing on the cloned object. e.g.
function MyObject() {
var methodAValue = null,
methodBValue = null
Object.defineProperty(this, "methodA", {
get: function() { return methodAValue; },
set: function(value) {
methodAValue = value || {};
},
enumerable: true
});
Object.defineProperty(this, "methodB", {
get: function() { return methodAValue; },
set: function(value) {
methodAValue = value || {};
}
});
}
where on MyObject I could clone methodA but methodB was excluded. This occurred because it is missing
enumerable: true
which meant it did not show up in
for(let key in item)
Instead I switched over to
Object.getOwnPropertyNames(item).forEach((key) => {
....
});
which will include non-enumerable keys.
I also found that the prototype (proto) was not cloned. For that I ended up using
if (obj.__proto__) {
copy.__proto__ = Object.assign(Object.create(Object.getPrototypeOf(obj)), obj);
}
PS: Frustrating that I could not find a built in function to do this.
Reference - What does this regex mean?
The Stack Overflow Regular Expressions FAQ
See also a lot of general hints and useful links at the regex tag details page.
Online tutorials
Quantifiers
- Zero-or-more:
*
:greedy, *?
:reluctant, *+
:possessive
- One-or-more:
+
:greedy, +?
:reluctant, ++
:possessive
?
:optional (zero-or-one)
- Min/max ranges (all inclusive):
{n,m}
:between n & m, {n,}
:n-or-more, {n}
:exactly n
- Differences between greedy, reluctant (a.k.a. "lazy", "ungreedy") and possessive quantifier:
Character Classes
Escape Sequences
Anchors
^
:start of line/input, \b
:word boundary, and \B
:non-word boundary, $
:end of line/input
\A
:start of input, \Z
:end of input php, perl, ruby
\z
:the very end of input (\Z
in Python) .net, php, pcre, java, ruby, icu, swift, objective-c
\G
:start of match php, perl, ruby
(Also see "Flavor-Specific Information ? Java ? The functions in Matcher
")
Groups
Lookarounds
Modifiers
Other:
Common Tasks
Advanced Regex-Fu
- Strings and numbers:
- Other:
Flavor-Specific Information
(Except for those marked with *
, this section contains non-Stack Overflow links.)
- Java
- .NET
- Official documentation:
- Boost regex engine: General syntax, Perl syntax (used by TextPad, Sublime Text, UltraEdit, ...???)
- JavaScript 1.5 general info and RegExp object
- .NET MySQL Oracle Perl5 version 18.2
- PHP: pattern syntax,
preg_match
- Python: Regular expression operations,
search
vs match
, how-to
- Rust: crate
regex
, struct regex::Regex
- Splunk: regex terminology and syntax and regex command
- Tcl: regex syntax, manpage,
regexp
command
- Visual Studio Find and Replace
General information
(Links marked with *
are non-Stack Overflow links.)
Examples of regex that can cause regex engine to fail
Tools: Testers and Explainers
(This section contains non-Stack Overflow links.)
How to compile a 32-bit binary on a 64-bit linux machine with gcc/cmake
For any complex application, I suggest to use an lxc container. lxc containers are 'something in the middle between a chroot on steroids and a full fledged virtual machine'.
For example, here's a way to build 32-bit wine using lxc on an Ubuntu Trusty system:
sudo apt-get install lxc lxc-templates
sudo lxc-create -t ubuntu -n my32bitbox -- --bindhome $LOGNAME -a i386 --release trusty
sudo lxc-start -n my32bitbox
# login as yourself
sudo sh -c "sed s/deb/deb-src/ /etc/apt/sources.list >> /etc/apt/sources.list"
sudo apt-get install devscripts
sudo apt-get build-dep wine1.7
apt-get source wine1.7
cd wine1.7-*
debuild -eDEB_BUILD_OPTIONS="parallel=8" -i -us -uc -b
shutdown -h now # to exit the container
Here is the wiki page about how to build 32-bit wine on a 64-bit host using lxc.
Counting number of characters in a file through shell script
#!/bin/sh
wc -m $1 | awk '{print $1}'
wc -m
counts the number of characters; the awk
command prints the number of characters only, omitting the filename.
wc -c
would give you the number of bytes (which can be different to the number of characters, as depending on the encoding you may have a character encoded on several bytes).
UNIX nonblocking I/O: O_NONBLOCK vs. FIONBIO
Prior to standardization there was ioctl(
...FIONBIO
...)
and fcntl(
...O_NDELAY
...)
, but these behaved inconsistently between systems, and even within the same system. For example, it was common for FIONBIO
to work on sockets and O_NDELAY
to work on ttys, with a lot of inconsistency for things like pipes, fifos, and devices. And if you didn't know what kind of file descriptor you had, you'd have to set both to be sure. But in addition, a non-blocking read with no data available was also indicated inconsistently; depending on the OS and the type of file descriptor the read may return 0, or -1 with errno EAGAIN, or -1 with errno EWOULDBLOCK. Even today, setting FIONBIO
or O_NDELAY
on Solaris causes a read with no data to return 0 on a tty or pipe, or -1 with errno EAGAIN on a socket. However 0 is ambiguous since it is also returned for EOF.
POSIX addressed this with the introduction of O_NONBLOCK
, which has standardized behavior across different systems and file descriptor types. Because existing systems usually want to avoid any changes to behavior which might break backward compatibility, POSIX defined a new flag rather than mandating specific behavior for one of the others. Some systems like Linux treat all 3 the same, and also define EAGAIN and EWOULDBLOCK to the same value, but systems wishing to maintain some other legacy behavior for backward compatibility can do so when the older mechanisms are used.
New programs should use fcntl(
...O_NONBLOCK
...)
, as standardized by POSIX.
Why am I getting a NoClassDefFoundError in Java?
This error can be caused by unchecked Java version requirements.
In my case I was able to resolve this error, while building a high-profile open-source project, by switching from Java 9 to Java 8 using SDKMAN!.
sdk list java
sdk install java 8u152-zulu
sdk use java 8u152-zulu
Then doing a clean install as described below.
When using Maven as your build tool, it is sometimes helpful -- and usually gratifying, to do a clean 'install' build with testing disabled.
mvn clean install -DskipTests
Now that everything has been built and installed, you can go ahead and run the tests.
mvn test
Best way to unselect a <select> in jQuery?
A quick google found this post that describes how to do what you want for both single and multiple select lists in IE. The solution seems pretty elegant as well:
$('#clickme').click(function() {
$('#selectmenu option').attr('selected', false);
});