In my case I had inherited from the IdentityDbContext correctly (with my own custom types and key defined) but had inadvertantly removed the call to the base class's OnModelCreating:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder); // I had removed this
/// Rest of on model creating here.
}
Which then fixed up my missing indexes from the identity classes and I could then generate migrations and enable migrations appropriately.
File-New-File.Make a Swift class named AppExtension.Add the following.
extension UIViewController{
func validateEmailAndGetBoolValue(candidate: String) -> Bool {
let emailRegex = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,6}"
return NSPredicate(format: "SELF MATCHES %@", emailRegex).evaluateWithObject(candidate)
}
}
Use:
var emailValidator:Bool?
self.emailValidator = self.validateEmailAndGetBoolValue(resetEmail!)
print("emailValidator : "+String(self.emailValidator?.boolValue))
Use a loop to alternate desired results.
OR
extension String
{
//Validate Email
var isEmail: Bool {
do {
let regex = try NSRegularExpression(pattern: "^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$", options: .CaseInsensitive)
return regex.firstMatchInString(self, options: NSMatchingOptions(rawValue: 0), range: NSMakeRange(0, self.characters.count)) != nil
} catch {
return false
}
}
}
Use:
if(resetEmail!.isEmail)
{
AppController().requestResetPassword(resetEmail!)
self.view.makeToast(message: "Sending OTP")
}
else
{
self.view.makeToast(message: "Please enter a valid email")
}
I found solution. It works fine when I throw away next line from form:
enctype="multipart/form-data"
And now it pass all parameters at request ok:
<form action="/registration" method="post">
<%-- error messages --%>
<div class="form-group">
<c:forEach items="${registrationErrors}" var="error">
<p class="error">${error}</p>
</c:forEach>
</div>
Or add "sort name" to list alphabetically
Get-ADPrincipalGroupMembership username | select name | sort name
For Azure Functions we use this simple extension to Microsoft.Extensions.Logging.ILogger
public static class LoggerExtensions
{
public static void Error(this ILogger logger, string message, Exception exception)
{
if (exception is DbEntityValidationException dbException)
{
message += "\nValidation Errors: ";
foreach (var error in dbException.EntityValidationErrors.SelectMany(entity => entity.ValidationErrors))
{
message += $"\n * Field name: {error.PropertyName}, Error message: {error.ErrorMessage}";
}
}
logger.LogError(default(EventId), exception, message);
}
}
and example usage:
try
{
do something with request and EF
}
catch (Exception e)
{
log.Error($"Failed to create customer due to an exception: {e.Message}", e);
return await StringResponseUtil.CreateResponse(HttpStatusCode.InternalServerError, e.Message);
}
I solve this problem with this code in NugetPackageConsole.and it works.The problem was in the version. i thikn it will help others.
I faced this error before
when I tried to update specific field in my model in entity framwork
Letter letter = new Letter {ID = letterId, ExportNumber = letterExportNumber,EntityState = EntityState.Modified};
LetterService.ChangeExportNumberfor(letter);
//----------
public int ChangeExportNumber(Letter letter)
{
int result = 0;
using (var db = ((LettersGeneratorEntities) GetContext()))
{
db.Letters.Attach(letter);
db.Entry(letter).Property(x => x.ExportNumber).IsModified = true;
result += db.SaveChanges();
}
return result;
}
and according the above answers
I found the Validation message The SignerName field is required.
which pointing to field in my model
and when I checked my database schema I found
so off coure ValidationException
has its right to raise
and according to this field I want it to be nullable, (I dont know how I messed it)
so I changed that field to allow Null, and by this my code will not give me this error again
so This error maybe will happened if you invalidate Your Data integrity of your database
This error also happens when you try to save an entity that has validation errors. A good way to cause this is to forget to check ModelState.IsValid before saving to your DB.
Use empty
(it checks both nullness and emptiness) and group the nested ternary expression by parentheses (EL is in certain implementations/versions namely somewhat problematic with nested ternary expressions). Thus, so:
styleClass="#{empty obj.validationErrorMap ? ' ' :
(obj.validationErrorMap.contains('key') ? 'highlight_field' : 'highlight_row')}"
If still in vain (I would then check JBoss EL configs), use the "normal" EL approach:
styleClass="#{empty obj.validationErrorMap ? ' ' :
(obj.validationErrorMap['key'] ne null ? 'highlight_field' : 'highlight_row')}"
Update: as per the comments, the Map
turns out to actually be a List
(please work on your naming conventions). To check if a List
contains an item the "normal" EL way, use JSTL fn:contains
(although not explicitly documented, it works for List
as well).
styleClass="#{empty obj.validationErrorMap ? ' ' :
(fn:contains(obj.validationErrorMap, 'key') ? 'highlight_field' : 'highlight_row')}"
Since you're using JPA, use the Lob
annotation (and optionally the Column
annotation). Here is what the JPA specification says about it:
9.1.19 Lob Annotation
A
Lob
annotation specifies that a persistent property or field should be persisted as a large object to a database-supported large object type. Portable applications should use theLob
annotation when mapping to a database Lob type. The Lob annotation may be used in conjunction with theBasic
annotation. A Lob may be either a binary or character type. The Lob type is inferred from the type of the persistent field or property, and except for string and character-based types defaults to Blob.
So declare something like this:
@Lob
@Column(name="CONTENT", length=512)
private String content;
Set the items into display: inline
and use :after
:
.text span { display: inline }
.break-after:after { content: '\A'; white-space:pre; }
and add the class into your html spans:
<span class="medium break-after">We</span>
Your makefile should ideally be named makefile
, not make
. Note that you can call your makefile anything you like, but as you found, you then need the -f
option with make
to specify the name of the makefile. Using the default name of makefile
just makes life easier.
There is a difference between initialization and assignment. What you want to do is not initialization, but assignment. But such assignment to array is not possible in C++.
Here is what you can do:
#include <algorithm>
int array [] = {1,3,34,5,6};
int newarr [] = {34,2,4,5,6};
std::copy(newarr, newarr + 5, array);
However, in C++0x, you can do this:
std::vector<int> array = {1,3,34,5,6};
array = {34,2,4,5,6};
Of course, if you choose to use std::vector
instead of raw array.
Lines 1,2,3,4 will call the default constructor. They are different in the essence as 1,2 are dynamically created object and 3,4 are statically created objects.
In Line 7, you create an object inside the argument call. So its an error.
And Lines 5 and 6 are invitation for memory leak.
as simple as that: echo '<a href="'.$link_address.'">Link</a>';
The ConnectTimeout option allows you to tell your ssh client how long you're willing to wait for a connection before returning an error. By setting ConnectTimeout to 1, you're effectively saying "try for at most 1 second and then fail if you haven't connected yet".
The problem is that when you connect by name, the DNS lookup can take several seconds. Connecting by IP address is much faster, and may actually work in one second or less. What sinelaw is experiencing is that every attempt to connect by DNS name is failing to occur within one second. The default setting of ConnectTimeout defers to the linux kernel connect timeout, which is usually pretty long.
I have created my own iterator to iterate over Outlook objects via python. The issue is that python tries to iterates starting with Index[0], but outlook expects for first item Index[1]... To make it more Ruby simple, there is below a helper class Oli with following methods:
.items() - yields a tuple(index, Item)...
.prop() - helping to introspect outlook object exposing available properties (methods and attributes)
from win32com.client import constants
from win32com.client.gencache import EnsureDispatch as Dispatch
outlook = Dispatch("Outlook.Application")
mapi = outlook.GetNamespace("MAPI")
class Oli():
def __init__(self, outlook_object):
self._obj = outlook_object
def items(self):
array_size = self._obj.Count
for item_index in xrange(1,array_size+1):
yield (item_index, self._obj[item_index])
def prop(self):
return sorted( self._obj._prop_map_get_.keys() )
for inx, folder in Oli(mapi.Folders).items():
# iterate all Outlook folders (top level)
print "-"*70
print folder.Name
for inx,subfolder in Oli(folder.Folders).items():
print "(%i)" % inx, subfolder.Name,"=> ", subfolder
all of these steered me to the correct result, but I wound up doing
DateTime.now.mjd - DateTime.parse("01-01-1995").mjd
If you have a list of words you can do a method like this:
public bool ContainWords(List<string> wordList, string text)
{
foreach(string currentWord in wordList)
if(!text.Contains(currentWord))
return false;
return true;
}
I needed to calculate a lot of distances between the points for my project, so I went ahead and tried to optimize the code, I have found here. On average in different browsers my new implementation runs 2 times faster than the most upvoted answer.
function distance(lat1, lon1, lat2, lon2) {
var p = 0.017453292519943295; // Math.PI / 180
var c = Math.cos;
var a = 0.5 - c((lat2 - lat1) * p)/2 +
c(lat1 * p) * c(lat2 * p) *
(1 - c((lon2 - lon1) * p))/2;
return 12742 * Math.asin(Math.sqrt(a)); // 2 * R; R = 6371 km
}
You can play with my jsPerf and see the results here.
Recently I needed to do the same in python, so here is a python implementation:
from math import cos, asin, sqrt, pi
def distance(lat1, lon1, lat2, lon2):
p = pi/180
a = 0.5 - cos((lat2-lat1)*p)/2 + cos(lat1*p) * cos(lat2*p) * (1-cos((lon2-lon1)*p))/2
return 12742 * asin(sqrt(a)) #2*R*asin...
And for the sake of completeness: Haversine on wiki.
An instance might be corrupted or not updated properly.
Try these Commands:
C:\>sqllocaldb stop MSSQLLocalDB
LocalDB instance "MSSQLLocalDB" stopped.
C:\>sqllocaldb delete MSSQLLocalDB
LocalDB instance "MSSQLLocalDB" deleted.
C:\>sqllocaldb create MSSQLLocalDB
LocalDB instance "MSSQLLocalDB" created with version 13.0.1601.5.
C:\>sqllocaldb start MSSQLLocalDB
LocalDB instance "MSSQLLocalDB" started.
It formats the string as two uppercase hexadecimal characters.
In more depth, the argument "X2"
is a "format string" that tells the ToString()
method how it should format the string. In this case, "X2" indicates the string should be formatted in Hexadecimal.
byte.ToString()
without any arguments returns the number in its natural decimal representation, with no padding.
Microsoft documents the standard numeric format strings which generally work with all primitive numeric types' ToString()
methods. This same pattern is used for other types as well: for example, standard date/time format strings can be used with DateTime.ToString()
.
I did a time test here, using each method 100000 times in a loop. The results surprised me. (The results still surprise me after editing them in response to valid criticism in the comments.)
Here's the script:
import timeit
bad_chars = '(){}<>'
setup = """import re
import string
s = 'Barack (of Washington)'
bad_chars = '(){}<>'
rgx = re.compile('[%s]' % bad_chars)"""
timer = timeit.Timer('o = "".join(c for c in s if c not in bad_chars)', setup=setup)
print "List comprehension: ", timer.timeit(100000)
timer = timeit.Timer("o= rgx.sub('', s)", setup=setup)
print "Regular expression: ", timer.timeit(100000)
timer = timeit.Timer('for c in bad_chars: s = s.replace(c, "")', setup=setup)
print "Replace in loop: ", timer.timeit(100000)
timer = timeit.Timer('s.translate(string.maketrans("", "", ), bad_chars)', setup=setup)
print "string.translate: ", timer.timeit(100000)
Here are the results:
List comprehension: 0.631745100021
Regular expression: 0.155561923981
Replace in loop: 0.235936164856
string.translate: 0.0965719223022
Results on other runs follow a similar pattern. If speed is not the primary concern, however, I still think string.translate
is not the most readable; the other three are more obvious, though slower to varying degrees.
%u is used for unsigned integer. Since the memory address given by the signed integer address operator %d is -12, to get this value in unsigned integer, Compiler returns the unsigned integer value for this address.
The following code assumes that your table has the ID 'MyTable'
<script language="JavaScript"> <!-- var oRows = document.getElementById('MyTable').getElementsByTagName('tr'); var iRowCount = oRows.length; alert('Your table has ' + iRowCount + ' rows.'); //--> </script>
Answer taken from : http://www.delphifaq.com/faq/f771.shtml, which is the first result on google for the query : "Get the number of rows in a HTML table" ;)
string apppath =
(new System.IO.FileInfo
(System.Reflection.Assembly.GetExecutingAssembly().CodeBase)).DirectoryName;
Yes, you're right. With the css()
method you can retrieve the desired css value stored in the DOM. You can read more about this at: http://api.jquery.com/css/
But if you want to get its position you can check offset() and position() methods to get it's position.
If you want to look in all tables in all Databases server-wide and get output you can make use of the undocumented sp_MSforeachdb procedure:
sp_MSforeachdb 'SELECT "?" AS DB, * FROM [?].sys.tables WHERE name like ''%Table_Names%'''
Yes, you should think of defining both your functions in a Class, and making word a member. This is cleaner :
class Spam:
def oneFunction(self,lists):
category=random.choice(list(lists.keys()))
self.word=random.choice(lists[category])
def anotherFunction(self):
for letter in self.word:
print("_", end=" ")
Once you make a Class you have to Instantiate it to an Object and access the member functions
s = Spam()
s.oneFunction(lists)
s.anotherFunction()
Another approach would be to make oneFunction
return the word so that you can use oneFunction
instead of word
in anotherFunction
>>> def oneFunction(lists):
category=random.choice(list(lists.keys()))
return random.choice(lists[category])
>>> def anotherFunction():
for letter in oneFunction(lists):
print("_", end=" ")
And finally, you can also make anotherFunction
, accept word
as a parameter which you can pass from the result of calling oneFunction
>>> def anotherFunction(words):
for letter in words:
print("_",end=" ")
>>> anotherFunction(oneFunction(lists))
I was trying to put a transparent HTML overlay over my GL view but it has always black flickering which covers my GL view. After several days trying to get rid of this flickering I found this workaround which is acceptable for me (but a shame for android).
The problem is that I need hardware acceleration for my nice CSS animations and so webView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
is not an option for me.
The trick was to put a second (empty) WebView
between my GL view and the HTML overlay. This dummyWebView
I told to render in SW mode, and now my HTML overlays renders smooth in HW and no more black flickering.
I don't know if this works on other devices than My Acer Iconia A700, but I hope I could help someone with this.
public class MyActivity extends Activity {
@Override
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
RelativeLayout layout = new RelativeLayout(getApplication());
setContentView(layout);
MyGlView glView = new MyGlView(this);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
dummyWebView = new WebView(this);
dummyWebView.setLayoutParams(params);
dummyWebView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
dummyWebView.loadData("", "text/plain", "utf8");
dummyWebView.setBackgroundColor(0x00000000);
webView = new WebView(this);
webView.setLayoutParams(params);
webView.loadUrl("http://10.0.21.254:5984/ui/index.html");
webView.setBackgroundColor(0x00000000);
layout.addView(glView);
layout.addView(dummyWebView);
layout.addView(webView);
}
}
So if the insert time is what you need, it's already there:
Login to mongodb shell
ubuntu@ip-10-0-1-223:~$ mongo 10.0.1.223
MongoDB shell version: 2.4.9
connecting to: 10.0.1.223/test
Create your database by inserting items
> db.penguins.insert({"penguin": "skipper"})
> db.penguins.insert({"penguin": "kowalski"})
>
Lets make that database the one we are on now
> use penguins
switched to db penguins
Get the rows back:
> db.penguins.find()
{ "_id" : ObjectId("5498da1bf83a61f58ef6c6d5"), "penguin" : "skipper" }
{ "_id" : ObjectId("5498da28f83a61f58ef6c6d6"), "penguin" : "kowalski" }
Get each row in yyyy-MM-dd HH:mm:ss format:
> db.penguins.find().forEach(function (doc){ d = doc._id.getTimestamp(); print(d.getFullYear()+"-"+(d.getMonth()+1)+"-"+d.getDate() + " " + d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds()) })
2014-12-23 3:4:41
2014-12-23 3:4:53
If that last one-liner confuses you I have a walkthrough on how that works here: https://stackoverflow.com/a/27613766/445131
2015 update with dplyr:
df %>% group_by(dive) %>% summarise(percentage = mean(speed))
Source: local data frame [2 x 2]
dive percentage
1 dive1 0.4777462
2 dive2 0.6726483
You can try using this way :
sentence ["Robert"] = "Roger"
Then the sentence will become :
sentence = "My name is Roger" # Robert is replaced with Roger
I spent way too much time on this and the solution was super simple. I had to use my "MX" as the host and port 25.
var sClient = new SmtpClient("domain-com.mail.protection.outlook.com");
var message = new MailMessage();
sClient.Port = 25;
sClient.EnableSsl = true;
sClient.Credentials = new NetworkCredential("user", "password");
sClient.UseDefaultCredentials = false;
message.Body = "Test";
message.From = new MailAddress("[email protected]");
message.Subject = "Test";
message.CC.Add(new MailAddress("[email protected]"));
sClient.Send(message);
To post a nested object with the key-value interface you can use a similar method to sending arrays. Pass an object key in square brackets after the object index.
"Items": [
{
"sku": "9257",
"Price": "100"
}
]
Under Windows 7, open the Event Viewer. You can do this the way Gishu suggested for XP, typing eventvwr
from the command line, or by opening the Control Panel, selecting System and Security, then Administrative Tools and finally Event Viewer. It may require UAC approval or an admin password.
In the left pane, expand Windows Logs and then System. You can filter the logs with Filter Current Log... from the Actions pane on the right and selecting "Service Control Manager." Or, depending on why you want this information, you might just need to look through the Error entries.
The actual log entry pane (not shown) is pretty user-friendly and self-explanatory. You'll be looking for messages like the following:
"The Praxco Assistant service entered the stopped state."
"The Windows Image Acquisition (WIA) service entered the running state."
"The MySQL service terminated unexpectedly. It has done this 3 time(s)."
Here's my solution when working with hex integers and not hex strings:
def convert_hex_to_ascii(h):
chars_in_reverse = []
while h != 0x0:
chars_in_reverse.append(chr(h & 0xFF))
h = h >> 8
chars_in_reverse.reverse()
return ''.join(chars_in_reverse)
print convert_hex_to_ascii(0x7061756c)
JonH has covered very well the part on how to write the query. There is another significant issue that must be mentioned too, however, which is the performance characteristics of such a query. Let's repeat it here (adapted to Oracle):
SELECT EmployeeName FROM EmployeeTable WHERE LENGTH(EmployeeName) > 4;
This query is restricting the result of a function applied to a column value (the result of applying the LENGTH
function to the EmployeeName
column). In Oracle, and probably in all other RDBMSs, this means that a regular index on EmployeeName will be useless to answer this query; the database will do a full table scan, which can be really costly.
However, various databases offer a function indexes feature that is designed to speed up queries like this. For example, in Oracle, you can create an index like this:
CREATE INDEX EmployeeTable_EmployeeName_Length ON EmployeeTable(LENGTH(EmployeeName));
This might still not help in your case, however, because the index might not be very selective for your condition. By this I mean the following: you're asking for rows where the name's length is more than 4. Let's assume that 80% of the employee names in that table are longer than 4. Well, then the database is likely going to conclude (correctly) that it's not worth using the index, because it's probably going to have to read most of the blocks in the table anyway.
However, if you changed the query to say LENGTH(EmployeeName) <= 4
, or LENGTH(EmployeeName) > 35
, assuming that very few employees have names with fewer than 5 character or more than 35, then the index would get picked and improve performance.
Anyway, in short: beware of the performance characteristics of queries like the one you're trying to write.
Perhaps a simpler one-liner, with identical or different column names. Worked even when df2['Name2'] contained duplicate values.
newDf = df1.set_index('Name1')
.drop(df2['Name2'], errors='ignore')
.reset_index(drop=False)
For me, the problem was that when I copied the solution to a new folder and opened it, it was missing the Nuget folder as shown below. I copied this folder over and everything worked. Note: This same folder was in our source control but not in this solutions project, it was up one directory.
Just put the following code on the top of the page
@{
Layout = "";
}
Here is another solution using Guava in Java 8 that returns the matched element if one exists in the list. If more than one elements are matched then the collector throws an IllegalArgumentException. A null is returned if there is no match.
Carnet carnet = listCarnet.stream()
.filter(c -> c.getCodeIsin().equals(wantedCodeIsin))
.collect(MoreCollectors.toOptional())
.orElse(null);
If you are installing first time then please try login with username and password as root
You could use the SQL%ROWCOUNT
Oracle variable:
UPDATE table1
SET field2 = value2,
field3 = value3
WHERE field1 = value1;
IF (SQL%ROWCOUNT = 0) THEN
INSERT INTO table (field1, field2, field3)
VALUES (value1, value2, value3);
END IF;
It would be easier just to determine if your primary key (i.e. field1
) has a value and then perform an insert or update accordingly. That is, if you use said values as parameters for a stored procedure.
If you don't feel like importing anything, you can try:
raise SystemExit, 0
You can easily wrap your button tag with tag.Using Url.Action() HTML Helper this will get to navigate to one page to another.
<a href='@Url.Action("YourAction", "YourController")'>
<input type='button' value='Dummy Button' />
</a>
If you want to navigate with javascript onclick() function then use
<input type='button' value='Dummy Button' onclick='window.location = "@Url.Action("YourAction", "YourController")";' />
its a block element, and you need to use none
document.getElementById("test").style.display="none"
hidden
is used for visibility
If you installed php with homebrew, then check if your apache2.conf file is using homebrew version of php5.so file.
If you have two columns with the same name. One simple way is to manually rename the columns like this:-
df.columns = ['column1', 'column2', 'column3']
Then you can drop via column index as you requested, like this:-
df.drop(df.columns[1], axis=1, inplace=True)
df.column[1]
will drop index 1.
Remember axis 1 = columns and axis 0 = rows.
Click "View Detail..." a window will open where you can expand the "Inner Exception" my guess is that when you try to delete the record there is a reference constraint violation. The inner exception will give you more information on that so you can modify your code to remove any references prior to deleting the record.
Here is a solution for a custom WordPress table. This will work for ENUM values without a comma (,)
in them
function get_enum_values($wpdb, $table, $field) {
$values = array();
$table = "{$wpdb->prefix}{$table}";
$query = "SHOW COLUMNS FROM {$table} WHERE Field = '{$field}'";
$results = $wpdb->get_results($query, ARRAY_A);
if (is_array($results) && count($results) > 0) {
preg_match("/^enum\(\'(.*)\'\)$/", $results[0]['Type'], $matches);
if (is_array($matches) && isset($matches[1])) {
$values = explode("','", $matches[1]);
}
}
return $values;
}
Use this:
li { color:blue; }
li:nth-child(odd) { color:green; }
li:nth-child(even) { color:red; }
See here for info on browser support: http://kimblim.dk/css-tests/selectors/
JavaScript validation is not secure as anybody can change what your script does in the browser. Using it for enhancing the visual experience is ok though.
var textBox = document.getElementById("myTextBox");
var textLength = textBox.value.length;
if(textLength > 5)
{
//red
textBox.style.backgroundColor = "#FF0000";
}
else
{
//green
textBox.style.backgroundColor = "#00FF00";
}
import { FormsModule } from '@angular/forms';
//<<<< import it here
BrowserModule, FormsModule
//<<<< and here
So simply looks for app.module.ts
or another module file and make sure you have FormsModule
imported in...
>>> sorted(['Some', 'words', 'sort', 'differently'], key=lambda word: word.lower())
Actually, above codes can be:
>>> sorted(['Some','words','sort','differently'],key=str.lower)
According to https://docs.python.org/2/library/functions.html?highlight=sorted#sorted, key specifies a function of one argument that is used to extract a comparison key from each list element: key=str.lower. The default value is None (compare the elements directly).
public function outletAmenities()
{
return $this->hasMany(OutletAmenities::class,'outlet_id','id')
->join('amenity_master','amenity_icon_url','=','image_url')
->where('amenity_master.status',1)
->where('outlet_amenities.status',1);
}
Try this
import ("strconv")
value := "123"
number,err := strconv.ParseUint(value, 10, 32)
finalIntNum := int(number) //Convert uint64 To int
You can write Bean Editors (details are in the Spring Docs) if you want to add further value and write to custom types.
Java 8 introduced a nice computeIfAbsent default method to Map
interface which stores lazy-computed value and so doesn't break map contract:
Map<Key, Graph> map = new HashMap<>();
map.computeIfAbsent(aKey, key -> createExpensiveGraph(key));
Origin: http://blog.javabien.net/2014/02/20/loadingcache-in-java-8-without-guava/
Disclamer: This answer doesn't match exactly what OP asked but may be handy in some cases matching question's title when keys number is limited and caching of different values would be profitable. It shouldn't be used in opposite case with plenty of keys and same default value as this would needlessly waste memory.
The problem here seems to be that you're reassigning $today
by assigning a string to it:
$today = $dd+'/'+$mm+'/'+$yyyy;
Strings don't have getDate
.
Also, $today.getDate()-1
just gives you the day of the month minus one; it doesn't give you the full date of 'yesterday'. Try this:
$today = new Date();
$yesterday = new Date($today);
$yesterday.setDate($today.getDate() - 1); //setDate also supports negative values, which cause the month to rollover.
Then just apply the formatting code you wrote:
var $dd = $yesterday.getDate();
var $mm = $yesterday.getMonth()+1; //January is 0!
var $yyyy = $yesterday.getFullYear();
if($dd<10){$dd='0'+$dd} if($mm<10){$mm='0'+$mm} $yesterday = $dd+'/'+$mm+'/'+$yyyy;
Because of the last statement, $yesterday
is now a String
(not a Date
) containing the formatted date.
as explained here
With help from numpy one can calculate for example a linear fitting.
# plot the data itself
pylab.plot(x,y,'o')
# calc the trendline
z = numpy.polyfit(x, y, 1)
p = numpy.poly1d(z)
pylab.plot(x,p(x),"r--")
# the line equation:
print "y=%.6fx+(%.6f)"%(z[0],z[1])
A lot of people do a common mistake of thinking that 'rvm implode' does it . You need to delete all traces of any .rm files . Also , it will take some manual deletions from root . Make sure , it gets deleted and also all the ruby versions u installed using it .
This cannot be done with pure HTML/JS, you will need CSS
CSS:
button {
width: 100%;
height: 100%;
}
Substitute 100% with required size
This can be done in many ways
int[] array = { 1, 3, 5 };
var lastItem = array[^1]; // 5
All tags must have enclosing tags. In my case, the hr and input elements weren't closed properly.
Parent Error was: JSX element 'div' has no corresponding closing tag, due to code below:
<hr class="my-4">
<input
type="password"
id="inputPassword"
class="form-control"
placeholder="Password"
required
>
Fix:
<hr class="my-4"/>
<input
type="password"
id="inputPassword"
class="form-control"
placeholder="Password"
required
/>
The parent elements will show errors due to child element errors. Therefore, start investigating from most inner elements up to the parent ones.
git diff
and git apply
will work for text files, but won't work for binary files.
You can easily create a full binary patch, but you will have to create a temporary commit. Once you've made your temporary commit(s), you can create the patch with:
git format-patch <options...>
After you've made the patch, run this command:
git reset --mixed <SHA of commit *before* your working-changes commit(s)>
This will roll back your temporary commit(s). The final result leaves your working copy (intentionally) dirty with the same changes you originally had.
On the receiving side, you can use the same trick to apply the changes to the working copy, without having the commit history. Simply apply the patch(es), and git reset --mixed <SHA of commit *before* the patches>
.
Note that you might have to be well-synced for this whole option to work. I've seen some errors when applying patches when the person making them hadn't pulled down as many changes as I had. There are probably ways to get it to work, but I haven't looked far into it.
Here's how to create the same patches in Tortoise Git (not that I recommend using that tool):
Tortoise Git
-> Create Patch Serial
Since
: FETCH_HEAD
will work if you're well-synced)Tortise Git
-> Show Log
reset "<branch>" to this...
Mixed
optionAnd how to apply them:
Tortoise Git
-> Apply Patch Serial
Tortise Git
-> Show Log
reset "<branch>" to this...
Mixed
optionTry this
$("#message span").text("hello world!");
function Errormessage(txt) {
var elem = $("#message");
elem.fadeIn("slow");
// find the span inside the div and assign a text
elem.children("span").text("your text");
elem.children("a.close-notify").click(function() {
elem.fadeOut("slow");
});
}
import operator
sorted_x = sorted(x, key=operator.attrgetter('score'))
if you want to sort x in-place, you can also:
x.sort(key=operator.attrgetter('score'))
Addendum to @sjngm's answer:
They both also ignore whitespace:
var foo = " 3 ";
console.log(parseInt(foo)); // 3
console.log(Number(foo)); // 3
If you patch /Developer/Platforms/iPhoneOS.platform/Info.plist
and then try to debug a application running on the device using a real development provisionen profile from Apple it will probably not work. Symptoms are weird error messages from com.apple.debugserver
and that you can use any bundle identifier without getting a error when building in Xcode. The solution is to restore Info.plist
.
In which scenarios does one out-perform the other?
For smaller tables (less than 1000 rows) use a temp variable, otherwise use a temp table.
For me this worked: (added into .ssh\config
)
Host *
HostkeyAlgorithms +ssh-dss
PubkeyAcceptedKeyTypes +ssh-dss
Try to use this code:
.col-lg-3 {
width: 100%;
}
.input-group {
width: 200px; // for exemple
margin: 0 auto;
}
if it didn't work use !important
you can use skimage.img_as_ubyte(yourdata)
it will make you numpy array ranges from 0->255
from skimage import img_as_ubyte
img = img_as_ubyte(data)
cv2.imshow("Window", img)
If you want greater control you can use javascript rather than use the meta tag. This would allow you to have a visual of some kind, e.g. a countdown.
Here is a very basic approach using setTimeout()
<html>_x000D_
<body>_x000D_
<p>You will be redirected in 3 seconds</p>_x000D_
<script>_x000D_
var timer = setTimeout(function() {_x000D_
window.location='http://example.com'_x000D_
}, 3000);_x000D_
</script>_x000D_
</body>_x000D_
</html>
_x000D_
(1..4).each { |i|
a = 9 if i==3
puts a
}
#nil
#nil
#9
#nil
for i in 1..4
a = 9 if i==3
puts a
end
#nil
#nil
#9
#9
In 'for' loop, local variable is still lives after each loop. In 'each' loop, local variable refreshes after each loop.
If you're talking about ASP.NET MVC then you should have a controller method that returns the following:
return Redirect("http://www.google.com");
Otherwise we need more info on the error you're getting in the redirect. I'd step through to make sure the url isn't empty.
"Curly Braces" are used in Python to define a dictionary. A dictionary is a data structure that maps one value to another - kind of like how an English dictionary maps a word to its definition.
Python:
dict = {
"a" : "Apple",
"b" : "Banana",
}
They are also used to format strings, instead of the old C style using %, like:
ds = ['a', 'b', 'c', 'd']
x = ['has_{} 1'.format(d) for d in ds]
print x
['has_a 1', 'has_b 1', 'has_c 1', 'has_d 1']
They are not used to denote code blocks as they are in many "C-like" languages.
C:
if (condition) {
// do this
}
The most intuitive way of doing this without using literals
or regular expressions
:
yourString.replaceAll(" ","");
I also had this question and found two more things very useful:
So I use something like this on the command line (OSX 10.9):
ping www.goooooogle.com & PING_PID=$(pgrep 'ping'); SECONDS=0; while pgrep -q 'ping'; do sleep 0.2; if [ $SECONDS = 10 ]; then kill $PING_PID; fi; done
As this is a loop I included a "sleep 0.2" to keep the CPU cool. ;-)
(BTW: ping is a bad example anyway, you just would use the built-in "-t" (timeout) option.)
If you are in windows you can just run
net user postgres postgres
and login in postgres with postgres/postgres as user/password
The main use of -f
is to force the removal of files that would
not be removed using rm
by itself (as a special case, it "removes"
non-existent files, thus suppressing the error message).
You can also just redirect the error message using
$ rm file.txt 2> /dev/null
(or your operating system's equivalent). You can check the value of $?
immediately after calling rm
to see if a file was actually removed or not.
It doesn't matter. In terms of REST, you can't do a GET, because it's not cacheable, but it doesn't matter if you use POST or PATCH or PUT or whatever, and it doesn't matter what the URL looks like. If you're doing REST, what matters is that when you get a representation of your resource from the server, that representation is able give the client state transition options.
If your GET response had state transitions, the client just needs to know how to read them, and the server can change them if needed. Here an update is done using POST, but if it was changed to PATCH, or if the URL changes, the client still knows how to make an update:
{
"customer" :
{
},
"operations":
[
"update" :
{
"method": "POST",
"href": "https://server/customer/123/"
}]
}
You could go as far as to list required/optional parameters for the client to give back to you. It depends on the application.
As far as business operations, that might be a different resource linked to from the customer resource. If you want to send an email to the customer, maybe that service is it's own resource that you can POST to, so you might include the following operation in the customer resource:
"email":
{
"method": "POST",
"href": "http://server/emailservice/send?customer=1234"
}
Some good videos, and example of the presenter's REST architecture are these. Stormpath only uses GET/POST/DELETE, which is fine since REST has nothing to do with what operations you use or how URLs should look (except GETs should be cacheable):
https://www.youtube.com/watch?v=pspy1H6A3FM,
https://www.youtube.com/watch?v=5WXYw4J4QOU,
http://docs.stormpath.com/rest/quickstart/
Had the same issue with VirtualBox 5.0.16/rXXX
Installed latest VirtualBox 5.0.18 and installed latest Vagrant 1.9.3, issue went toodles.
where somefield like '%a%' or somefield like '%b%'
Hi guys I found a new solution. Actually it is defined in another template so instead of defining TEMPLATE_DIRS yourself, put your directory path name at their:
if you want to stay DRY, use an include.
{% if foo %}
{% with a as b %}
{% include "snipet.html" %}
{% endwith %}
{% else %}
{% with bar as b %}
{% include "snipet.html" %}
{% endwith %}
{% endif %}
or, even better would be to write a method on the model that encapsulates the core logic:
def Patient(models.Model):
....
def get_legally_responsible_party(self):
if self.age > 18:
return self
else:
return self.parent
Then in the template:
{% with patient.get_legally_responsible_party as p %}
Do html stuff
{% endwith %}
Then in the future, if the logic for who is legally responsible changes you have a single place to change the logic -- far more DRY than having to change if statements in a dozen templates.
I did want to obmit a old big history and start from a fresh commit i choosed to:
rsync -a --exclude '.git' old-repo/ new-repo/
cd new-repo
git push
when now old-repo changes i can apply the patches to the new-repo to rebase them on the new-repo.
Detecting and Correcting the ObjectID Error
I stumbled into this problem when trying to delete an item using mongoose and got the same error. After looking over the return string, I found there were some extra spaces inside the returned string which caused the error for me. So, I applied a few of the answers provided here to detect the erroneous id then remove the extra spaces from the string. Here is the code that worked for me to finally resolve the issue.
const mongoose = require("mongoose");
mongoose.set('useFindAndModify', false); //was set due to DeprecationWarning: Mongoose: `findOneAndUpdate()` and `findOneAndDelete()` without the `useFindAndModify`
app.post("/delete", function(req, res){
let checkedItem = req.body.deleteItem;
if (!mongoose.Types.ObjectId.isValid(checkedItem)) {
checkedItem = checkedItem.replace(/\s/g, '');
}
Item.findByIdAndRemove(checkedItem, function(err) {
if (!err) {
console.log("Successfully Deleted " + checkedItem);
res.redirect("/");
}
});
});
This worked for me and I assume if other items start to appear in the return string they can be removed in a similar way.
I hope this helps.
JQuery is looking for a json type result, but because the redirect is processed automatically, it will receive the generated html source of your login.htm
page.
One idea is to let the the browser know that it should redirect by adding a redirect
variable to to the resulting object and checking for it in JQuery:
$(document).ready(function(){
jQuery.ajax({
type: "GET",
url: "populateData.htm",
dataType:"json",
data:"userId=SampleUser",
success:function(response){
if (response.redirect) {
window.location.href = response.redirect;
}
else {
// Process the expected results...
}
},
error: function(xhr, textStatus, errorThrown) {
alert('Error! Status = ' + xhr.status);
}
});
});
You could also add a Header Variable to your response and let your browser decide where to redirect. In Java, instead of redirecting, do response.setHeader("REQUIRES_AUTH", "1")
and in JQuery you do on success(!):
//....
success:function(response){
if (response.getResponseHeader('REQUIRES_AUTH') === '1'){
window.location.href = 'login.htm';
}
else {
// Process the expected results...
}
}
//....
Hope that helps.
My answer is heavily inspired by this thread which shouldn't left any questions in case you still have some problems.
If used ispconfig3:
Go to Website section -> Options -> PHP open_basedir:
/var/www/clients/client2/web3/image:/var/www/clients/client2/web3/web:/var/www/... and so on
/var/www/clients/client2/web3/image:
When a script tries to access the filesystem, for example using include, or fopen(), the location of the file is checked. When the file is outside the specified directory-tree, PHP will refuse to access it.
Unfortunately, stringByAddingPercentEscapesUsingEncoding
doesn't always work 100%. It encodes non-URL characters but leaves the reserved characters (like slash /
and ampersand &
) alone. Apparently this is a bug that Apple is aware of, but since they have not fixed it yet, I have been using this category to url-encode a string:
@implementation NSString (NSString_Extended)
- (NSString *)urlencode {
NSMutableString *output = [NSMutableString string];
const unsigned char *source = (const unsigned char *)[self UTF8String];
int sourceLen = strlen((const char *)source);
for (int i = 0; i < sourceLen; ++i) {
const unsigned char thisChar = source[i];
if (thisChar == ' '){
[output appendString:@"+"];
} else if (thisChar == '.' || thisChar == '-' || thisChar == '_' || thisChar == '~' ||
(thisChar >= 'a' && thisChar <= 'z') ||
(thisChar >= 'A' && thisChar <= 'Z') ||
(thisChar >= '0' && thisChar <= '9')) {
[output appendFormat:@"%c", thisChar];
} else {
[output appendFormat:@"%%%02X", thisChar];
}
}
return output;
}
Used like this:
NSString *urlEncodedString = [@"SOME_URL_GOES_HERE" urlencode];
// Or, with an already existing string:
NSString *someUrlString = @"someURL";
NSString *encodedUrlStr = [someUrlString urlencode];
This also works:
NSString *encodedString = (NSString *)CFURLCreateStringByAddingPercentEscapes(
NULL,
(CFStringRef)unencodedString,
NULL,
(CFStringRef)@"!*'();:@&=+$,/?%#[]",
kCFStringEncodingUTF8 );
Some good reading about the subject:
Objective-c iPhone percent encode a string?
Objective-C and Swift URL encoding
http://cybersam.com/programming/proper-url-percent-encoding-in-ios
https://devforums.apple.com/message/15674#15674
http://simonwoodside.com/weblog/2009/4/22/how_to_really_url_encode/
$('#submit_button').click(function() {
if (!$("input[@name='name']:checked").val()) {
alert('Nothing is checked!');
return false;
}
else {
alert('One of the radio buttons is checked!');
}
});
.combobox_selector ul {
padding: 0;
margin: 0;
list-style: none;
border:1px solid #CCC;
height: 200px;
overflow: auto;
overflow-x: hidden;
}
sets 200px scrolldown size, overflow-x
hides any horizontal scrollbar.
To add a "local" package to your project, add a folder (for example "package_name"). And put your implementation files in that folder.
src/github.com/GithubUser/myproject/
+-- main.go
+---package_name
+-- whatever_name1.go
+-- whatever_name2.go
In your package main
do this:
import "github.com/GithubUser/myproject/package_name"
Where package_name
is the folder name and it must match the package name used in files whatever_name1.go and whatever_name2.go. In other words all files with a sub-directory should be of the same package.
You can further nest more subdirectories as long as you specify the whole path to the parent folder in the import.
Create a user like this:
db.createUser(
{
user: "myUserAdmin",
pwd: "abc123",
roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
}
)
Then connect it following this:
mongo --port 27017 -u "myUserAdmin" -p "abc123" --authenticationDatabase "admin"
Check the manual :
https://docs.mongodb.org/manual/tutorial/enable-authentication/
Take a look at the Tiny But Strong templating system. It's generally used for templating HTML but there's an extension that works with XML files. I use this extensively for creating reports where I can have one code file and two template files - htm and xml - and the user can then choose whether to send a report to screen or spreadsheet.
Another advantage is you don't have to code the xml from scratch, in some cases I've been wanting to export very large complex spreadsheets, and instead of having to code all the export all that is required is to save an existing spreadsheet in xml and substitute in code tags where data output is required. It's a quick and a very efficient way to work.
The key difference: NSMutableDictionary can be modified in place, NSDictionary cannot. This is true for all the other NSMutable* classes in Cocoa. NSMutableDictionary is a subclass of NSDictionary, so everything you can do with NSDictionary you can do with both. However, NSMutableDictionary also adds complementary methods to modify things in place, such as the method setObject:forKey:
.
You can convert between the two like this:
NSMutableDictionary *mutable = [[dict mutableCopy] autorelease];
NSDictionary *dict = [[mutable copy] autorelease];
Presumably you want to store data by writing it to a file. NSDictionary has a method to do this (which also works with NSMutableDictionary):
BOOL success = [dict writeToFile:@"/file/path" atomically:YES];
To read a dictionary from a file, there's a corresponding method:
NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:@"/file/path"];
If you want to read the file as an NSMutableDictionary, simply use:
NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithContentsOfFile:@"/file/path"];
@font-face {
font-family: 'RieslingRegular';
src: url('fonts/riesling.eot');
src: local('Riesling Regular'), local('Riesling'), url('fonts/riesling.ttf') format('truetype');
}
I found this thread on that there Interweb thing. Boils down to:
@echo off
setlocal enableextensions
for /f "tokens=*" %%a in (
'VER'
) do (
set myvar=%%a
)
echo/%%myvar%%=%myvar%
pause
endlocal
You can also redirect the output of a command to a temporary file, and then put the contents of that temporary file into your variable, likesuchashereby. It doesn't work with multiline input though.
cmd > tmpFile
set /p myvar= < tmpFile
del tmpFile
Credit to the thread on Tom's Hardware.
Premise to my answer:
Approach
Additionally, the base image can be upgraded/ the container with a complete new base image can be built at regular intervals, as the maintainer feels necessary
Advantages
Thanks HansUp for your answer, it is very helpful and it works!
I found three patterns working in Access, yours is the best, because it works in all cases.
INNER JOIN, your variant. I will call it "closed set pattern". It is possible to join more than two tables to the same table with good performance only with this pattern.
SELECT C_Name, cr.P_FirstName+" "+cr.P_SurName AS ClassRepresentativ, cr2.P_FirstName+" "+cr2.P_SurName AS ClassRepresentativ2nd
FROM
((class
INNER JOIN person AS cr
ON class.C_P_ClassRep=cr.P_Nr
)
INNER JOIN person AS cr2
ON class.C_P_ClassRep2nd=cr2.P_Nr
)
;
INNER JOIN "chained-set pattern"
SELECT C_Name, cr.P_FirstName+" "+cr.P_SurName AS ClassRepresentativ, cr2.P_FirstName+" "+cr2.P_SurName AS ClassRepresentativ2nd
FROM person AS cr
INNER JOIN ( class
INNER JOIN ( person AS cr2
) ON class.C_P_ClassRep2nd=cr2.P_Nr
) ON class.C_P_ClassRep=cr.P_Nr
;
CROSS JOIN with WHERE
SELECT C_Name, cr.P_FirstName+" "+cr.P_SurName AS ClassRepresentativ, cr2.P_FirstName+" "+cr2.P_SurName AS ClassRepresentativ2nd
FROM class, person AS cr, person AS cr2
WHERE class.C_P_ClassRep=cr.P_Nr AND class.C_P_ClassRep2nd=cr2.P_Nr
;
Since Spring 5 you just need to implement the interface WebMvcConfigurer
:
public class MvcConfig implements WebMvcConfigurer {
This is because Java 8 introduced default methods on interfaces which cover the functionality of the WebMvcConfigurerAdapter
class
See here:
I just declare an interface and use a variable of that type access the enum. Keeping the interface and enum in sync is actually easy, since TypeScript complains if something changes in the enum, like so.
error TS2345: Argument of type 'typeof EAbFlagEnum' is not assignable to parameter of type 'IAbFlagEnum'. Property 'Move' is missing in type 'typeof EAbFlagEnum'.
The advantage of this method is no type casting is required in order to use the enum (interface) in various situations, and more types of situations are thus supported, such as the switch/case.
// Declare a TypeScript enum using unique string
// (per hack mentioned by zjc0816)
enum EAbFlagEnum {
None = <any> "none",
Select = <any> "sel",
Move = <any> "mov",
Edit = <any> "edit",
Sort = <any> "sort",
Clone = <any> "clone"
}
// Create an interface that shadows the enum
// and asserts that members are a type of any
interface IAbFlagEnum {
None: any;
Select: any;
Move: any;
Edit: any;
Sort: any;
Clone: any;
}
// Export a variable of type interface that points to the enum
export var AbFlagEnum: IAbFlagEnum = EAbFlagEnum;
Using the variable, rather than the enum, produces the desired results.
var strVal: string = AbFlagEnum.Edit;
switch (strVal) {
case AbFlagEnum.Edit:
break;
case AbFlagEnum.Move:
break;
case AbFlagEnum.Clone
}
Flags were another necessity for me, so I created an NPM module that adds to this example, and includes tests.
I believe the REAL answer to this question is an explanation as to how you configure what editor to use by default, if you are not comfortable with Vim.
This is how to configure Notepad for example, useful in Windows:
git config --global core.editor "notepad"
Gedit, more Linux friendly:
git config --global core.editor "gedit"
You can read the current configuration like this:
git config core.editor
I had the same problem and I resolved it like this:
Thanx schwiz for idea! Here is modified solution:
public class FileDialog {
private static final String PARENT_DIR = "..";
private final String TAG = getClass().getName();
private String[] fileList;
private File currentPath;
public interface FileSelectedListener {
void fileSelected(File file);
}
public interface DirectorySelectedListener {
void directorySelected(File directory);
}
private ListenerList<FileSelectedListener> fileListenerList = new ListenerList<FileDialog.FileSelectedListener>();
private ListenerList<DirectorySelectedListener> dirListenerList = new ListenerList<FileDialog.DirectorySelectedListener>();
private final Activity activity;
private boolean selectDirectoryOption;
private String fileEndsWith;
/**
* @param activity
* @param initialPath
*/
public FileDialog(Activity activity, File initialPath) {
this(activity, initialPath, null);
}
public FileDialog(Activity activity, File initialPath, String fileEndsWith) {
this.activity = activity;
setFileEndsWith(fileEndsWith);
if (!initialPath.exists()) initialPath = Environment.getExternalStorageDirectory();
loadFileList(initialPath);
}
/**
* @return file dialog
*/
public Dialog createFileDialog() {
Dialog dialog = null;
AlertDialog.Builder builder = new AlertDialog.Builder(activity);
builder.setTitle(currentPath.getPath());
if (selectDirectoryOption) {
builder.setPositiveButton("Select directory", new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Log.d(TAG, currentPath.getPath());
fireDirectorySelectedEvent(currentPath);
}
});
}
builder.setItems(fileList, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
String fileChosen = fileList[which];
File chosenFile = getChosenFile(fileChosen);
if (chosenFile.isDirectory()) {
loadFileList(chosenFile);
dialog.cancel();
dialog.dismiss();
showDialog();
} else fireFileSelectedEvent(chosenFile);
}
});
dialog = builder.show();
return dialog;
}
public void addFileListener(FileSelectedListener listener) {
fileListenerList.add(listener);
}
public void removeFileListener(FileSelectedListener listener) {
fileListenerList.remove(listener);
}
public void setSelectDirectoryOption(boolean selectDirectoryOption) {
this.selectDirectoryOption = selectDirectoryOption;
}
public void addDirectoryListener(DirectorySelectedListener listener) {
dirListenerList.add(listener);
}
public void removeDirectoryListener(DirectorySelectedListener listener) {
dirListenerList.remove(listener);
}
/**
* Show file dialog
*/
public void showDialog() {
createFileDialog().show();
}
private void fireFileSelectedEvent(final File file) {
fileListenerList.fireEvent(new FireHandler<FileDialog.FileSelectedListener>() {
public void fireEvent(FileSelectedListener listener) {
listener.fileSelected(file);
}
});
}
private void fireDirectorySelectedEvent(final File directory) {
dirListenerList.fireEvent(new FireHandler<FileDialog.DirectorySelectedListener>() {
public void fireEvent(DirectorySelectedListener listener) {
listener.directorySelected(directory);
}
});
}
private void loadFileList(File path) {
this.currentPath = path;
List<String> r = new ArrayList<String>();
if (path.exists()) {
if (path.getParentFile() != null) r.add(PARENT_DIR);
FilenameFilter filter = new FilenameFilter() {
public boolean accept(File dir, String filename) {
File sel = new File(dir, filename);
if (!sel.canRead()) return false;
if (selectDirectoryOption) return sel.isDirectory();
else {
boolean endsWith = fileEndsWith != null ? filename.toLowerCase().endsWith(fileEndsWith) : true;
return endsWith || sel.isDirectory();
}
}
};
String[] fileList1 = path.list(filter);
for (String file : fileList1) {
r.add(file);
}
}
fileList = (String[]) r.toArray(new String[]{});
}
private File getChosenFile(String fileChosen) {
if (fileChosen.equals(PARENT_DIR)) return currentPath.getParentFile();
else return new File(currentPath, fileChosen);
}
private void setFileEndsWith(String fileEndsWith) {
this.fileEndsWith = fileEndsWith != null ? fileEndsWith.toLowerCase() : fileEndsWith;
}
}
class ListenerList<L> {
private List<L> listenerList = new ArrayList<L>();
public interface FireHandler<L> {
void fireEvent(L listener);
}
public void add(L listener) {
listenerList.add(listener);
}
public void fireEvent(FireHandler<L> fireHandler) {
List<L> copy = new ArrayList<L>(listenerList);
for (L l : copy) {
fireHandler.fireEvent(l);
}
}
public void remove(L listener) {
listenerList.remove(listener);
}
public List<L> getListenerList() {
return listenerList;
}
}
Use it on activity onCreate (directory selection option is commented):
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
File mPath = new File(Environment.getExternalStorageDirectory() + "//DIR//");
fileDialog = new FileDialog(this, mPath, ".txt");
fileDialog.addFileListener(new FileDialog.FileSelectedListener() {
public void fileSelected(File file) {
Log.d(getClass().getName(), "selected file " + file.toString());
}
});
//fileDialog.addDirectoryListener(new FileDialog.DirectorySelectedListener() {
// public void directorySelected(File directory) {
// Log.d(getClass().getName(), "selected dir " + directory.toString());
// }
//});
//fileDialog.setSelectDirectoryOption(false);
fileDialog.showDialog();
}
I ran into this and it ended up being I was opening the file with the text editor and not the java editor.
I wanted to comment on https://stackoverflow.com/users/607470/elroy-flynn response but the add comment only works after I have a rating of 50? not sure WTF that is...
Thanks, Tom
Verbose, but copied from the HTTP 1.1 method specification at http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html
The GET method means retrieve whatever information (in the form of an entity) is identified by the Request-URI. If the Request-URI refers to a data-producing process, it is the produced data which shall be returned as the entity in the response and not the source text of the process, unless that text happens to be the output of the process.
The semantics of the GET method change to a "conditional GET" if the request message includes an If-Modified-Since, If-Unmodified-Since, If-Match, If-None-Match, or If-Range header field. A conditional GET method requests that the entity be transferred only under the circumstances described by the conditional header field(s). The conditional GET method is intended to reduce unnecessary network usage by allowing cached entities to be refreshed without requiring multiple requests or transferring data already held by the client.
The semantics of the GET method change to a "partial GET" if the request message includes a Range header field. A partial GET requests that only part of the entity be transferred, as described in section 14.35. The partial GET method is intended to reduce unnecessary network usage by allowing partially-retrieved entities to be completed without transferring data already held by the client.
The response to a GET request is cacheable if and only if it meets the requirements for HTTP caching described in section 13.
See section 15.1.3 for security considerations when used for forms.
The POST method is used to request that the origin server accept the entity enclosed in the request as a new subordinate of the resource identified by the Request-URI in the Request-Line. POST is designed to allow a uniform method to cover the following functions:
- Annotation of existing resources;
- Posting a message to a bulletin board, newsgroup, mailing list,
or similar group of articles;
- Providing a block of data, such as the result of submitting a
form, to a data-handling process;
- Extending a database through an append operation.
The actual function performed by the POST method is determined by the server and is usually dependent on the Request-URI. The posted entity is subordinate to that URI in the same way that a file is subordinate to a directory containing it, a news article is subordinate to a newsgroup to which it is posted, or a record is subordinate to a database.
The action performed by the POST method might not result in a resource that can be identified by a URI. In this case, either 200 (OK) or 204 (No Content) is the appropriate response status, depending on whether or not the response includes an entity that describes the result.
If a resource has been created on the origin server, the response SHOULD be 201 (Created) and contain an entity which describes the status of the request and refers to the new resource, and a Location header (see section 14.30).
Responses to this method are not cacheable, unless the response includes appropriate Cache-Control or Expires header fields. However, the 303 (See Other) response can be used to direct the user agent to retrieve a cacheable resource.
POST requests MUST obey the message transmission requirements set out in section 8.2.
See section 15.1.3 for security considerations.
The PUT method requests that the enclosed entity be stored under the supplied Request-URI. If the Request-URI refers to an already existing resource, the enclosed entity SHOULD be considered as a modified version of the one residing on the origin server. If the Request-URI does not point to an existing resource, and that URI is capable of being defined as a new resource by the requesting user agent, the origin server can create the resource with that URI. If a new resource is created, the origin server MUST inform the user agent via the 201 (Created) response. If an existing resource is modified, either the 200 (OK) or 204 (No Content) response codes SHOULD be sent to indicate successful completion of the request. If the resource could not be created or modified with the Request-URI, an appropriate error response SHOULD be given that reflects the nature of the problem. The recipient of the entity MUST NOT ignore any Content-* (e.g. Content-Range) headers that it does not understand or implement and MUST return a 501 (Not Implemented) response in such cases.
If the request passes through a cache and the Request-URI identifies one or more currently cached entities, those entries SHOULD be treated as stale. Responses to this method are not cacheable.
The fundamental difference between the POST and PUT requests is reflected in the different meaning of the Request-URI. The URI in a POST request identifies the resource that will handle the enclosed entity. That resource might be a data-accepting process, a gateway to some other protocol, or a separate entity that accepts annotations. In contrast, the URI in a PUT request identifies the entity enclosed with the request -- the user agent knows what URI is intended and the server MUST NOT attempt to apply the request to some other resource. If the server desires that the request be applied to a different URI,
it MUST send a 301 (Moved Permanently) response; the user agent MAY then make its own decision regarding whether or not to redirect the request.
A single resource MAY be identified by many different URIs. For example, an article might have a URI for identifying "the current version" which is separate from the URI identifying each particular version. In this case, a PUT request on a general URI might result in several other URIs being defined by the origin server.
HTTP/1.1 does not define how a PUT method affects the state of an origin server.
PUT requests MUST obey the message transmission requirements set out in section 8.2.
Unless otherwise specified for a particular entity-header, the entity-headers in the PUT request SHOULD be applied to the resource created or modified by the PUT.
The DELETE method requests that the origin server delete the resource identified by the Request-URI. This method MAY be overridden by human intervention (or other means) on the origin server. The client cannot be guaranteed that the operation has been carried out, even if the status code returned from the origin server indicates that the action has been completed successfully. However, the server SHOULD NOT indicate success unless, at the time the response is given, it intends to delete the resource or move it to an inaccessible location.
A successful response SHOULD be 200 (OK) if the response includes an entity describing the status, 202 (Accepted) if the action has not yet been enacted, or 204 (No Content) if the action has been enacted but the response does not include an entity.
If the request passes through a cache and the Request-URI identifies one or more currently cached entities, those entries SHOULD be treated as stale. Responses to this method are not cacheable.
<form (submit)="addTodo()">_x000D_
<input type="text" [(ngModel)]="text">_x000D_
</form>
_x000D_
As mentioned by nux and micheg79 a node is left behind in the DOM after the dialog closes.
This can also be cleaned up simply by adding:
$(this).dialog('destroy').remove();
to the close method of the dialog. Example adding this line to eidylon's answer:
function jqAlert(outputMsg, titleMsg, onCloseCallback) {
if (!titleMsg)
titleMsg = 'Alert';
if (!outputMsg)
outputMsg = 'No Message to Display.';
$("<div></div>").html(outputMsg).dialog({
title: titleMsg,
resizable: false,
modal: true,
buttons: {
"OK": function () {
$(this).dialog("close");
}
},
close: function() { onCloseCallback();
/* Cleanup node(s) from DOM */
$(this).dialog('destroy').remove();
}
});
}
EDIT: I had problems getting callback function to run and found that I had to add parentheses () to onCloseCallback to actually trigger the callback. This helped me understand why: In JavaScript, does it make a difference if I call a function with parentheses?
Got it.
sort(mMyClassVector.begin(), mMyClassVector.end(),
[](const MyClass & a, const MyClass & b) -> bool
{
return a.mProperty > b.mProperty;
});
I assumed it'd figure out that the > operator returned a bool (per documentation). But apparently it is not so.
This should fulfill your requirements.
ABC:\s*(\(\D+\)\s*.*?)\\n
Here it is with some tests http://www.regexplanet.com/cookbook/ahJzfnJlZ2V4cGxhbmV0LWhyZHNyDgsSBlJlY2lwZRiEjiUM/index.html
Futher reading on regular expressions: http://www.regular-expressions.info/characters.html
This error happens to me when I am pushing my commit and my computer hangs. This is how I've fix it.
git status
show the empty/corrupt object file
rm .git/objects/08/3834cb34d155e67a8930604d57d3d302d7ec12
remove it
git status
I got fatal: bad object HEAD
message
rm .git/index
I remove the index
for the reset
git reset
fatal: Could not parse object 'HEAD'.
git status
git pull
just to check whats happening
tail -n 2 .git/logs/refs/heads/MY-CURRENT-BRANCH
prints the last 2 lines tail -n 2
of log branch to show my last 2 commit hash
git update-ref HEAD 7221fa02cb627470db163826da4265609aba47b2
I pick the last commit hash
git status
shows all my file as deleted
because i removed the .git/index
file
git reset
continue to the reset
git status
verify my fix
Note: The steps starts when I landed on this question and used the answers as reference.
The browser is complaining because you're using JavaScript to close a window that wasn't opened with JavaScript, i.e. window.open('foo.html');
.
Your @Entity
class has a String
type for its @Id
field, so it can't generate ids for you.
If you change it to an auto increment in the DB and a Long
in java, and add the @GeneratedValue
annotation:
@Id
@Column(name="U_id")
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Long U_id;
it will handle incrementing id generation for you.
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script>
$(document).ready(function(){
var locations = ["http://webPage1.com", "http://webPage2.com"];
var len = locations.length;
var iframe = $('#frame');
var i = 0;
setInterval(function () {
iframe.attr('src', locations[++i % len]);
}, 30000);
});
</script>
</head>
<body>
<iframe id="frame"></iframe>
</body>
</html>
"1".PadLeft(4, '0');
Its a bit counter-intuitive. The toolchain is called gcc-arm-linux-gnueabi. To invoke the tools execute the following: arm-linux-gnueabi-xxx
where xxx is gcc or ar or ld, etc
An HTML parser should be used for this purpose rather than regular expressions. A Perl program that makes use of HTML::TreeBuilder
:
#!/usr/bin/env perl
use strict;
use warnings;
use HTML::TreeBuilder;
my $tree = HTML::TreeBuilder->new_from_file( \*DATA );
my @elements = $tree->look_down(
sub { defined $_[0]->attr('name') }
);
for (@elements) {
print $_->attr('name'), "\n";
}
__DATA__
<table name="content_analyzer" primary-key="id">
<type="global" />
</table>
<table name="content_analyzer2" primary-key="id">
<type="global" />
</table>
<table name="content_analyzer_items" primary-key="id">
<type="global" />
</table>
content_analyzer
content_analyzer2
content_analyzer_items
There is no way to know unless the particular company reveals the info. The best you can do is find a few companies that are sharing and then extrapolate based on app ranking (which is available publicly). The best you'll get is a ball park estimate.
Set the CommandText
as well, and call Fill
on the SqlAdapter
to retrieve the results in a DataSet
:
var con = new SqlConnection();
con.ConnectionString = "connection string";
var com = new SqlCommand();
com.Connection = con;
com.CommandType = CommandType.StoredProcedure;
com.CommandText = "sp_returnTable";
var adapt = new SqlDataAdapter();
adapt.SelectCommand = com;
var dataset = new DataSet();
adapt.Fill(dataset);
(Example is using parameterless constructors for clarity; can be shortened by using other constructors.)
byte[] bytes = { 1,2,3,4 };
string stringByte= BitConverter.ToString(bytes);
Console.WriteLine(stringByte);
When your network team does ssl-inspection by rewriting certificates, then using a http url instead of a https one, combined with setting this var worked for me.
git config --global http.proxy http://proxy:8081
Apart from tuples being immutable there is also a semantic distinction that should guide their usage. Tuples are heterogeneous data structures (i.e., their entries have different meanings), while lists are homogeneous sequences. Tuples have structure, lists have order.
Using this distinction makes code more explicit and understandable.
One example would be pairs of page and line number to reference locations in a book, e.g.:
my_location = (42, 11) # page number, line number
You can then use this as a key in a dictionary to store notes on locations. A list on the other hand could be used to store multiple locations. Naturally one might want to add or remove locations from the list, so it makes sense that lists are mutable. On the other hand it doesn't make sense to add or remove items from an existing location - hence tuples are immutable.
There might be situations where you want to change items within an existing location tuple, for example when iterating through the lines of a page. But tuple immutability forces you to create a new location tuple for each new value. This seems inconvenient on the face of it, but using immutable data like this is a cornerstone of value types and functional programming techniques, which can have substantial advantages.
There are some interesting articles on this issue, e.g. "Python Tuples are Not Just Constant Lists" or "Understanding tuples vs. lists in Python". The official Python documentation also mentions this
"Tuples are immutable, and usually contain an heterogeneous sequence ...".
In a statically typed language like Haskell the values in a tuple generally have different types and the length of the tuple must be fixed. In a list the values all have the same type and the length is not fixed. So the difference is very obvious.
Finally there is the namedtuple in Python, which makes sense because a tuple is already supposed to have structure. This underlines the idea that tuples are a light-weight alternative to classes and instances.
Your format specifier is incorrect. From the printf()
man page on my machine:
0
A zero '0
' character indicating that zero-padding should be used rather than blank-padding. A '-
' overrides a '0
' if both are used;Field Width: An optional digit string specifying a field width; if the output string has fewer characters than the field width it will be blank-padded on the left (or right, if the left-adjustment indicator has been given) to make up the field width (note that a leading zero is a flag, but an embedded zero is part of a field width);
Precision: An optional period, '
.
', followed by an optional digit string giving a precision which specifies the number of digits to appear after the decimal point, for e and f formats, or the maximum number of characters to be printed from a string; if the digit string is missing, the precision is treated as zero;
For your case, your format would be %09.3f
:
#include <stdio.h>
int main(int argc, char **argv)
{
printf("%09.3f\n", 4917.24);
return 0;
}
Output:
$ make testapp
cc testapp.c -o testapp
$ ./testapp
04917.240
Note that this answer is conditional on your embedded system having a printf()
implementation that is standard-compliant for these details - many embedded environments do not have such an implementation.
Edited updated to clarify the various options (depending on what your desired intentions are)
See @noah's answer for full details
//Option A.) set to null
some_var = null;
//Option B.) set to undefined
some_var = undefined;
//Option C.) remove/delete the variable reference
delete obj.some_var
//if your variable was defined as a global, you'll need to
//qualify the reference with 'window'
delete window.some_var;
References:
MDN SyntaxError when deleting an unqualified variable name in strict mode
I encountered this error when the JDK that I compiled the app under was different from the tomcat JVM. I verified that the Tomcat manager was running jvm 1.6.0 but the app was compiled under java 1.7.0.
After upgrading Java and changing JAVA_HOME in our startup script (/etc/init.d/tomcat) the error went away.
Iterate over any item in the array. For every item you visit, check that item's id. If it's a match, return it.
If you just want teh codez:
function getId(array, id) {
for (var i = 0, len = array.length; i < len; i++) {
if (array[i].id === id) {
return array[i];
}
}
return null; // Nothing found
}
And the same thing using ECMAScript 5's Array methods:
function getId(array, id) {
var obj = array.filter(function (val) {
return val.id === id;
});
// Filter returns an array, and we just want the matching item.
return obj[0];
}
Since your local repository is few commits ahead, git tries to merge your remote to your local repo. This can be handled via merge, but in your case, perhaps you are looking for rebase, i.e. add your commit to the top. You can do this with
git rebase
or git pull --rebase
Here is a good article explaining the difference between git pull
& git pull --rebase
.
https://www.derekgourlay.com/blog/git-when-to-merge-vs-when-to-rebase/
Start at one of the vertices, and compute the angle subtended by each side.
The first and the last will be zero (so skip those); for the rest, the sine of the angle will be given by the cross product of the normalizations to unit length of (point[n]-point[0]) and (point[n-1]-point[0]).
If the sum of the values is positive, then your polygon is drawn in the anti-clockwise sense.
With the latest NodeJS you can experiment with this monkey patch:
const http = require("http");
const originalOnSocket = http.ClientRequest.prototype.onSocket;
require("http").ClientRequest.prototype.onSocket = function(socket) {
const that = this;
socket.setTimeout(this.timeout ? this.timeout : 3000);
socket.on('timeout', function() {
that.abort();
});
originalOnSocket.call(this, socket);
};
After Redis 2.6, the result of INFO command are splitted by sections. In the "keyspace" section, there are "keys" and "expired keys" fields to tell how many keys are there.
You can create an empty file whether it exists or not ...
new FileOutputStream("score.txt", false).close();
if you want to leave the file if it exists ...
new FileOutputStream("score.txt", true).close();
You will only get a FileNotFoundException if you try to create the file in a directory which doesn't exist.
Turns out that the post (or rather the whole table) was locked by the very same connection that I tried to update the post with.
I had a opened record set of the post that was created by:
Set RecSet = Conn.Execute()
This type of recordset is supposed to be read-only and when I was using MS Access as database it did not lock anything. But apparently this type of record set did lock something on MS SQL Server 2012 because when I added these lines of code before executing the UPDATE SQL statement...
RecSet.Close
Set RecSet = Nothing
...everything worked just fine.
So bottom line is to be careful with opened record sets - even if they are read-only they could lock your table from updates.
Models.py define the serializers
def default(o):
if isinstance(o, (date, datetime)):
return o.isoformat()
class User(db.Model):
__tablename__='user'
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
.......
####
def serializers(self):
dict_val={"id":self.id,"created_by":self.created_by,"created_at":self.created_at,"updated_by":self.updated_by,"updated_at":self.updated_at}
return json.loads(json.dumps(dict_val,default=default))
In RestApi, We can update the record dynamically by passing the json data into update query:
class UpdateUserDetails(Resource):
@auth_token_required
def post(self):
json_data = request.get_json()
user_id = current_user.id
try:
instance = User.query.filter(User.id==user_id)
data=instance.update(dict(json_data))
db.session.commit()
updateddata=instance.first()
msg={"msg":"User details updated successfully","data":updateddata.serializers()}
code=200
except Exception as e:
print(e)
msg = {"msg": "Failed to update the userdetails! please contact your administartor."}
code=500
return msg
Receive POST and GET request in nodejs :
1).Server
var http = require('http');
var server = http.createServer ( function(request,response){
response.writeHead(200,{"Content-Type":"text\plain"});
if(request.method == "GET")
{
response.end("received GET request.")
}
else if(request.method == "POST")
{
response.end("received POST request.");
}
else
{
response.end("Undefined request .");
}
});
server.listen(8000);
console.log("Server running on port 8000");
2). Client :
var http = require('http');
var option = {
hostname : "localhost" ,
port : 8000 ,
method : "POST",
path : "/"
}
var request = http.request(option , function(resp){
resp.on("data",function(chunck){
console.log(chunck.toString());
})
})
request.end();
From the code that you have provided, not knowing the language that you are programming in. The variable capital
is null. When you are trying to read the property length, the system cant as it is trying to deference a null variable. You need to define capital
.
https://www.codeproject.com/articles/317700/convert-a-pdf-into-a-series-of-images-using-csharp
I found this GhostScript wrapper to be working like a charm for converting the PDFs to PNGs, page by page.
Usage:
string pdf_filename = @"C:\TEMP\test.pdf";
var pdf2Image = new Cyotek.GhostScript.PdfConversion.Pdf2Image(pdf_filename);
for (var page = 1; page < pdf2Image.PageCount; page++)
{
string png_filename = @"C:\TEMP\test" + page + ".png";
pdf2Image.ConvertPdfPageToImage(png_filename, page);
}
Being built on GhostScript, obviously for commercial application the licensing question remains.
Since a comprehensive list does not appear to exist, let's start one here on SO. This can be of great value to the ASP.NET MVC community if people add their experience (esp. anyone who contributed to one of these). Anything implementing IViewEngine
(e.g. VirtualPathProviderViewEngine
) is fair game here. Just alphabetize new View Engines (leaving WebFormViewEngine and Razor at the top), and try to be objective in comparisons.
System.Web.Mvc.WebFormViewEngine
Design Goals:
A view engine that is used to render a Web Forms page to the response.
Pros:
Cons:
Example:
<%@ Control Inherits="System.Web.Mvc.ViewPage<IEnumerable<Product>>" %>
<% if(model.Any()) { %>
<ul>
<% foreach(var p in model){%>
<li><%=p.Name%></li>
<%}%>
</ul>
<%}else{%>
<p>No products available</p>
<%}%>
Design Goals:
Pros:
Cons:
Con Example #1 (notice the placement of "string[]..."):
@{
<h3>Team Members</h3> string[] teamMembers = {"Matt", "Joanne", "Robert"};
foreach (var person in teamMembers)
{
<p>@person</p>
}
}
Design goals:
- Respect HTML as first-class language as opposed to treating it as "just text".
- Don't mess with my HTML! The data binding code (Bellevue code) should be separate from HTML.
- Enforce strict Model-View separation
Design Goals:
The Brail view engine has been ported from MonoRail to work with the Microsoft ASP.NET MVC Framework. For an introduction to Brail, see the documentation on the Castle project website.
Pros:
Cons:
Example:
<html>
<head>
<title>${title}</title>
</head>
<body>
<p>The following items are in the list:</p>
<ul><%for element in list: output "<li>${element}</li>"%></ul>
<p>I hope that you would like Brail</p>
</body>
</html>
Hasic uses VB.NET's XML literals instead of strings like most other view engines.
Pros:
Cons:
Example:
Protected Overrides Function Body() As XElement
Return _
<body>
<h1>Hello, World</h1>
</body>
End Function
Design Goals:
NDjango is an implementation of the Django Template Language on the .NET platform, using the F# language.
Pros:
WebFormViewEngine
Design Goals:
.NET port of Rails Haml view engine. From the Haml website:
Haml is a markup language that's used to cleanly and simply describe the XHTML of any web document, without the use of inline code... Haml avoids the need for explicitly coding XHTML into the template, because it is actually an abstract description of the XHTML, with some code to generate dynamic content.
Pros:
Cons:
Example:
@type=IEnumerable<Product>
- if(model.Any())
%ul
- foreach (var p in model)
%li= p.Name
- else
%p No products available
NVelocityViewEngine (MvcContrib)
Design Goals:
A view engine based upon NVelocity which is a .NET port of the popular Java project Velocity.
Pros:
Cons:
Example:
#foreach ($p in $viewdata.Model)
#beforeall
<ul>
#each
<li>$p.Name</li>
#afterall
</ul>
#nodata
<p>No products available</p>
#end
Design Goals:
SharpTiles is a partial port of JSTL combined with concept behind the Tiles framework (as of Mile stone 1).
Pros:
Cons:
Example:
<c:if test="${not fn:empty(Page.Tiles)}">
<p class="note">
<fmt:message key="page.tilesSupport"/>
</p>
</c:if>
Design Goals:
The idea is to allow the html to dominate the flow and the code to fit seamlessly.
Pros:
Cons:
Example:
<viewdata products="IEnumerable[[Product]]"/>
<ul if="products.Any()">
<li each="var p in products">${p.Name}</li>
</ul>
<else>
<p>No products available</p>
</else>
<Form style="background-color:olive;">
<Label For="username" />
<TextBox For="username" />
<ValidationMessage For="username" Message="Please type a valid username." />
</Form>
StringTemplate View Engine MVC
Design Goals:
- Lightweight. No page classes are created.
- Fast. Templates are written to the Response Output stream.
- Cached. Templates are cached, but utilize a FileSystemWatcher to detect file changes.
- Dynamic. Templates can be generated on the fly in code.
- Flexible. Templates can be nested to any level.
- In line with MVC principles. Promotes separation of UI and Business Logic. All data is created ahead of time, and passed down to the template.
Pros:
Cons:
Wing Beats is an internal DSL for creating XHTML. It is based on F# and includes an ASP.NET MVC view engine, but can also be used solely for its capability of creating XHTML.
Pros:
Cons:
Design Goals:
Builds views from familiar XSLT
Pros:
Cons:
I'd suggest installing something like GNU Utilities for Win32. It has most favourites, including tail.
Example
To see the entire process in context, here is a supplemental answer. See my fuller answer for more explanation.
MainActivity.java
public class MainActivity extends AppCompatActivity {
// Add a different request code for every activity you are starting from here
private static final int SECOND_ACTIVITY_REQUEST_CODE = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
// "Go to Second Activity" button click
public void onButtonClick(View view) {
// Start the SecondActivity
Intent intent = new Intent(this, SecondActivity.class);
startActivityForResult(intent, SECOND_ACTIVITY_REQUEST_CODE);
}
// This method is called when the second activity finishes
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// check that it is the SecondActivity with an OK result
if (requestCode == SECOND_ACTIVITY_REQUEST_CODE) {
if (resultCode == RESULT_OK) { // Activity.RESULT_OK
// get String data from Intent
String returnString = data.getStringExtra("keyName");
// set text view with string
TextView textView = (TextView) findViewById(R.id.textView);
textView.setText(returnString);
}
}
}
}
SecondActivity.java
public class SecondActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
}
// "Send text back" button click
public void onButtonClick(View view) {
// get the text from the EditText
EditText editText = (EditText) findViewById(R.id.editText);
String stringToPassBack = editText.getText().toString();
// put the String to pass back into an Intent and close this activity
Intent intent = new Intent();
intent.putExtra("keyName", stringToPassBack);
setResult(RESULT_OK, intent);
finish();
}
}
Use C++ streams and restore state afterwards
This is a variation of How do I print bytes as hexadecimal? but:
main.cpp
#include <iomanip>
#include <iostream>
int main() {
int array[] = {0, 0x8, 0x10, 0x18};
constexpr size_t size = sizeof(array) / sizeof(array[0]);
// Sanity check decimal print.
for (size_t i = 0; i < size; ++i)
std::cout << array[i] << " ";
std::cout << std::endl;
// Hex print and restore default afterwards.
std::ios cout_state(nullptr);
cout_state.copyfmt(std::cout);
std::cout << std::hex << std::setfill('0') << std::setw(2);
for (size_t i = 0; i < size; ++i)
std::cout << array[i] << " ";
std::cout << std::endl;
std::cout.copyfmt(cout_state);
// Check that cout state was restored.
for (size_t i = 0; i < size; ++i)
std::cout << array[i] << " ";
std::cout << std::endl;
}
Compile and run:
g++ -o main.out -std=c++11 main.cpp
./main.out
Output:
0 8 16 24
00 8 10 18
0 8 16 24
Tested on Ubuntu 16.04, GCC 6.4.0.
byte b = (byte)0xC8;
int v1 = b; // v1 is -56 (0xFFFFFFC8)
int v2 = b & 0xFF // v2 is 200 (0x000000C8)
Most of the time v2 is the way you really need.
background-image: url(/images/poster.png);
background-position: center;
background-position-y: 50px;
background-repeat: no-repeat;
Your select statement is returning a sequence of anonymous type , not a sequence of DataRows. CopyToDataTable() is only available on IEnumerable<T>
where T
is or derives from DataRow
. You can select r
the row object to call CopyToDataTable on it.
var query = from r in matrix.AsEnumerable()
where r.Field<string>("c_to") == c_to &&
r.Field<string>("p_to") == p_to
select r;
DataTable conversions = query.CopyToDataTable();
You can also implement CopyToDataTable Where the Generic Type T Is Not a DataRow.
There seems no way to have google maps api key free without credit card. To test the functionality of google map you can use it while leaving the api key field "EMPTY". It will show a message saying "For Development Purpose Only". And that way you can test google map functionality without putting billing information for google map api key.
<script src="https://maps.googleapis.com/maps/api/js?key=&callback=initMap" async defer></script>
I had an issue with connected repository. What's how I fixed:
I deleted manually .git folder under my project folder, run git init and then it all worked.
Update: With PostgreSQL 9.5, there are some jsonb
manipulation functionality within PostgreSQL itself (but none for json
; casts are required to manipulate json
values).
Merging 2 (or more) JSON objects (or concatenating arrays):
SELECT jsonb '{"a":1}' || jsonb '{"b":2}', -- will yield jsonb '{"a":1,"b":2}'
jsonb '["a",1]' || jsonb '["b",2]' -- will yield jsonb '["a",1,"b",2]'
So, setting a simple key can be done using:
SELECT jsonb '{"a":1}' || jsonb_build_object('<key>', '<value>')
Where <key>
should be string, and <value>
can be whatever type to_jsonb()
accepts.
For setting a value deep in a JSON hierarchy, the jsonb_set()
function can be used:
SELECT jsonb_set('{"a":[null,{"b":[]}]}', '{a,1,b,0}', jsonb '{"c":3}')
-- will yield jsonb '{"a":[null,{"b":[{"c":3}]}]}'
Full parameter list of jsonb_set()
:
jsonb_set(target jsonb,
path text[],
new_value jsonb,
create_missing boolean default true)
path
can contain JSON array indexes too & negative integers that appear there count from the end of JSON arrays. However, a non-existing, but positive JSON array index will append the element to the end of the array:
SELECT jsonb_set('{"a":[null,{"b":[1,2]}]}', '{a,1,b,1000}', jsonb '3', true)
-- will yield jsonb '{"a":[null,{"b":[1,2,3]}]}'
For inserting into JSON array (while preserving all of the original values), the jsonb_insert()
function can be used (in 9.6+; this function only, in this section):
SELECT jsonb_insert('{"a":[null,{"b":[1]}]}', '{a,1,b,0}', jsonb '2')
-- will yield jsonb '{"a":[null,{"b":[2,1]}]}', and
SELECT jsonb_insert('{"a":[null,{"b":[1]}]}', '{a,1,b,0}', jsonb '2', true)
-- will yield jsonb '{"a":[null,{"b":[1,2]}]}'
Full parameter list of jsonb_insert()
:
jsonb_insert(target jsonb,
path text[],
new_value jsonb,
insert_after boolean default false)
Again, negative integers that appear in path
count from the end of JSON arrays.
So, f.ex. appending to an end of a JSON array can be done with:
SELECT jsonb_insert('{"a":[null,{"b":[1,2]}]}', '{a,1,b,-1}', jsonb '3', true)
-- will yield jsonb '{"a":[null,{"b":[1,2,3]}]}', and
However, this function is working slightly differently (than jsonb_set()
) when the path
in target
is a JSON object's key. In that case, it will only add a new key-value pair for the JSON object when the key is not used. If it's used, it will raise an error:
SELECT jsonb_insert('{"a":[null,{"b":[1]}]}', '{a,1,c}', jsonb '[2]')
-- will yield jsonb '{"a":[null,{"b":[1],"c":[2]}]}', but
SELECT jsonb_insert('{"a":[null,{"b":[1]}]}', '{a,1,b}', jsonb '[2]')
-- will raise SQLSTATE 22023 (invalid_parameter_value): cannot replace existing key
Deleting a key (or an index) from a JSON object (or, from an array) can be done with the -
operator:
SELECT jsonb '{"a":1,"b":2}' - 'a', -- will yield jsonb '{"b":2}'
jsonb '["a",1,"b",2]' - 1 -- will yield jsonb '["a","b",2]'
Deleting, from deep in a JSON hierarchy can be done with the #-
operator:
SELECT '{"a":[null,{"b":[3.14]}]}' #- '{a,1,b,0}'
-- will yield jsonb '{"a":[null,{"b":[]}]}'
For 9.4, you can use a modified version of the original answer (below), but instead of aggregating a JSON string, you can aggregate into a json object directly with json_object_agg()
.
Original answer: It is possible (without plpython or plv8) in pure SQL too (but needs 9.3+, will not work with 9.2)
CREATE OR REPLACE FUNCTION "json_object_set_key"(
"json" json,
"key_to_set" TEXT,
"value_to_set" anyelement
)
RETURNS json
LANGUAGE sql
IMMUTABLE
STRICT
AS $function$
SELECT concat('{', string_agg(to_json("key") || ':' || "value", ','), '}')::json
FROM (SELECT *
FROM json_each("json")
WHERE "key" <> "key_to_set"
UNION ALL
SELECT "key_to_set", to_json("value_to_set")) AS "fields"
$function$;
Edit:
A version, which sets multiple keys & values:
CREATE OR REPLACE FUNCTION "json_object_set_keys"(
"json" json,
"keys_to_set" TEXT[],
"values_to_set" anyarray
)
RETURNS json
LANGUAGE sql
IMMUTABLE
STRICT
AS $function$
SELECT concat('{', string_agg(to_json("key") || ':' || "value", ','), '}')::json
FROM (SELECT *
FROM json_each("json")
WHERE "key" <> ALL ("keys_to_set")
UNION ALL
SELECT DISTINCT ON ("keys_to_set"["index"])
"keys_to_set"["index"],
CASE
WHEN "values_to_set"["index"] IS NULL THEN 'null'::json
ELSE to_json("values_to_set"["index"])
END
FROM generate_subscripts("keys_to_set", 1) AS "keys"("index")
JOIN generate_subscripts("values_to_set", 1) AS "values"("index")
USING ("index")) AS "fields"
$function$;
Edit 2: as @ErwinBrandstetter noted these functions above works like a so-called UPSERT
(updates a field if it exists, inserts if it does not exist). Here is a variant, which only UPDATE
:
CREATE OR REPLACE FUNCTION "json_object_update_key"(
"json" json,
"key_to_set" TEXT,
"value_to_set" anyelement
)
RETURNS json
LANGUAGE sql
IMMUTABLE
STRICT
AS $function$
SELECT CASE
WHEN ("json" -> "key_to_set") IS NULL THEN "json"
ELSE (SELECT concat('{', string_agg(to_json("key") || ':' || "value", ','), '}')
FROM (SELECT *
FROM json_each("json")
WHERE "key" <> "key_to_set"
UNION ALL
SELECT "key_to_set", to_json("value_to_set")) AS "fields")::json
END
$function$;
Edit 3: Here is recursive variant, which can set (UPSERT
) a leaf value (and uses the first function from this answer), located at a key-path (where keys can only refer to inner objects, inner arrays not supported):
CREATE OR REPLACE FUNCTION "json_object_set_path"(
"json" json,
"key_path" TEXT[],
"value_to_set" anyelement
)
RETURNS json
LANGUAGE sql
IMMUTABLE
STRICT
AS $function$
SELECT CASE COALESCE(array_length("key_path", 1), 0)
WHEN 0 THEN to_json("value_to_set")
WHEN 1 THEN "json_object_set_key"("json", "key_path"[l], "value_to_set")
ELSE "json_object_set_key"(
"json",
"key_path"[l],
"json_object_set_path"(
COALESCE(NULLIF(("json" -> "key_path"[l])::text, 'null'), '{}')::json,
"key_path"[l+1:u],
"value_to_set"
)
)
END
FROM array_lower("key_path", 1) l,
array_upper("key_path", 1) u
$function$;
Updated: Added function for replacing an existing json field's key by another given key. Can be in handy for updating data types in migrations or other scenarios like data structure amending.
CREATE OR REPLACE FUNCTION json_object_replace_key(
json_value json,
existing_key text,
desired_key text)
RETURNS json AS
$BODY$
SELECT COALESCE(
(
SELECT ('{' || string_agg(to_json(key) || ':' || value, ',') || '}')
FROM (
SELECT *
FROM json_each(json_value)
WHERE key <> existing_key
UNION ALL
SELECT desired_key, json_value -> existing_key
) AS "fields"
-- WHERE value IS NOT NULL (Actually not required as the string_agg with value's being null will "discard" that entry)
),
'{}'
)::json
$BODY$
LANGUAGE sql IMMUTABLE STRICT
COST 100;
Update: functions are compacted now.
this is how i did it:
String[] listAges = getResources().getStringArray(R.array.ages);
// Creating adapter for spinner
ArrayAdapter<String> dataAdapter =
new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, listAges);
// Drop down layout style - list view with radio button
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
spinner_age.getBackground().setColorFilter(ContextCompat.getColor(this, R.color.spinner_icon), PorterDuff.Mode.SRC_ATOP);
spinner_age.setAdapter(dataAdapter);
spinner_age.setSelection(0);
spinner_age.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String item = parent.getItemAtPosition(position).toString();
if(position > 0){
// get spinner value
Toast.makeText(parent.getContext(), "Age..." + item, Toast.LENGTH_SHORT).show();
}else{
// show toast select gender
Toast.makeText(parent.getContext(), "none" + item, Toast.LENGTH_SHORT).show();
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
There are two solutions to this:
a) Set your PATH variable to include "/usr/local/bin"
export PATH="$PATH:/usr/local/bin"
b) Create a symlink to "/usr/bin" which is already in your PATH
ln -s /usr/bin/nodejs /usr/bin/node
I hope it helps.
If you are using com.google.android.gms:play-services-maps:16.0.0
or below and your app is targeting API level 28 (Android 9.0) or above, you must include the following declaration within the element of AndroidManifest.xml
<uses-library
android:name="org.apache.http.legacy"
android:required="false" />
Check this link - https://developers.google.com/maps/documentation/android-sdk/config#specify_requirement_for_apache_http_legacy_library
use property UseSimpleDictionaryFormat
on DataContractJsonSerializer
and set it to true
.
Does the job :)
Use matplotlib
's calls that won't block:
Using draw()
:
from matplotlib.pyplot import plot, draw, show
plot([1,2,3])
draw()
print('continue computation')
# at the end call show to ensure window won't close.
show()
Using interactive mode:
from matplotlib.pyplot import plot, ion, show
ion() # enables interactive mode
plot([1,2,3]) # result shows immediatelly (implicit draw())
print('continue computation')
# at the end call show to ensure window won't close.
show()
This wikipedia article provides the formulae and an example. The text is in german, but the calculations speak for themselves.
So it would become:
List<Integer> myCoords = new ArrayList<Integer>();
myCoords.add(10);
myCoords.add(20);
myCoords.add(30);
myCoords.add(40);
myCoords.add(50);
while(true)
Iterator<Integer> myListIterator = myCoords.iterator();
while (myListIterator.hasNext()) {
Integer coord = myListIterator.next();
System.out.print("\r" + coord);
try{
Thread.sleep(2000);
}catch(Exception e){
// handle the exception...
}
}
}
I think you are looking for ToText(CCur(@Price}/{ValuationReport.YestPrice}*100-100))
You can use CCur
to convert numbers or string to Curency formats. CCur(number)
or CCur(string)
I think this may be what you are looking for,
Replace (ToText(CCur({field})),"$" , "")
that will give the parentheses for negative numbers
It is a little hacky, but I'm not sure CR is very kind in the ways of formatting
Here you go. I found it somewhere on the internet. Works well for me.
/// <summary>
/// Encrypts a given password and returns the encrypted data
/// as a base64 string.
/// </summary>
/// <param name="plainText">An unencrypted string that needs
/// to be secured.</param>
/// <returns>A base64 encoded string that represents the encrypted
/// binary data.
/// </returns>
/// <remarks>This solution is not really secure as we are
/// keeping strings in memory. If runtime protection is essential,
/// <see cref="SecureString"/> should be used.</remarks>
/// <exception cref="ArgumentNullException">If <paramref name="plainText"/>
/// is a null reference.</exception>
public string Encrypt(string plainText)
{
if (plainText == null) throw new ArgumentNullException("plainText");
//encrypt data
var data = Encoding.Unicode.GetBytes(plainText);
byte[] encrypted = ProtectedData.Protect(data, null, Scope);
//return as base64 string
return Convert.ToBase64String(encrypted);
}
/// <summary>
/// Decrypts a given string.
/// </summary>
/// <param name="cipher">A base64 encoded string that was created
/// through the <see cref="Encrypt(string)"/> or
/// <see cref="Encrypt(SecureString)"/> extension methods.</param>
/// <returns>The decrypted string.</returns>
/// <remarks>Keep in mind that the decrypted string remains in memory
/// and makes your application vulnerable per se. If runtime protection
/// is essential, <see cref="SecureString"/> should be used.</remarks>
/// <exception cref="ArgumentNullException">If <paramref name="cipher"/>
/// is a null reference.</exception>
public string Decrypt(string cipher)
{
if (cipher == null) throw new ArgumentNullException("cipher");
//parse base64 string
byte[] data = Convert.FromBase64String(cipher);
//decrypt data
byte[] decrypted = ProtectedData.Unprotect(data, null, Scope);
return Encoding.Unicode.GetString(decrypted);
}
You can make use of apache's commons lang DateUtils helper utility class.
Date newDate = DateUtils.addMonths(new Date(), 1);
You can download commons lang jar at http://commons.apache.org/proper/commons-lang/
Winston is a pretty good logging library. You can write logs out to a file using it.
Code would look something like:
var winston = require('winston');
var logger = new (winston.Logger)({
transports: [
new (winston.transports.Console)({ json: false, timestamp: true }),
new winston.transports.File({ filename: __dirname + '/debug.log', json: false })
],
exceptionHandlers: [
new (winston.transports.Console)({ json: false, timestamp: true }),
new winston.transports.File({ filename: __dirname + '/exceptions.log', json: false })
],
exitOnError: false
});
module.exports = logger;
You can then use this like:
var logger = require('./log');
logger.info('log to file');
In my case, I added a new service (file) to my app. That new service is injected in an existing controller. I did not miss new service dependency injection into that existing controller and did not declare my app module no more than one place. The same exception is thrown when I re-run my web app and my browser cache is not reset with a new service file codes. I simply refreshed my browser to get that new service file for browser cache, and the problem was gone.
In my case, the site was fine in server but not in local. Then I remember I was working on secure website.
So in file config.session.php, set the variable secure to false
'secure' => env('SESSION_SECURE_COOKIE', false),
I realised there aren't any good solutions utilizing the CLI dotnet
command so here's one:
dotnet ef migrations list
dotnet ef database update NameOfYourMigration
In the place of NameOfYourMigration
enter the name of the migration you want to revert to.
To execute SomeClass.main(String [] args) from a deployed war file do:
Step 1: Write class SomeClass.java that has a main method method i.e. (public static void main(String[] args) {...})
Step 2: Deploy your WAR
Step 3: cd /usr/local/yourprojectsname/tomcat/webapps/projectName/WEB-INF
Step 4: java -cp "lib/jar1.jar:lib/jar2.jar: ... :lib/jarn.jar" com.mypackage.SomeClass arg1 arg2 ... arg3
Note1: (to see if the class SomeOtherClass.class is in /usr/tomcat/webapps/projectName/WEB-INF/lib)
run --> cd /usr/tomcat/webapps/projectName/WEB-INF/lib && find . -name '*.jar' | while read jarfile; do if jar tf "$jarfile" | grep SomeOtherClass.class; then echo "$jarfile"; fi; done
Note2: Write to standard out so you can see if your main actually works via print statements to the console. This is called a back door.
Note3: The comment above by Bozhidar Bozhanov seems correct
Thank you for all the input made so far. I just wanna add on that while one may have successfully normalized DB, updated any schema changes to their application (e.g. to dataset) or so, there is also another cause: sql CARTESIAN product (when joining tables in queries).
The existence of a cartesian query result will cause duplicate records in the primary (or key first) table of two or more tables being joined. Even if you specify a "Where" clause in the SQL, a Cartesian may still occur if JOIN with secondary table for example contains the unequal join (useful when to get data from 2 or more UNrelated tables):
FROM tbFirst INNER JOIN tbSystem ON tbFirst.reference_str <> tbSystem.systemKey_str
Solution for this: tables should be related.
Thanks. chagbert
Borrowed from @Deena above, that function modification for labels is more versatile than you might have thought. For example, I had a ggplot where the denominator of counted variables was 140. I used her example thus:
scale_y_continuous(labels = function(x) paste0(round(x/140*100,1), "%"), breaks = seq(0, 140, 35))
This allowed me to get my percentages on the 140 denominator, and then break the scale at 25% increments rather than the weird numbers it defaulted to. The key here is that the scale breaks are still set by the original count, not by your percentages. Therefore the breaks must be from zero to the denominator value, with the third argument in "breaks" being the denominator divided by however many label breaks you want (e.g. 140 * 0.25 = 35).
A little late reply, but what I found in Notepad++ v7.8.6 is, on RMB (Right Mouse Button), on selection text, it gives an option called "Style token" where it shows "Using 1st/2nd/3rd/4th/5th style" to highlight the selected text in different pre-defined colors
ngOnInit()
is called after ngOnChanges()
was called the first time. ngOnChanges()
is called every time inputs are updated by change detection.
ngAfterViewInit()
is called after the view is initially rendered. This is why @ViewChild()
depends on it. You can't access view members before they are rendered.
when we call ASCII as 7 bit code, the left most bit is used as sign bit so with 7 bits we can write up to 127. that means from -126 to 127 because Max imam value of ASCII is 0 to 255. this can be only satisfied with the argument of 7 bit if last bit is considered as sign bit
Brute is your best bet!
Here is a script that helped me out:
https://code.google.com/p/android-keystore-password-recover/wiki/HowTo
You can optionally give it a list of words the password might include for a very fast recover (for me it worked in <1 sec)
If you're going to run a little console app, you may as well install clrver.exe
from the .NET SDK. I don't think you can get cleaner than that. This isn't my answer (but I happen to agree), I found it here.
In my case the problem occurred due to closing my PC while visual studio were remain open, so in result csproj.user file saved empty. Thankfully i have already backup, so i just copied all xml from csproj.user and paste in my affected project csproj.user file ,so it worked perfectly.
This file just contain building device info and some more.
I usually use Criteria when I don't know what the inputs will be used on which pieces of data. Like on a search form where the user can enter any of 1 to 50 items and I don't know what they will be searching for. It is very easy to just append more to the criteria as I go through checking for what the user is searching for. I think it would be a little more troublesome to put an HQL query in that circumstance. HQL is great though when I know exactly what I want.
I know the question is asking about your "csv" package implementation, but for your information, there are options that are much simpler — numpy, for instance.
import numpy as np
np.savetxt('data.csv', (col1_array, col2_array, col3_array), delimiter=',')
(This answer posted 6 years later, for posterity's sake.)
In a different case similar to what you're asking about, say you have two columns like this:
names = ['Player Name', 'Foo', 'Bar']
scores = ['Score', 250, 500]
You could save it like this:
np.savetxt('scores.csv', [p for p in zip(names, scores)], delimiter=',', fmt='%s')
scores.csv
would look like this:
Player Name,Score
Foo,250
Bar,500
As NT3RP told us that:
... we (Yahoo!) don't have a Finance API. It appears some have reverse engineered an API that they use to pull Finance data, but they are breaking our Terms of Service...
So I just thought of sharing this site with you:
http://josscrowcroft.github.com/open-exchange-rates/
[update: site has moved to - http://openexchangerates.org]
This site says:
No access fees, no rate limits, no ugly XML - just free, hourly updated exchange rates in JSON format
[update: Free for personal use, a bargain for your business.]
I hope I've helped and this is of some use to you (and others too). : )
It is just this:
if 'errormessage' in kwargs:
print("yeah it's here")
You need to check, if the key is in the dictionary. The syntax for that is some_key in some_dict
(where some_key
is something hashable, not necessarily a string).
The ideas you have linked (these ideas) contained examples for checking if specific key existed in dictionaries returned by locals()
and globals()
. Your example is similar, because you are checking existence of specific key in kwargs
dictionary (the dictionary containing keyword arguments).
Why just don't do like this?:
if ($res) {
$converted_res = "true";
}
else {
$converted_res = "false";
}
I like Jon Skeet's answer, but would like to add one thing. I'm not sure if Jon was expecting the ctor to always be passed in the Local timezone. But I want to use it for cases where it's something other then local.
I'm reading values from a database, and I know what timezone that database is in. So in the ctor, I'll pass in the timezone of the database. But then I would like the value in local time. Jon's LocalTime does not return the original date converted into a local timezone date. It returns the date converted into the original timezone (whatever you had passed into the ctor).
I think these property names clear it up...
public DateTime TimeInOriginalZone { get { return TimeZoneInfo.ConvertTime(utcDateTime, timeZone); } }
public DateTime TimeInLocalZone { get { return TimeZoneInfo.ConvertTime(utcDateTime, TimeZoneInfo.Local); } }
public DateTime TimeInSpecificZone(TimeZoneInfo tz)
{
return TimeZoneInfo.ConvertTime(utcDateTime, tz);
}
For both *printf
and *scanf
, %s
expects the corresponding argument to be of type char *
, and for scanf
, it had better point to a writable buffer (i.e., not a string literal).
char *str_constant = "I point to a string literal";
char str_buf[] = "I am an array of char initialized with a string literal";
printf("string literal = %s\n", "I am a string literal");
printf("str_constant = %s\n", str_constant);
printf("str_buf = %s\n", str_buf);
scanf("%55s", str_buf);
Using %s
in scanf
without an explcit field width opens the same buffer overflow exploit that gets
did; namely, if there are more characters in the input stream than the target buffer is sized to hold, scanf
will happily write those extra characters to memory outside the buffer, potentially clobbering something important. Unfortunately, unlike in printf
, you can't supply the field with as a run time argument:
printf("%*s\n", field_width, string);
One option is to build the format string dynamically:
char fmt[10];
sprintf(fmt, "%%%lus", (unsigned long) (sizeof str_buf) - 1);
...
scanf(fmt, target_buffer); // fmt = "%55s"
EDIT
Using scanf
with the %s
conversion specifier will stop scanning at the first whitespace character; for example, if your input stream looks like
"This is a test"
then scanf("%55s", str_buf)
will read and assign "This"
to str_buf
. Note that the field with specifier doesn't make a difference in this case.
If you just want to run your node app in the terminal always, just use screen.
Install on ubuntu/ debian:
sudo apt-get install screen
Usage:
$ screen
$ node /path/to/app.js
ctrl + a
and then ctrl + d
to dismiss
To get is back:
One screen: screen -r
If there's more than one you can list all the screens with: screen -ls
And then: screen -r pid_number
Although <input>
ignores the rows
attribute, you can take advantage of the fact that <textarea>
doesn't have to be inside <form>
tags, but can still be a part of a form by referencing the form's id:
<form method="get" id="testformid">
<input type="submit" />
</form>
<textarea form ="testformid" name="taname" id="taid" cols="35" wrap="soft"></textarea>
Of course, <textarea>
now appears below "submit" button, but maybe you'll find a way to reposition it.
Clone is broken, so dont use it.
THE CLONE METHOD of the Object class is a somewhat magical method that does what no pure Java method could ever do: It produces an identical copy of its object. It has been present in the primordial Object superclass since the Beta-release days of the Java compiler*; and it, like all ancient magic, requires the appropriate incantation to prevent the spell from unexpectedly backfiring
Prefer a method that copies the object
Foo copyFoo (Foo foo){
Foo f = new Foo();
//for all properties in FOo
f.set(foo.get());
return f;
}
Read more http://adtmag.com/articles/2000/01/18/effective-javaeffective-cloning.aspx
Oracle (database) can use many ports. when you install the software it scans for free ports and decides which port to use then.
The database listener defaults to 1520 but will use 1521 or 1522 if 1520 is not available. This can be adjusted in the listener.ora files.
The Enterprise Manager, web-based database administration tool defaults to port 80 but will use 8080 if 80 is not available.
See here for details on how to change the port number for enterprise manager: http://download-uk.oracle.com/docs/cd/B14099_19/integrate.1012/b19370/manage_oem.htm#i1012853
Returns a QuerySet that returns dictionaries
, rather than model instances, when used as an iterable.
Returns a QuerySet that returns list of tuples
, rather than model instances, when used as an iterable.
distinct are used to eliminate the duplicate
elements.
Example:
>>> list(Article.objects.values_list('id', flat=True)) # flat=True will remove the tuples and return the list
[1, 2, 3, 4, 5, 6]
>>> list(Article.objects.values('id'))
[{'id':1}, {'id':2}, {'id':3}, {'id':4}, {'id':5}, {'id':6}]
Scanner.next()
does not read a newline but reads the next token, delimited by whitespace (by default, if useDelimiter()
was not used to change the delimiter pattern). To read a line use Scanner.nextLine()
.
Once you read a single line you can use String.split(",")
to separate the line into fields. This enables identification of lines that do not consist of the required number of fields. Using useDelimiter(",");
would ignore the line-based structure of the file (each line consists of a list of fields separated by a comma). For example:
while (inputStream.hasNextLine())
{
String line = inputStream.nextLine();
String[] fields = line.split(",");
if (fields.length >= 4) // At least one address specified.
{
for (String field: fields) System.out.print(field + "|");
System.out.println();
}
else
{
System.err.println("Invalid record: " + line);
}
}
As already mentioned, using a CSV library is recommended. For one, this (and useDelimiter(",")
solution) will not correctly handle quoted identifiers containing ,
characters.
If by configure release/build, you mean you only need one config per makefile, then it is simply a matter and decoupling CC and CFLAGS:
CFLAGS=-DDEBUG
#CFLAGS=-O2 -DNDEBUG
CC=g++ -g3 -gdwarf2 $(CFLAGS)
Depending on whether you can use gnu makefile, you can use conditional to make this a bit fancier, and control it from the command line:
DEBUG ?= 1
ifeq ($(DEBUG), 1)
CFLAGS =-DDEBUG
else
CFLAGS=-DNDEBUG
endif
.o: .c
$(CC) -c $< -o $@ $(CFLAGS)
and then use:
make DEBUG=0
make DEBUG=1
If you need to control both configurations at the same time, I think it is better to have build directories, and one build directory / config.
You can do this with .htaccess:
php_value upload_max_filesize 20M
php_value post_max_size 20M
try this
select * from <tablename> where 1=2
...............................................
To add to @migontech's answer and also his address his comment that you could "probably make it more generic", here's a way to do it. The below will allow you to search by any property:
.filter('getByProperty', function() {
return function(propertyName, propertyValue, collection) {
var i=0, len=collection.length;
for (; i<len; i++) {
if (collection[i][propertyName] == +propertyValue) {
return collection[i];
}
}
return null;
}
});
The call to filter would then become:
var found = $filter('getByProperty')('id', fish_id, $scope.fish);
Note, I removed the unary(+) operator to allow for string-based matches...
Login using the system maintenance user and password created when you installed phpMyAdmin.
It can be found in the debian.cnf file at /etc/mysql then you will have total access.
cd /etc/mysql
sudo nano debian.cnf
Just look - don't change anything!
[mysql_upgrade]
host = localhost
user = debian-sys-maint <----use this user
password = s0meRaND0mChar$s <----use this password
socket = /var/run/mysqld/mysqld.sock
Worked for me.
Try :
Configure in web config file
<system.web>
<globalization culture="ja-JP" uiCulture="zh-HK" />
</system.web>
eg: DateTime dt = DateTime.ParseExact("08/21/2013", "MM/dd/yyyy", null);
ref url : http://support.microsoft.com/kb/306162/
You can use dtype=np.int64
instead of dtype=int
$('input[name="testing"]').val(theValue);
The ports required will be different for your XMPP Server and any XMPP Clients. Most "modern" XMPP Servers follow the defined IANA Ports for Server-to-Server 5269 and for Client-to-Server 5222. Any additional ports depends on what features you enable on the Server, i.e. if you offer BOSH then you may need to open port 80.
File Transfer is highly dependent on both the Clients you use and the Server as to what port it will use, but most of them also negotiate the connect via your existing XMPP Client-to-Server link so the required port opening will be client side (or proxied via port 80.)
Subsetting the data and combining them back is unnecessary. So are loops since those operations are vectorized. From your previous edit, I'm guessing you are doing all of this to make bubble plots. If that is correct, perhaps the example below will help you. If this is way off, I can just delete the answer.
library(ggplot2)
# let's look at the included dataset named trees.
# ?trees for a description
data(trees)
ggplot(trees,aes(Height,Volume)) + geom_point(aes(size=Girth))
# Great, now how do we color the bubbles by groups?
# For this example, I'll divide Volume into three groups: lo, med, high
trees$set[trees$Volume<=22.7]="lo"
trees$set[trees$Volume>22.7 & trees$Volume<=45.4]="med"
trees$set[trees$Volume>45.4]="high"
ggplot(trees,aes(Height,Volume,colour=set)) + geom_point(aes(size=Girth))
# Instead of just circles scaled by Girth, let's also change the symbol
ggplot(trees,aes(Height,Volume,colour=set)) + geom_point(aes(size=Girth,pch=set))
# Now let's choose a specific symbol for each set. Full list of symbols at ?pch
trees$symbol[trees$Volume<=22.7]=1
trees$symbol[trees$Volume>22.7 & trees$Volume<=45.4]=2
trees$symbol[trees$Volume>45.4]=3
ggplot(trees,aes(Height,Volume,colour=set)) + geom_point(aes(size=Girth,pch=symbol))
I don't think you can do that easily with the InvokeCommandAction
- I would take a look at EventToCommand
from MVVMLight or similar.
Evaluating "1,2,3" results in (1, 2, 3)
, a tuple
. As you've discovered, tuples are immutable. Convert to a list before processing.
With pure javascript:
var buttons = document.getElementsByTagName("button");
var buttonsCount = buttons.length;
for (var i = 0; i <= buttonsCount; i += 1) {
buttons[i].onclick = function(e) {
alert(this.id);
};
}?
<p class="pull-left">Text left</p>
<p class="text-right">Text right in same line</p>
This work for me.
edit: An example with your snippet:
@import url('https://unpkg.com/[email protected]/dist/css/bootstrap.css');_x000D_
.container {_x000D_
margin-top: 10px;_x000D_
}
_x000D_
<div class="container">_x000D_
<div class="row-fluid">_x000D_
<div class="span6 pull-left">_x000D_
<p>Text left</p>_x000D_
</div>_x000D_
<div class="span6 text-right">_x000D_
<p>text right</p>_x000D_
</div>_x000D_
</div>_x000D_
</div>
_x000D_
If you want to return more than 1 value use this:
DECLARE @sqlstatement2 NVARCHAR(MAX);
DECLARE @retText NVARCHAR(MAX);
DECLARE @ParmDefinition NVARCHAR(MAX);
DECLARE @retIndex INT = 0;
SELECT @sqlstatement = 'SELECT @retIndexOUT=column1 @retTextOUT=column2 FROM XXX WHERE bla bla';
SET @ParmDefinition = N'@retIndexOUT INT OUTPUT, @retTextOUT NVARCHAR(MAX) OUTPUT';
exec sp_executesql @sqlstatement, @ParmDefinition, @retIndexOUT=@retIndex OUTPUT, @retTextOUT=@retText OUTPUT;
returned values are in @retIndex and @retText
The best option would be to set a class style in CSS like .showMenu
and .hideMenu
with the various styles inside. Then you can do something like
$("#user_button").addClass("showMenu");
I am not sure about the XML but you can do it by code in the following way.
ImageView myImageView = new ImageView(this);
myImageView.setAlpha(xxx);
In pre-API 11:
In API 11+:
IN opencv3.x SIFT() & SURF() are no longer exist .for this
uninstall all the opencv versions
python -m pip uninstall opencv-python
python -m pip uninstall opencv-contrib-python
after that install opencv-contrib to include sift() and surf() using below given command with python(3.x)
python -m pip install opencv-contrib-python==3.4.2.16
then you can use
sift = cv2.xfeatures2d.SIFT_create()
I hope this example will be helpful for you)
print(type(None)) # NoneType
So, you can check type of the variable name
# Example
name = 12 # name = None
if type(name) is type(None):
print("Can't find name")
else:
print(name)