This happens when the pointer passed to free() is not valid or has been modified somehow. I don't really know the details here. The bottom line is that the pointer passed to free() must be the same as returned by malloc(), realloc() and their friends. It's not always easy to spot what the problem is for a novice in their own code or even deeper in a library. In my case, it was a simple case of an undefined (uninitialized) pointer related to branching.
The free() function frees the memory space pointed to by ptr, which must have been returned by a previous call to malloc(), calloc() or realloc(). Otherwise, or if free(ptr) has already been called before, undefined behavior occurs. If ptr is NULL, no operation is performed. GNU 2012-05-10 MALLOC(3)
char *words; // setting this to NULL would have prevented the issue
if (condition) {
words = malloc( 512 );
/* calling free sometime later works here */
free(words)
} else {
/* do not allocate words in this branch */
}
/* free(words); -- error here --
*** glibc detected *** ./bin: munmap_chunk(): invalid pointer: 0xb________ ***/
There are many similar questions here about the related free() and rellocate() functions. Some notable answers providing more details:
*** glibc detected *** free(): invalid next size (normal): 0x0a03c978 ***
*** glibc detected *** sendip: free(): invalid next size (normal): 0x09da25e8 ***
glibc detected, realloc(): invalid pointer
IMHO running everything in a debugger (Valgrind) is not the best option because errors like this are often caused by inept or novice programmers. It's more productive to figure out the issue manually and learn how to avoid it in the future.
for OrderedDict() you can access the elements by indexing by getting the tuples of (key,value) pairs as follows or using '.values()'
>>> import collections
>>> d = collections.OrderedDict()
>>> d['foo'] = 'python'
>>> d['bar'] = 'spam'
>>> d.items()
[('foo', 'python'), ('bar', 'spam')]
>>>d.values()
odict_values(['python','spam'])
>>>list(d.values())
['python','spam']
There is a simple way to verify if a service is running
systemctl status service_name
Try PostgreSQL:
systemctl status postgresql
This is the fastest way:
if ($coll->isEmpty()) {...}
Other solutions like count
do a bit more than you need which costs slightly more time.
Plus, the isEmpty()
name quite precisely describes what you want to check there so your code will be more readable.
You have to set to element_blank()
in theme()
elements you need to remove
ggplot(data = diamonds, mapping = aes(x = clarity)) + geom_bar(aes(fill = cut))+
theme(axis.title.x=element_blank(),
axis.text.x=element_blank(),
axis.ticks.x=element_blank())
The Python documentation does explain it.
Tuples and lists are compared lexicographically using comparison of corresponding elements. This means that to compare equal, each element must compare equal and the two sequences must be of the same type and have the same length.
If you are using eclipse to start the server then check for the server location being used and the deployment path:
In my case changing this to Tomcat installation
instead of workspace metadata
worked for me.
Maybe SO_REUSEADDR helps here? http://www.unixguide.net/network/socketfaq/4.5.shtml
Modules go in site-packages
and executables go in your system's executable path. For your environment, this path is /usr/local/bin/
.
To avoid having to deal with this, simply use easy_install
, distribute
or pip
. These tools know which files need to go where.
I had this same problem, common also to other borwsers like Firefox. Finally I discovered that dynamically create an element with animated gif inside at form submit did not animate, so I developed the following workaorund.
1) At document.ready()
, each FORM found in page, receive position:relative
property and then to each one is attached an invisible DIV.bg-overlay
.
2) After this, assuming that each submit value of my website is identified by btn-primary
css class, again at document.ready()
, I look for these buttons, traverse to the FORM parent of each one, and at form submit, I fire showOverlayOnFormExecution(this,true);
function, passing clicked button and a boolean that toggle visibility of DIV.bg-overlay
.
$(document).ready(function() {
//Append LOADING image to all forms
$('form').css('position','relative').append('<div class="bg-overlay" style="display:none;"><img src="/images/loading.gif"></div>');
//At form submit, fires a specific function
$('form .btn-primary').closest('form').submit(function (e) {
showOverlayOnFormExecution(this,true);
});
});
CSS for DIV.bg-overlay
is the following:
.bg-overlay
{
width:100%;
height:100%;
position:absolute;
top:0;
left:0;
background:rgba(255,255,255,0.6);
z-index:100;
}
.bg-overlay img
{
position:absolute;
left:50%;
top:50%;
margin-left:-40px; //my loading images is 80x80 px. This is done to center it horizontally and vertically.
margin-top:-40px;
max-width:auto;
max-height:80px;
}
3) At any form submit, the following function is fired to show a semi-white background overlay all over it (that deny ability to interact again with form) and an animated gif inside it (that visually show a loading action).
function showOverlayOnFormExecution(clicked_button, showOrNot)
{
if(showOrNot == 1)
{
//Add "content" of #bg-overlay_container (copying it) to the confrm that contains clicked button
$(clicked_button).closest('form').find('.bg-overlay').show();
}
else
$('form .bg-overlay').hide();
}
Showing animated gif at form submit, instead of appending it at this event, solves "gif animation freeze" problem of various browsers (as said, I found this problem in IE and Firefox, not in Chrome)
your issue will be resolved by properly defining cascading depedencies or by saving the referenced entities before saving the entity that references. Defining cascading is really tricky to get right because of all the subtle variations in how they are used.
Here is how you can define cascades:
@Entity
public class Userrole implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private long userroleid;
private Timestamp createddate;
private Timestamp deleteddate;
private String isactive;
//bi-directional many-to-one association to Role
@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name="ROLEID")
private Role role;
//bi-directional many-to-one association to User
@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name="USERID")
private User user;
}
In this scenario, every time you save, update, delete, etc Userrole, the assocaited Role and User will also be saved, updated...
Again, if your use case demands that you do not modify User or Role when updating Userrole, then simply save User or Role before modifying Userrole
Additionally, bidirectional relationships have a one-way ownership. In this case, User owns Bloodgroup. Therefore, cascades will only proceed from User -> Bloodgroup. Again, you need to save User into the database (attach it or make it non-transient) in order to associate it with Bloodgroup.
You could also send your testers the apk that is signed with your debug key. You can find that in the bin folder of your project after building in debug mode.
select get_something('NAME', sys.diutil.int_to_bool(1)) from dual;
You can't style buttons as links reliably throughout browsers. I've tried it, but there's always some weird padding, margin or font issues in some browser. Either live with letting the button look like a button, or use onClick and preventDefault on a link.
To request a new password for the postgres user (without showing it in the command):
sudo -u postgres psql -c "\password"
There is another answer here that also fits the authors request: 'compile-time' way to get all property names defined interface
If you use the plugin ts-transformer-keys and an Interface to your class you can get all the keys for the class.
But if you're using Angular or React then in some scenarios there is additional configuration necessary (webpack and typescript) to get it working: https://github.com/kimamula/ts-transformer-keys/issues/4
Here's a more descriptive example with a CodePen snippet attached:
1.js
function fn1() {
document.getElementById("result").innerHTML += "fn1 gets called";
}
2.js
function clickedTheButton() {
fn1();
}
index.html
<html>
<head>
</head>
<body>
<button onclick="clickedTheButton()">Click me</button>
<script type="text/javascript" src="1.js"></script>
<script type="text/javascript" src="2.js"></script>
</body>
</html>
output
Try this CodePen snippet: link .
The thread is old, but maybe someone is still interested. The shortest form I found is further improvement on the example from ?lex and bmargulies. The execution tag will look like:
<execution>
<id>TheNameOfTheRelevantExecution</id>
<phase/>
</execution>
2 points I want to highlight:
After posting found it is already in stackoverflow: In a Maven multi-module project, how can I disable a plugin in one child?
You can change the default namespace:
-> Project
-> XXX Properties...
On Application tab: Default namespace
Other than that:
Ctrl-H
Find: WindowsFormsApplication16
Replace: MyName
I'm using FirebaseListAdapter and couldn't get any of the solutions to work. I ended up doing this. I'm guessing there are more elegant ways but this is a complete and working solution.
Before onCreate:
private int reset;
private int top;
private int index;
Inside of the FirebaseListAdapter:
@Override
public void onDataChanged() {
super.onDataChanged();
// Only do this on first change, when starting
// activity or coming back to it.
if(reset == 0) {
mListView.setSelectionFromTop(index, top);
reset++;
}
}
onStart:
@Override
protected void onStart() {
super.onStart();
if(adapter != null) {
adapter.startListening();
index = 0;
top = 0;
// Get position from SharedPrefs
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
top = sharedPref.getInt("TOP_POSITION", 0);
index = sharedPref.getInt("INDEX_POSITION", 0);
// Set reset to 0 to allow change to last position
reset = 0;
}
}
onStop:
@Override
protected void onStop() {
super.onStop();
if(adapter != null) {
adapter.stopListening();
// Set position
index = mListView.getFirstVisiblePosition();
View v = mListView.getChildAt(0);
top = (v == null) ? 0 : (v.getTop() - mListView.getPaddingTop());
// Save position to SharedPrefs
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
sharedPref.edit().putInt("TOP_POSITION" + "", top).apply();
sharedPref.edit().putInt("INDEX_POSITION" + "", index).apply();
}
}
Since I also had to solve this for FirebaseRecyclerAdapter I'm posting the solution here for that too:
Before onCreate:
private int reset;
private int top;
private int index;
Inside of the FirebaseRecyclerAdapter:
@Override
public void onDataChanged() {
// Only do this on first change, when starting
// activity or coming back to it.
if(reset == 0) {
linearLayoutManager.scrollToPositionWithOffset(index, top);
reset++;
}
}
onStart:
@Override
protected void onStart() {
super.onStart();
if(adapter != null) {
adapter.startListening();
index = 0;
top = 0;
// Get position from SharedPrefs
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
top = sharedPref.getInt("TOP_POSITION", 0);
index = sharedPref.getInt("INDEX_POSITION", 0);
// Set reset to 0 to allow change to last position
reset = 0;
}
}
onStop:
@Override
protected void onStop() {
super.onStop();
if(adapter != null) {
adapter.stopListening();
// Set position
index = linearLayoutManager.findFirstVisibleItemPosition();
View v = linearLayoutManager.getChildAt(0);
top = (v == null) ? 0 : (v.getTop() - linearLayoutManager.getPaddingTop());
// Save position to SharedPrefs
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
sharedPref.edit().putInt("TOP_POSITION" + "", top).apply();
sharedPref.edit().putInt("INDEX_POSITION" + "", index).apply();
}
}
select max( 1 )
into my_if_has_data
from MY_TABLE X
where X.my_field = my_condition
and rownum = 1;
Not iterating through all records.
If MY_TABLE has no data, then my_if_has_data sets to null.
Since MySQL 8.0 you can use regular expression to remove non alphanumeric characters from a string. There is method REGEXP_REPLACE
Here is the code to remove non-alphanumeric characters:
UPDATE {table} SET {column} = REGEXP_REPLACE({column}, '[^0-9a-zA-Z ]', '')
jQuery('#testID2').find('.test2').replaceWith('.test3');
Semantically, you are selecting the element with the ID testID2
, then you are looking for any descendent elements with the class test2
(does not exist) and then you are replacing that element with another element (elements anywhere in the page with the class test3
) that also do not exist.
You need to do this:
jQuery('#testID2').addClass('test3').removeClass('test2');
This selects the element with the ID testID2
, then adds the class test3
to it. Last, it removes the class test2
from that element.
Since [^a-z0-9]
character class contains all that is not alnum, it contains white characters too!
text.replace(/[^a-z0-9]+/gi, " ");
Initializer block is just like any bits of code; it's not "attached" to any field/method preceding it. To assign values to fields, you have to explicitly use the field as the lhs of an assignment statement.
private int lineCount; {
try{
lineCount = LineCounter.countLines(sFileName);
/*^^^^^^^*/
}
catch(IOException ex){
System.out.println (ex.toString());
System.out.println("Could not find file " + sFileName);
}
}
Also, your countLines
can be made simpler:
public static int countLines(String filename) throws IOException {
LineNumberReader reader = new LineNumberReader(new FileReader(filename));
while (reader.readLine() != null) {}
reader.close();
return reader.getLineNumber();
}
Based on my test, it looks like you can getLineNumber()
after close()
.
In repo_a:
git remote add -f b path/to/repo_b.git
git remote update
git diff master remotes/b/master
git remote rm b
With .split
:
var arr = str.split( /(?<=^(?:.{3})+)(?!$)/ ) // [ 'abc', 'def', 'ghi', 'jkl' ]
and .replace
will be:
var replaced = str.replace( /(?<=^(.{3})+)(?!$)/g, ' || ' ) // 'abc || def || ghi || jkl'
/(?!$)/
is to to stop before end/$/
, without is:
var arr = str.split( /(?<=^(?:.{3})+)/ ) // [ 'abc', 'def', 'ghi', 'jkl' ] // I don't know why is not [ 'abc', 'def', 'ghi', 'jkl' , '' ], comment?
var replaced = str.replace( /(?<=^(.{3})+)/g, ' || ') // 'abc || def || ghi || jkl || '
ignoring group /(?:
...)/
is no need in .replace
but in .split
is adding groups to arr:
var arr = str.split( /(?<=^(.{3})+)(?!$)/ ) // [ 'abc', 'abc', 'def', 'abc', 'ghi', 'abc', 'jkl' ]
Your use of @PathParam is incorrect. It does not follow these requirements as documented in the javadoc here. I believe you just want to POST the JSON entity. You can fix this in your resource method to accept JSON entity.
@Path("/hello")
public class Hello {
@POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public JSONObject sayPlainTextHello(JSONObject inputJsonObj) throws Exception {
String input = (String) inputJsonObj.get("input");
String output = "The input you sent is :" + input;
JSONObject outputJsonObj = new JSONObject();
outputJsonObj.put("output", output);
return outputJsonObj;
}
}
And, your client code should look like this:
ClientConfig config = new DefaultClientConfig();
Client client = Client.create(config);
client.addFilter(new LoggingFilter());
WebResource service = client.resource(getBaseURI());
JSONObject inputJsonObj = new JSONObject();
inputJsonObj.put("input", "Value");
System.out.println(service.path("rest").path("hello").accept(MediaType.APPLICATION_JSON).post(JSONObject.class, inputJsonObj));
So I have ElementTree 1.2.6 on my box now, and ran the following code against the XML chunk you posted:
import elementtree.ElementTree as ET
tree = ET.parse("test.xml")
doc = tree.getroot()
thingy = doc.find('timeSeries')
print thingy.attrib
and got the following back:
{'name': 'NWIS Time Series Instantaneous Values'}
It appears to have found the timeSeries element without needing to use numerical indices.
What would be useful now is knowing what you mean when you say "it doesn't work." Since it works for me given the same input, it is unlikely that ElementTree is broken in some obvious way. Update your question with any error messages, backtraces, or anything you can provide to help us help you.
As far as I know it’s usually a placeholder for links that have some JavaScript attached to them. The main point of the link is served by executing the JavaScript code; browsers with JS support then ignore the real link target. If the browser does not support JS, the hash mark essentially turns the link into a no-op. See also unobtrusive JavaScript.
Tools-> Options-> Select no proxy is worked for me
I think you're looking for a method like this:
public static IEnumerable<TResult> CompareSequences<T1, T2, TResult>(IEnumerable<T1> seq1,
IEnumerable<T2> seq2, Func<T1, T2, TResult> comparer)
{
var enum1 = seq1.GetEnumerator();
var enum2 = seq2.GetEnumerator();
while (enum1.MoveNext() && enum2.MoveNext())
{
yield return comparer(enum1.Current, enum2.Current);
}
}
It's untested, but it should do the job nonetheless. Note that what's particularly useful about this method is that it's full generic, i.e. it can take two sequences of arbitrary (and different) types and return objects of any type.
This solution of course assumes that you want to compare the nth item of seq1
with the nth item in seq2
. If you want to do match the elements in the two sequences based on a particular property/comparison, then you'll want to perform some sort of join operation (as suggested by danbruc using Enumerable.Join
. Do let me know if it neither of these approaches is quite what I'm after and maybe I can suggest something else.
Edit:
Here's an example of how you might use the CompareSequences
method with the comparer function you originally posted.
// Prints out to the console all the results returned by the comparer function (CompareTwoClass_ReturnDifferences in this case).
var results = CompareSequences(list1, list2, CompareTwoClass_ReturnDifferences);
int index;
foreach(var element in results)
{
Console.WriteLine("{0:#000} {1}", index++, element.ToString());
}
If you can afford to use the Tag
element of the TabPage
, you can use this extension methods
public static void HideByRemoval(this TabPage tp)
{
TabControl tc = tp.Parent as TabControl;
if (tc != null && tc.TabPages.Contains(tp))
{
// Store TabControl and Index
tp.Tag = new Tuple<TabControl, Int32>(tc, tc.TabPages.IndexOf(tp));
tc.TabPages.Remove(tp);
}
}
public static void ShowByInsertion(this TabPage tp)
{
Tuple<TabControl, Int32> tagObj = tp.Tag as Tuple<TabControl, Int32>;
if (tagObj?.Item1 != null)
{
// Restore TabControl and Index
tagObj.Item1.TabPages.Insert(tagObj.Item2, tp);
}
}
this is not your answer but is for those come here searching solution for another problem. I wanted to get sum of a column of related table conditionally. In my database Deals has many Activities I wanted to get the sum of the "amount_total" from Activities table where activities.deal_id = deal.id and activities.status = paid so i did this.
$query->withCount([
'activity AS paid_sum' => function ($query) {
$query->select(DB::raw("SUM(amount_total) as paidsum"))->where('status', 'paid');
}
]);
it returns
"paid_sum_count" => "320.00"
in Deals attribute.
This it now the sum which i wanted to get not the count.
Although I am very late to this but after seeing some legitimate questions for those who wanted to use INSERT-SELECT
query with GROUP BY
clause, I came up with the work around for this.
Taking further the answer of Marcus Adams and accounting GROUP BY
in it, this is how I would solve the problem by using Subqueries in the FROM Clause
INSERT INTO lee(exp_id, created_by, location, animal, starttime, endtime, entct,
inact, inadur, inadist,
smlct, smldur, smldist,
larct, lardur, lardist,
emptyct, emptydur)
SELECT sb.id, uid, sb.location, sb.animal, sb.starttime, sb.endtime, sb.entct,
sb.inact, sb.inadur, sb.inadist,
sb.smlct, sb.smldur, sb.smldist,
sb.larct, sb.lardur, sb.lardist,
sb.emptyct, sb.emptydur
FROM
(SELECT id, uid, location, animal, starttime, endtime, entct,
inact, inadur, inadist,
smlct, smldur, smldist,
larct, lardur, lardist,
emptyct, emptydur
FROM tmp WHERE uid=x
GROUP BY location) as sb
ON DUPLICATE KEY UPDATE entct=sb.entct, inact=sb.inact, ...
what is about this? \D(\d{5})\D
This will do on:
f 23 23453 234 2344 2534 hallo33333 "50000"
23453, 33333 50000
Well the answer was sitting right in front of me the whole time.
In SQL Server Management Studio 2008 there is a Debug button in the toolbar. Set a break point in a query window to step through.
I dismissed this functionality at the beginning because I didn't think of stepping INTO the stored procedure, which you can do with ease.
SSMS basically does what FinnNK mentioned with the MSDN walkthrough but automatically.
So easy! Thanks for your help FinnNK.
Edit: I should add a step in there to find the stored procedure call with parameters I used SQL Profiler on my database.
If t
is a matrix, you need to use the element-wise multiplication or exponentiation. Note the dot.
x = exp( -t.^2 )
or
x = exp( -t.*t )
OpenSSL command line app does not display any characters when you are entering your password. Just type it then press enter and you will see that it is working.
You can also use openssl pkcs12 -export -inkey mykey.key -in developer_identity.pem -out iphone_dev.p12 -password pass:YourPassword
to pass the password YourPassword
from command line. Please take a look at section Pass Phrase Options in OpenSSL manual for more information.
There's a pretty nice interface for this in processing, which is kind of a pidgin java designed for graphics. It gets used in some image recognition work, such as that link.
Depending on what you need out of it, you might be able to load the video library that's used there in java, or if you're just playing around with it you might be able to get by using processing itself.
Here is my current code, the 2nd line works if I comment the 3rd line, but don't work if I leave it how it is.
var page_title = $(this).val().replace(/[^a-zA-Z0-9\s]/g, '');
page_title = page_title.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
page_title = page_title.replace(/([\s]+)/g, '-');
If I understand correctly, what you want to do is divide by the maximum value in each column. You can do this easily using broadcasting.
Starting with your example array:
import numpy as np
x = np.array([[1000, 10, 0.5],
[ 765, 5, 0.35],
[ 800, 7, 0.09]])
x_normed = x / x.max(axis=0)
print(x_normed)
# [[ 1. 1. 1. ]
# [ 0.765 0.5 0.7 ]
# [ 0.8 0.7 0.18 ]]
x.max(0)
takes the maximum over the 0th dimension (i.e. rows). This gives you a vector of size (ncols,)
containing the maximum value in each column. You can then divide x
by this vector in order to normalize your values such that the maximum value in each column will be scaled to 1.
If x
contains negative values you would need to subtract the minimum first:
x_normed = (x - x.min(0)) / x.ptp(0)
Here, x.ptp(0)
returns the "peak-to-peak" (i.e. the range, max - min) along axis 0. This normalization also guarantees that the minimum value in each column will be 0.
I had similar expirience like yours. I have Denwer server. When I loaded my http://new.new local site without using via script src jquery.min.js file at index.php in Chrome I got error 500 jquery.min.map in console. I resolved this problem simply - I disabled extension Wunderlist in Chrome and voila - I never see this error more. Although, No, I found this error again - when Wunderlist have been on again. So, check your extensions and try to disable all of them or some of them or one by one. Good luck!
You can't initialize arrays like this:
int cipher[Array_size][Array_size]=0;
The syntax for 2D arrays is:
int cipher[Array_size][Array_size]={{0}};
Note the curly braces on the right hand side of the initialization statement.
for 1D arrays:
int tomultiply[Array_size]={0};
It's a separate statement.
It's also not possible to insert into a table and select from it and build an index in the same statement either.
The BOL entry contains the information you need:
CLUSTERED | NONCLUSTERED
Indicate that a clustered or a nonclustered index is created for the PRIMARY KEY or UNIQUE constraint. PRIMARY KEY constraints default to CLUSTERED, and UNIQUE constraints default to NONCLUSTERED.In a CREATE TABLE statement, CLUSTERED can be specified for only one constraint. If CLUSTERED is specified for a UNIQUE constraint and a PRIMARY KEY constraint is also specified, the PRIMARY KEY defaults to NONCLUSTERED.
You can create an index on a PK field, but not a non-clustered index on a non-pk non-unique-constrained field.
A NCL index is not relevant to the structure of the table, and is not a constraint on the data inside the table. It's a separate entity that supports the table but is not integral to it's functionality or design.
That's why it's a separate statement. The NCL index is irrelevant to the table from a design perspective (query optimization notwithstanding).
router.navigate['/path']
will only takes you to the specified path
use router.navigateByUrl('/path')
it reloads the whole page
If you're on a Unix-like system, use gettimeofday
and convert the result from microseconds to milliseconds.
This should work:
if (!string.IsNullOrWhiteSpace(dateTimeEnd))
eventCustom.DateTimeEnd = DateTime.Parse(dateTimeEnd);
else
eventCustom.DateTimeEnd = null;
Note that this will throw an exception if the string is not in the correct format.
The META-INF folder is the home for the MANIFEST.MF file. This file contains meta data about the contents of the JAR. For example, there is an entry called Main-Class that specifies the name of the Java class with the static main() for executable JAR files.
Ternary is the most clear way of doing this.
<div>{{ConditionVar ? 'varIsTrue' : 'varIsFalse'}}</div>
Edge (as opposed to IE11) has a better UI for Local storage / Session storage and cookies:
Actually the XSD is XML itself. Its purpose is to validate the structure of another XML document. The XSD is not mandatory for any XML, but it assures that the XML could be used for some particular purposes. The XML is only containing data in suitable format and structure.
In the database, there are two options:
I've used bytea columns with great success in the past storing 10+gb of images with thousands of rows. PG's TOAST functionality pretty much negates any advantage that blobs have. You'll need to include metadata columns in either case for filename, content-type, dimensions, etc.
To get this working with YAML, do this:
property-name: '{
key1: "value1",
key2: "value2"
}'
After instaling the package you need to add the newtonsoft.json.dll into assemble path by runing the flowing command.
Before we can use our assembly, we have to add it to the global assembly cache (GAC). Open the Visual Studio 2008 Command Prompt again (for Vista/Windows7/etc. open it as Administrator). And execute the following command. gacutil /i d:\myMethodsForSSIS\myMethodsForSSIS\bin\Release\myMethodsForSSIS.dll
flow this link for more informATION http://microsoft-ssis.blogspot.com/2011/05/referencing-custom-assembly-inside.html
Usually when I want to pass arguments to an alias in Bash, I use a combination of an alias and a function like this, for instance:
function __t2d {
if [ "$1x" != 'x' ]; then
date -d "@$1"
fi
}
alias t2d='__t2d'
If I recall correctly, 'make' uses timestamps (file modification time) to determine whether or not a target is up to date. A common way to force a re-build is to update that timestamp, using the 'touch' command. You could try invoking 'touch' in your makefile to update the timestamp of one of the targets (perhaps one of those sub-makefiles), which might force Make to execute that command.
module Enumerable
def map_with_index(&block)
i = 0
self.map { |val|
val = block.call(val, i)
i += 1
val
}
end
end
["foo", "bar"].map_with_index {|item, index| [item, index] } => [["foo", 0], ["bar", 1]]
After read all Answers I came up with elegant way:
public class MyActivity extends ActionBarActivity {
Fragment fragment ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FragmentManager fm = getSupportFragmentManager();
fragment = fm.findFragmentByTag("myFragmentTag");
if (fragment == null) {
FragmentTransaction ft = fm.beginTransaction();
fragment =new MyFragment();
ft.add(android.R.id.content,fragment,"myFragmentTag");
ft.commit();
}
}
basically you don't need to add a frameLayout as container of your fragment instead you can add straight the fragment into the android root View container
IMPORTANT: don't use replace fragment as most of the approach shown here, unless you don't mind to lose fragment variable instance state during onrecreation process.
I can't for the life of me get the Next or Finish button to not go grey
This is the eclipse pain in the ass UI. If you unckecked previously some components because they have broken dependencies, it blocks in the license. You have to unselect them in the first step.
Note that avoid to use the update feature of Eclipse it broke all my plugin, I had to delete my ./eclipse folder and reinstall all.
You should put the button inside a div, and in the div you should be able to use the classes:
text-left, text-center and text-right.
for example:
<div class="row">
<div class="col text-center">
<button class="button button-small button-light">Search</button>
</div>
</div>
And about the "textarea" position:
<div class="list">
<label class="item item-input">
<span class="input-label">Date</span>
<input type="text" placeholder="Text Area">
</label>
Demo using your code:
http://codepen.io/douglask/pen/zxXvYY
I use this code for VB:
<asp:TemplateField HeaderText="Active" SortExpression="Active">
<ItemTemplate><%#IIf(Boolean.Parse(Eval("Active").ToString()), "Yes", "No")%></ItemTemplate>
</asp:TemplateField>
And this should work for C# (untested):
<asp:TemplateField HeaderText="Active" SortExpression="Active">
<ItemTemplate><%# (Boolean.Parse(Eval("Active").ToString())) ? "Yes" : "No" %></ItemTemplate>
</asp:TemplateField>
Upload buttons are a pain to style because it styles the input and not the button.
but you can use this trick:
http://www.quirksmode.org/dom/inputfile.html
Summary:
Take a normal <input type="file">
and put it in an element with position: relative
.
To this same parent element, add a normal <input>
and an image, which have the correct styles. Position these elements absolutely, so that they occupy the same place as the <input type="file">
.
Set the z-index of the <input type="file">
to 2 so that it lies on top of the styled input/image.
Finally, set the opacity of the <input type="file">
to 0. The <input type="file">
now becomes effectively invisible, and the styles input/image shines through, but you can still click on the "Browse" button. If the button is positioned on top of the image, the user appears to click on the image and gets the normal file selection window. (Note that you can't use visibility: hidden, because a truly invisible element is unclickable, too, and we need the to remain clickable)
If you just need to search for one string within another, use the index
function (or rindex
if you want to start scanning from the end of the string):
if (index($string, $substring) != -1) {
print "'$string' contains '$substring'\n";
}
To search a string for a pattern match, use the match operator m//
:
if ($string =~ m/pattern/) {
print "'$string' matches the pattern\n";
}
@Mark Rajcok gave a great solution for ion projects that include a range type input.
In any other case of non ion projects I will suggest this:
HTML:
<input type="text" name="points" #points maxlength="8" [(ngModel)]="range" (ngModelChange)="range=saverange($event, points)">
Component:
onChangeAchievement(eventStr: string, eRef): string {
//Do something (some manipulations) on input and than return it to be saved:
//In case you need to force of modifing the Element-Reference value on-focus of input:
var eventStrToReplace = eventStr.replace(/[^0-9,eE\.\+]+/g, "");
if (eventStr != eventStrToReplace) {
eRef.value = eventStrToReplace;
}
return this.getNumberOnChange(eventStr);
}
The idea here:
Letting the (ngModelChange)
method to do the Setter job:
(ngModelChange)="range=saverange($event, points)
Enabling direct access to the native Dom element using this call:
eRef.value = eventStrToReplace;
As everyone else told you, you can convert it directly... UNLESS you meant something like "how can I convert an ASCII Extended character to its UTF-16 or UTF-32 value". This is a TOTALLY different question (one at least as good). And one quite difficult, if I remember correctly, if you are using only "pure" C. Then you could start here: https://stackoverflow.com/questions/114611/what-is-the-best-unicode-library-for-c/114643#114643
(for ASCII Extended I mean one of the many "extensions" to the ASCII set. The 0-127 characters of the base ASCII set are directly convertible to Unicode, while the 128-255 are not.). For example ISO_8859-1 http://en.wikipedia.org/wiki/ISO_8859-1 is an 8 bit extensions to the 7 bit ASCII set, or the (quite famous) codepages 437 and 850.
I think you should actually have a submit button or a submit image... Do you have a specific reason for using a "submit div"? If you just want custom styles I recommend <input type="image"...
. http://webdesign.about.com/cs/forms/a/aaformsubmit_2.htm
Use dict.get
Returns the value for key if key is in the dictionary, else default. If default is not given, it defaults to None, so that this method never raises a KeyError.
For those who use Data Binding:
Add the following static method to any class
@BindingAdapter("app:thumbTintCompat")
public static void setThumbTint(SeekBar seekBar, @ColorInt int color) {
seekBar.getThumb().setColorFilter(color, PorterDuff.Mode.SRC_IN);
}
Add app:thumbTintCompat
attribute to your SeekBar
<SeekBar
android:id="@+id/seek_bar"
style="@style/Widget.AppCompat.SeekBar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:thumbTintCompat="@{@android:color/white}"
/>
That's it. Now you can use app:thumbTintCompat
with any SeekBar
. The progress tint can be configured in the same way.
Note: this method is also compatble with pre-lollipop devices.
and dont forget to clean your project after writing these lines you`ll a get an error in your xml file until you´ve cleaned your project in eclipse: Project->Clean...
SQL 2016 solution/workaround here (could also work in earlier versions). This may not work or be appropriate in every situation, but I resolved the error by granting my database user read/write schema ownership as follows in SSMS:
Database > Security > Users > User > Properties > Owned Schemas > check db_datareader and db_datawriter.
If you are planning to hide show some span based on click event which is initially hidden with style="display:none" then .toggle() is best option to go with.
$("span").toggle();
Reasons : Each time you don't need to check whether the style is already there or not. .toggle() will take care of that automatically and hide/show span based on current state.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<input type="button" value="Toggle" onclick="$('#hiddenSpan').toggle();"/>_x000D_
<br/>_x000D_
<br/>_x000D_
<span id="hiddenSpan" style="display:none">Just toggle me</span>
_x000D_
To the original question:
'ln -s '+basebuild+'/IpDome-kernel/kernel /home/build/sandbox/gen2/basebuild/IpDome-kernel/kernal'
This will indeed create a symbolic link (-s
) from the file/directory:
<basebuild>/IpDome-kernel/kernel
to your new link
/home/build/sandbox/gen2/basebuild/IpDome-kernel/kernal
Here's a few ways to help you remember:
First, there's the man page for ln
. You can access this via searching "man ln" in google, or just open a terminal window and type man ln
and you'll get the same information. The man page clearly states:
ln [OPTION]... [-T] TARGET LINK_NAME (1st form)
If having to search or read through a man page every time isn't for you, maybe you'll have an easier time remembering that all nix commands work the same way:
cp /file/that/exists /location/for/new/file
mv /file/that/exists /location/its/moving/to
ln /file/that/exists /the/new/link
cp
copies a file that currently exists (the first argument) to a new file (the second argument).
mv
moves a file that currently exists (the first argument) to a new place (the second argument)
Likewise ln
links a file that currently exists (the first argument) to a new link (the second argument)*
The final option I would like to suggest is you can create your own man pages that are easy to read and easy (for you) to find/remember. Just make a simple shell script that gives you the hint you need. For example?:
In your .bash_aliases file you can place something like:
commandsfx() {
echo "Symlink: ln -s /path/to/file /path/to/symlink"
echo "Copy: cp /file/to/copy /destination/to/send/copy"
}
alias 'cmds'=commandsfx
Then when you need it, from the command line just type cmds
and you'll get back the proper syntax in a way you can quickly read and understand it. You can make these functions as advanced as you'd like to get what what information you need, it's up to you. You could even make them interactive so you just have to follow the prompts.. something like:
makesymlink() {
echo "Symlink name:"
read sym
echo "File to link to:"
read fil
ln -s $fil $sym
}
alias 'symlink'=makesymlink
* - well obviously they can all take different parameters and do different things and can work on files as well as directories... but the premise is the same
? - examples using the bash shell
A String is an object in Java.
you could compare like so,
if(this.lastName.compareTo(s.getLastName() == 0)//last names are the same
Will result always be the floor of the division? What is the defined behavior?
Not quite. It rounds toward 0, rather than flooring.
6.5.5 Multiplicative operators
6 When integers are divided, the result of the / operator is the algebraic quotient with any fractional part discarded.88) If the quotient a/b is representable, the expression (a/b)*b + a%b shall equal a.
and the corresponding footnote:
- This is often called ‘‘truncation toward zero’’.
Of course two points to note are:
3 The usual arithmetic conversions are performed on the operands.
and:
5 The result of the / operator is the quotient from the division of the first operand by the second; the result of the % operator is the remainder. In both operations, if the value of the second operand is zero, the behavior is undefined.
[Note: Emphasis mine]
If you are using Angular2+ following code will help
You can use following syntax to get attribute value from html element
//to retrieve html element
const element = fixture.debugElement.nativeElement.querySelector('name of element'); // example a, h1, p
//get attribute value from that element
const attributeValue = element.attributeName // like textContent/href
How to convert foreach
to react to the last element:
List<int> myList = new List<int>() {1, 2, 3, 4, 5};
Console.WriteLine("foreach version");
{
foreach (var current in myList)
{
Console.WriteLine(current);
}
}
Console.WriteLine("equivalent that reacts to last element");
{
var enumerator = myList.GetEnumerator();
if (enumerator.MoveNext() == true) // Corner case: empty list.
{
while (true)
{
int current = enumerator.Current;
// Handle current element here.
Console.WriteLine(current);
bool ifLastElement = (enumerator.MoveNext() == false);
if (ifLastElement)
{
// Cleanup after last element
Console.WriteLine("[last element]");
break;
}
}
}
enumerator.Dispose();
}
HTML5 spec:
http://www.w3.org/TR/html5/forms.html#enabling-and-disabling-form-controls:-the-disabled-attribute :
The checked content attribute is a boolean attribute
http://www.w3.org/TR/html5/infrastructure.html#boolean-attributes :
The presence of a boolean attribute on an element represents the true value, and the absence of the attribute represents the false value.
If the attribute is present, its value must either be the empty string or a value that is an ASCII case-insensitive match for the attribute's canonical name, with no leading or trailing whitespace.
Conclusion:
The following are valid, equivalent and true:
<input type="text" disabled />
<input type="text" disabled="" />
<input type="text" disabled="disabled" />
<input type="text" disabled="DiSaBlEd" />
The following are invalid:
<input type="text" disabled="0" />
<input type="text" disabled="1" />
<input type="text" disabled="false" />
<input type="text" disabled="true" />
The absence of the attribute is the only valid syntax for false:
<input type="text" />
Recommendation
If you care about writing valid XHTML, use disabled="disabled"
, since <input disabled>
is invalid and other alternatives are less readable. Else, just use <input disabled>
as it is shorter.
pathlib
module (python's object-oriented filesystem paths)Just for kicks, this is perhaps the latest pythonic version of the solution.
from pathlib import Path
path = Path(f'{player}.txt')
path.touch() # default exists_ok=True
with path.open('a') as highscore:
highscore.write(f'Username:{player}')
If you are using an <img>
tag for the SVG, then you cannot manipulate its contents (as far as I know).
As the accepted answer shows, using <object>
is an option.
I needed this recently and used gulp-inject
during my gulp build to inject the contents of an SVG file directly into the HTML document as an <svg>
element, which is then very easy to work with using CSS selectors and querySelector
/getElementBy*
.
The color and window sizing are defined by the shortcut LNK file. I think I found a way that will do what you need, try this:
explorer.exe "Windows PowerShell.lnk"
The LNK file is in the all user start menu which is located in different places depending whether your on XP or Windows 7. In 7 the LNK file is here:
C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Accessories\Windows PowerShell
Generally if you are not sure of what value you will end up returning, you should consider using return-type as super-class of all the return values. In this case, where you need to return String or int, consider returning Object class(which is the base class of all the classes defined in java).
But be careful to have instanceof checks where you are calling this method. Or else you may end up getting ClassCastException.
public static void main(String args[]) {
Object obj = myMethod(); // i am calling static method from main() which return Object
if(obj instanceof String){
// Do something
}else(obj instance of Integer) {
//do something else
}
Simple HTML + Thymeleaf version. Code with Controller
<form action="/" method="post">
<input type="hidden" th:value="${post.getId_post()}" name="id_post">
<input type="hidden" th:value="-1" name="valueForChange">
<input type="submit" value="-">
</form>
This is how it looks - look of buttons you can change with style. https://i.stack.imgur.com/b97N1.png
var baseArrayOfJsonObjects = [{},{}];
for (var i=0; i<arrayOfJsonObjectsFromAjax.length; i++) {
baseArrayOfJsonObjects.push(arrayOfJsonObjectsFromAjax[i]);
}
Range("A:B,D:E,G:H").Select
can help
Edit note: I just saw you have used different column sequence, I have updated my answer
Günters answer is great, I just want to point out another way without using Observables.
Here we though have to remember that these objects are passed by reference, so if you want to do some work on the object in the child and not affect the parent object, I would suggest using Günther's solution. But if it doesn't matter, or actually is desired behavior, I would suggest the following.
@Injectable()
export class SharedService {
sharedNode = {
// properties
};
}
In your parent you can assign the value:
this.sharedService.sharedNode = this.node;
And in your children (AND parent), inject the shared Service in your constructor. Remember to provide the service at module level providers array if you want a singleton service all over the components in that module. Alternatively, just add the service in the providers array in the parent only, then the parent and child will share the same instance of service.
node: Node;
ngOnInit() {
this.node = this.sharedService.sharedNode;
}
And as newman kindly pointed, you can also have this.sharedService.sharedNode
in the html template or a getter:
get sharedNode(){
return this.sharedService.sharedNode;
}
How about PropertiesLoaderUtils?
Resource resource = new ClassPathResource("/my.properties");
Properties props = PropertiesLoaderUtils.loadProperties(resource);
If you include a file input box you can access the file as a base64 encoded string by using the FileReader object. If it's a text file a simple base64 decode will work to get the text.
Assuming the following HTML:
<input type="file" id="myfile" />
You can access using the following JQuery JS:
var file = $('#myfile').get(0).files[0];
var reader = new FileReader();
reader.onload = function (e) {
//get the file result, split by comma to remove the prefix, then base64 decode the contents
var decodedText = atob(e.target.result.split(',')[1]);
//show the file contents
alert(decoded);
};
reader.readAsDataURL(file);
Yep, just add parenthesis (calling the function). Make sure the function is in scope and actually returns something.
<ul class="ui-listview ui-radiobutton" ng-repeat="meter in meters">
<li class = "ui-divider">
{{ meter.DESCRIPTION }}
{{ htmlgeneration() }}
</li>
</ul>
I understand the question as this: you want to completely replace the contents of one file (or a selection) from upstream. You don't want to affect the index directly (so you would go through add + commit as usual).
Simply do
git checkout remote/branch -- a/file b/another/file
If you want to do this for extensive subtrees and instead wish to affect the index directly use
git read-tree remote/branch:subdir/
You can then (optionally) update your working copy by doing
git checkout-index -u --force
I had a similar problem and ended up using parse_url
and parse_str
, which as long as the URL in the parameter is correctly url encoded (which it definitely should) allows you to access both all the parameters of the actual URL, as well as the parameters of the encoded URL in the query parameter, like so:
$get_url = "http://google.com/?var=234&key=234";
$my_url = "http://localhost/test.php?id=" . urlencode($get_url);
function so_5645412_url_params($url) {
$url_comps = parse_url($url);
$query = $url_comps['query'];
$args = array();
parse_str($query, $args);
return $args;
}
$my_url_args = so_5645412_url_params($my_url); // Array ( [id] => http://google.com/?var=234&key=234 )
$get_url_args = so_5645412_url_params($my_url_args['id']); // Array ( [var] => 234, [key] => 234 )
You need to cleanup your tortoise SVN by clicking on cleanup option you get after Right Clicking on windows where you want to UPDATE SVN. And after cleanup try updating SVN similarly by clicking UPDATE SVN option you get after right clicking.
This worked for me.
The technique below helped me many times:
System.out.println(TheNoDefFoundClass.class.getProtectionDomain().getCodeSource().getLocation());
where the TheNoDefFoundClass is the class that might be "lost" due to a preference for an older version of the same library used by your program. This most frequently happens with the cases, when the client software is being deployed into a dominant container, armed with its own classloaders and tons of ancient versions of most popular libs.
Delete the .metadata
folder in your workspace.
If you want check only displayed objects(C#):
public bool TextPresent(string text, int expectedNumberOfOccurrences)
{
var elements = Driver.FindElements(By.XPath(".//*[text()[contains(.,'" + text + "')]]"));
var dispayedElements = 0;
foreach (var webElement in elements)
{
if (webElement.Displayed)
{
dispayedElements++;
}
}
var allExpectedElementsDisplayed = dispayedElements == expectedNumberOfOccurrences;
return allExpectedElementsDisplayed;
}
The list()
function [docs] will convert a string into a list of single-character strings.
>>> list('hello')
['h', 'e', 'l', 'l', 'o']
Even without converting them to lists, strings already behave like lists in several ways. For example, you can access individual characters (as single-character strings) using brackets:
>>> s = "hello"
>>> s[1]
'e'
>>> s[4]
'o'
You can also loop over the characters in the string as you can loop over the elements of a list:
>>> for c in 'hello':
... print c + c,
...
hh ee ll ll oo
In Microsoft ASP.net MVC, the routing engine, which is used to parse incoming and outgoing URL Combinations, is designed with the idea of Convention over Configuration. What this means is that if you follow the Convention (rules) that the routing engine uses, you don't have to change the Configuration.
The routing engine for ASP.net MVC does not serve web pages (.cshtml). It provides a way for a URL to be handled by a Class in your code, which can render text/html to the output stream, or parse and serve the .cshtml files in a consistent manner using Convention.
The Convention which is used for routing is to match a Controller to a Class with a name similar to ControllerNameController
i.e. controller="MyAccount"
means find class named MyAccountController
. Next comes the action, which is mapped to a function within the Controller Class, which usually returns an ActionResult
. i.e. action="LoginRegister"
will look for a function public ActionResult LoginRegister(){}
in the controller's class. This function may return a View()
which would be by Convention named LoginRegister.cshtml
and would be stored in the /Views/MyAccount/
folder.
To summarize, you would have the following code:
/Controllers/MyAccountController.cs:
public class MyAccountController : Controller
{
public ActionResult LoginRegister()
{
return View();
}
}
/Views/MyAccount/LoginRegister.cshtml: Your view file.
My solution is create .htaccess and use #Sorian code.. without .htaccess I failed to remove #
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_URI} !^(/index\.php|/img|/js|/css|/robots\.txt|/favicon\.ico)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ./index.html [L]
(In Chrome 35+ the "Emulation" tab is present by default. Also, the console is available from any primary tab.)
This option is not (yet?) available in the console tab.
It means "no value". You use void
to indicate that a function doesn't return a value or that it has no parameters or both. Pretty much consistent with typical uses of word void in English.
In new code assignment should be,
B[0] = 5
In func(B), you are just passing address of the pointer which is pointing to array B. You can do change in func() as B[i] or *(B + i). Where i is the index of the array.
In the first code the declaration says,
int *B[10]
says that B is an array of 10 elements, each element of which is a pointer to a int. That is, B[i] is a int pointer and *B[i] is the integer it points to the first integer of the i-th saved text line.
If you don't have access to the v$ views (as suggested by Quassnoi) there are two alternatives
select utl_inaddr.get_host_name from dual
and
select sys_context('USERENV','SERVER_HOST') from dual
Personally I'd tend towards the last as it doesn't require any grants/privileges which makes it easier from stored procedures.
This way you get 'y' 'yes' or 'Enter'
read -r -p "Are you sure? [Y/n]" response
response=${response,,} # tolower
if [[ $response =~ ^(yes|y| ) ]] || [[ -z $response ]]; then
your-action-here
fi
If you are using zsh try this:
read "response?Are you sure ? [Y/n] "
response=${response:l} #tolower
if [[ $response =~ ^(yes|y| ) ]] || [[ -z $response ]]; then
your-action-here
fi
.text-left {
text-align: left;
}
.text-right {
text-align: right;
}
.text-center {
text-align: center;
}
bootstrap has added three css classes for text align.
You can use the first selector.
var header = $('.header:first')
I have found class<T>
useful when I create service registry lookups. E.g.
<T> T getService(Class<T> serviceClass)
{
...
}
java.lang.StackOverflowError
The error java.lang.StackOverflowError
is thrown to indicate that the application’s stack was exhausted, due to deep recursion i.e your program/script recurses too deeply.
The StackOverflowError
extends VirtualMachineError
class which indicates that the JVM have been or have run out of resources and cannot operate further. The VirtualMachineError
which extends the Error
class is used to indicate those serious problems that an application should not catch. A method may not declare such errors in its throw
clause because these errors are abnormal conditions that was never expected to occur.
Minimal, Complete, and Verifiable Example
:
package demo;
public class StackOverflowErrorExample {
public static void main(String[] args)
{
StackOverflowErrorExample.recursivePrint(1);
}
public static void recursivePrint(int num) {
System.out.println("Number: " + num);
if(num == 0)
return;
else
recursivePrint(++num);
}
}
Number: 1
Number: 2
.
.
.
Number: 8645
Number: 8646
Number: 8647Exception in thread "main" java.lang.StackOverflowError
at java.io.FileOutputStream.write(Unknown Source)
at java.io.BufferedOutputStream.flushBuffer(Unknown Source)
at java.io.BufferedOutputStream.flush(Unknown Source)
at java.io.PrintStream.write(Unknown Source)
at sun.nio.cs.StreamEncoder.writeBytes(Unknown Source)
at sun.nio.cs.StreamEncoder.implFlushBuffer(Unknown Source)
at sun.nio.cs.StreamEncoder.flushBuffer(Unknown Source)
at java.io.OutputStreamWriter.flushBuffer(Unknown Source)
at java.io.PrintStream.newLine(Unknown Source)
at java.io.PrintStream.println(Unknown Source)
at demo.StackOverflowErrorExample.recursivePrint(StackOverflowErrorExample.java:11)
at demo.StackOverflowErrorExample.recursivePrint(StackOverflowErrorExample.java:16)
.
.
.
at demo.StackOverflowErrorExample.recursivePrint(StackOverflowErrorExample.java:16)
When a function call is invoked by a Java Application, a stack frame is allocated on the call stack. The stack frame
contains the parameters of the invoked method, its local parameters, and the return address of the method. The return address denotes the execution point from which, the program execution shall continue after the invoked method returns. If there is no space for a new stack frame then, the StackOverflowError
is thrown by the Java Virtual Machine (JVM).
The most common case that can possibly exhaust a Java application’s stack is recursion. In recursion, a method invokes itself during its execution. Recursion
one of the most powerful general-purpose programming technique, but must be used with caution, in order for the StackOverflowError
to be avoided.
raw_input is your helper here. From documentation -
If the prompt argument is present, it is written to standard output without a trailing newline. The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that. When EOF is read, EOFError is raised.
So your code will basically look like this.
num_array = list()
num = raw_input("Enter how many elements you want:")
print 'Enter numbers in array: '
for i in range(int(num)):
n = raw_input("num :")
num_array.append(int(n))
print 'ARRAY: ',num_array
P.S: I have typed all this free hand. Syntax might be wrong but the methodology is correct. Also one thing to note is that, raw_input
does not do any type checking, so you need to be careful...
The AWS support pointed a simpler solution. It's basically the same idea proposed by @Vivek M. Chawla, with a more simple implementation.
AWS S3:
aws.example.com
Redirect all requests to another host name
and enter your URL:
https://myaccount.signin.aws.amazon.com/console/
AWS Route53:
Yes
. Click on Alias
Target
field and select the S3 bucket you created in the previous
step.Reference: How to redirect domains using Amazon Web Services
AWS official documentation: Is there a way to redirect a domain to another domain using Amazon Route 53?
Easyest solution I found: I had some < span > tags with :hover css rules in them. I switched for < a href="javascript:void(0)" > and voilà. The hover styles in iOS started working.
It should be sufficient to use
git ls-files --others -i --exclude-standard
as that covers everything covered by
git ls-files --others -i --exclude-from=.git/info/exclude
therefore the latter is redundant.
~/.gitconfig
file:
git config --global alias.ignored "ls-files --others -i --exclude-standard"
Now you can just type git ignored
to see the list. Much easier to remember, and faster to type.
If you prefer the more succinct display of Jason Geng's solution, you can add an alias for that like this:
git config --global alias.ignored "status --ignored -s"
However the more verbose output is more useful for troubleshooting problems with your .gitignore files, as it lists every single cotton-pickin' file that is ignored. You would normally pipe the results through grep
to see if a file you expect to be ignored is in there, or if a file you don't want to be ignore is in there.
git ignored | grep some-file-that-isnt-being-ignored-properly
Then, when you just want to see a short display, it's easy enough to remember and type
git status --ignored
(The -s
can normally be left off.)
They are functionally equivalent, but INNER JOIN
can be a bit clearer to read, especially if the query has other join types (i.e. LEFT
or RIGHT
or CROSS
) included in it.
.main-box{
border: solid 10px;
}
.sub-box{
border-right: 1px solid;
}
//draws a line on right side of the box. later add a margin-top and margin-bottom. i.e.,
.sub-box{
border-right: 1px solid;
margin-top: 10px;;
margin-bottom: 10px;
}
This might help in drawing a line on the right-side of the box with a gap on top and bottom.
It isn't possible to do directly. There are a couple alternatives:
UIBarButtonItem
that validates on tap and pops if the test passesUITextField
delegate method, such as -textFieldShouldReturn:
, which is called after the Return
or Done
button is pressed on the keyboardThe downside of the first option is that the left-pointing-arrow style of the back button cannot be accessed from a custom bar button. So you have to use an image or go with a regular style button.
The second option is nice because you get the text field back in the delegate method, so you can target your validation logic to the specific text field sent to the delegate call-back method.
After have read all the above, I have found that there could be another reason for this.
In my case:
react-native-cli: 2.0.1
react-native: 0.60.4
and following structure:
First has to be noted that index.android is not been update in Android Studio when the build run by Metro builder( react-native run-android) so it has to be done manually. Also in Android studio does not "read" the
app.json(created by default together with index.js, that renamed index.android.js):
{
"name": "authApp",
"displayName": "authApp"
}
and so this like
(in my case)
import {authApp as appName} from './app.json';
cause the fact that android studio does not know what authApp refer to. I fix for the moment referring to the app name with its string name and not using that import from app.json:
AppRegistry.registerComponent('authApp', () => MyApp);
Try this
sql = "select username from usermst where userid=2"
string getusername = Convert.ToString(command.ExecuteScalar());
UPDATE
the super finishAffinity()
method will help to reduce the code but achieve the same. It will finish the current activity as well as all activities in the stack, use getActivity().finishAffinity()
if you are in a fragment.
finishAffinity();
startActivity(new Intent(mActivity, LoginActivity.class));
ORIGINAL ANSWER
Assume that LoginActivity --> HomeActivity --> ... --> SettingsActivity call signOut():
void signOut() {
Intent intent = new Intent(this, HomeActivity.class);
intent.putExtra("finish", true);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); // To clean up all activities
startActivity(intent);
finish();
}
HomeActivity:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
boolean finish = getIntent().getBooleanExtra("finish", false);
if (finish) {
startActivity(new Intent(mContext, LoginActivity.class));
finish();
return;
}
initializeView();
}
This works for me, hope that it is helpful for you too. :)
The difference between this two tables ItemBack1
and #ItemBack1
is that the first on is persistent (permanent) where as the other is temporary.
Now if take a look at your question again
Is it necessary to Use # for creating temp table in sql server?
The answer is Yes, because without this preceding #
the table will not be a temporary table, it will be independent of all sessions and scopes.
You can Use this for Curl:
function fakeip()
{
return long2ip( mt_rand(0, 65537) * mt_rand(0, 65535) );
}
function getdata($url,$args=false)
{
global $session;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("REMOTE_ADDR: ".fakeip(),"X-Client-IP: ".fakeip(),"Client-IP: ".fakeip(),"HTTP_X_FORWARDED_FOR: ".fakeip(),"X-Forwarded-For: ".fakeip()));
if($args)
{
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,$args);
}
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//curl_setopt($ch, CURLOPT_PROXY, "127.0.0.1:8888");
$result = curl_exec ($ch);
curl_close ($ch);
return $result;
}
Then To Read Json:
$result=getdata("https://example.com");
Then :
///Deocde Json
$data = json_decode($result,true);
///Count
$total=count($data);
$Str='<h1>Total : '.$total.'';
echo $Str;
//You Can Also Make In Table:
foreach ($data as $key => $value)
{
echo ' <td><font face="calibri"color="red">'.$value[type].' </font></td><td><font face="calibri"color="blue">'.$value[category].' </font></td><td><font face="calibri"color="green">'.$value[amount].' </font></tr><tr>';
}
echo "</tr></table>";
}
You Can Also Use This:
echo '<p>Name : '.$data['result']['name'].'</p>
<img src="'.$data['result']['pic'].'"><br>';
Hope this helped.
@hbhakhra's answer will do.
If you're interested in detailed explanation, it is useful to look into Android Compatibility Definition Document. (3.2.2 Build Parameters)
You will find:
DEVICE - A value chosen by the device implementer containing the development name or code name identifying the configuration of the hardware features and industrial design of the device. The value of this field MUST be encodable as 7-bit ASCII and match the regular expression “^[a-zA-Z0-9_-]+$”.
MODEL - A value chosen by the device implementer containing the name of the device as known to the end user. This SHOULD be the same name under which the device is marketed and sold to end users. There are no requirements on the specific format of this field, except that it MUST NOT be null or the empty string ("").
MANUFACTURER - The trade name of the Original Equipment Manufacturer (OEM) of the product. There are no requirements on the specific format of this field, except that it MUST NOT be null or the empty string ("").
Since you are using JSON.NET, personally I would go with serialization so that you can have Intellisense support for your object. You'll need a class that represents your JSON structure. You can build this by hand, or you can use something like json2csharp to generate it for you:
e.g.
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
public class RootObject
{
public List<Person> People { get; set; }
}
Then, you can simply call JsonConvert
's methods to deserialize the JSON into an object:
RootObject instance = JsonConvert.Deserialize<RootObject>(json);
Then you have Intellisense:
var firstName = instance.People[0].FirstName;
var lastName = instance.People[0].LastName;
This seems to be premature microoptimization. The compiler is free to produce the same code for both cases or at least for these two
if len(s) != 0 { ... }
and
if s != "" { ... }
because the semantics is clearly equal.
Very similar to previous responses, but the is from the current directory, looks at any file and only for ones that are 4 days old. This is what I needed for my research and the above answers were all very helpful. Thanks.
Get-ChildItem -Path . -Recurse| ? {$_.LastWriteTime -gt (Get-Date).AddDays(-4)}
You need to just replace '
with ''
inside your string
SELECT colA, colB, colC
FROM tableD
WHERE colA = 'John''s Mobile'
You can also use REPLACE(@name, '''', '''''')
if generating the SQL dynamically
If you want to escape inside a like statement then you need to use the ESCAPE syntax
It's also worth mentioning that you're leaving yourself open to SQL injection attacks if you don't consider it. More info at Google or: http://it.toolbox.com/wiki/index.php/How_do_I_escape_single_quotes_in_SQL_queries%3F
You can silence the "Snapshotting a view" warning by referencing the view
property before presenting the view controller. Doing so causes the view to load and allows iOS render it before taking the snapshot.
UIAlertController *controller = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
controller.modalPresentationStyle = UIModalPresentationPopover;
controller.popoverPresentationController.barButtonItem = (UIBarButtonItem *)sender;
... setup the UIAlertController ...
[controller view]; // <--- Add to silence the warning.
[self presentViewController:controller animated:YES completion:nil];
org.apache.commons.lang.ArrayUtils can do this
num = (int []) ArrayUtils.add(num, 12); // builds new array with 12 appended
To my knowledge, there is sadly no CSS filter to colorise an element (perhaps with the use of some SVG filter magic, but I'm somewhat unfamiliar with that) and even if that wasn't the case, filters are basically only supported by webkit browsers.
With that said, you could still work around this and use a canvas
to modify your image. Basically, you can draw an image element onto a canvas and then loop through the pixels, modifying the respective RGBA values to the colour you want.
However, canvases do come with some restrictions. Most importantly, you have to make sure that the image src comes from the same domain as the page. Otherwise the browser won't allow you to read or modify the pixel data of the canvas.
Here's a JSFiddle changing the colour of the JSFiddle logo.
//Base64 source, but any local source will work_x000D_
var src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAC0AAAAgCAYAAACGhPFEAAAABGdBTUEAALGPC/xhBQAABzhJREFUWAnNWAtwXFUZ/v9zs4GUJJu+k7tb5DFAGWO1aal1sJUiY3FQQaWidqgPLAMqYzd9CB073VodhCa7KziiFgWhzvAYQCiCD5yK4gOTDnZK2ymdZoruppu0afbu0pBs7p7f7yy96W662aw2QO/Mzj2P//Gd/5z/+89dprfzubnTN332Re+xiKawllxWucm+9O4eCi9xT8ctn45yKd3AXX1BPsu3XIiuY+K5kDmrUA7jORb5m2baLm7uscNrJr9eOF9Je8JAz9ySnFHlq9nEpG6CYx+RdJDQDtKymxT1iWZLFDUy0/kkfDUxzYVzV0hvHZLs946Gph+uBLCRmRDQdjTVwmw9DZCNMPi4KzqWbPX/sxwIu71vlrKq10HnZizwTSFZngj5f1NOx5s7bdB2LHWDEusBOD487LrX9qyd8qpnvJL3zGjqAh+pR4W4RVhu715Vv2U8PTWeQLn5YHvms4qsR4TpH/ImLfhfARvbPaGGrrjTtwjH5hFFfHcgkv5SOZ9mbvxIgwGaZl+8ULGcJ8zOsJa9R1r9B2d8v2eGb1KNieqBhLNz8ekyAoV3VAX985+FvSXEenF8lf9lA7DUUxa0HUl/RTG1EfOUQmUwwCtggDewiHmc1R+Ir/MfKJz/f9tTwn31Nf7qVxlHLR6qXwg7cHXqU/p4hPdUB6Lp55TiXwDYTsrpG12dbdY5t0WLrCSRSVjIItG0dqIAG2jHwlPTmvQdsL3Ajjg3nAq3zIgdS98ZiGV0MJZeWVJs2WNWIJK5hcLh0osuqVTxIAdi6X3w/0LFGoa+AtFMzo5kflix0gQLBiLOZmAYro84RcfSc3NKpFAcliM9eYDdjZ7QO/1mRc+CTapqFX+4lO9TQEPoUpz//anQ5FQphXdizB1QXXk/moOl/JUC7aLMDpQSHj02PdxbG9xybM60u47UjZ4bq290Zm451ky3HSi6kxTKJ9fXHQVvZJm1XTjutYsozw53T1L+2ufBGPMTe/c30M/mD3uChW+c+6tQttthuBnbqMBLKGbydI54/eFQ3b5CWa/dGMl8xFJ0D/rvg1Pjdxil+2XK5b6ZWD15lyfnvYOxTBYs9TrY5NbuUENRUo5EGtGyVUNtBwBfDjA/IDtTkiNRsdYD8O+NcVN2KUfXo3UnukvA6Z3I+mWeY++NpNoAwDvAv1Uiss7oiNBmYD+XraoO0NvnPVnvrbUsA4CcYusPgajzY2/cvN+KtOFl/6w/IWrvdTV/Ktla92KhkNcOxpwPCqm/IgLbEvteW1m4E2/d8iY9AZOXQ/7WxKq6nxq9YNT5OLF6DmAfTHT13EL3XjTk2csXk4bqX2OXWiQ73Jz49tS4N5d/oxoHLr14EzPfAf1IIlS/2oznIx1omLURhL5Qa1oxFuC8EeHb8U6I88bXCwGbuZ61jb2Jgz1XYUHb0b0vEHNWmHE9lNsjWrcmnMhNhYDNnCkmNJSFHFdzte82M1b04HgC6HrYbAPw1pFdNOc4GE334wz9qkihRAdK/0HBub/E1MkhJBiq6V8gq7Htm05OjN2C/z/jCP1xbAlCwcnsAsbdkGHF/trPIcoNrtbjFRNmoama6EgZ42SimRG5FjLHWakNwWjmirLyZpLpKH7TysghZ00OUHNTxFmK2yDNQSKlx7u0Q0GQeLtQdy4rY5zMzqVb/ccoJ/OQMEmoPWW3988to4NY8DxYf6WMDCW6ktuRvFqxmqewgguhdLCcwsic0DMA8lE7kvrYyFhBw446X2B/nRNo739/YnX9azKUXYCg9CtlvdAUyywuEB1p4gh9AzbPZc0mF8Z+sINgn0MIwiVgKcAG6rGlT86AMdqw2n8ppR63o+mveQXCFAxzX2BWD0P6pcT+g3uNlmEDV3JX4iOh1xICdWU2gGXOMXN5HfRhK4IoPxlfXQfmKf+Ajh1I+MEeHMcKzqvoxoZsHsoOXgP+fEkxbw1e2JhB0h2q9tc4OL/fAVdsdd3jnyhklmRo8qGBQXchIvMMKPW7Pt85/SM66CNmDw1mh75cHu6JWZFZxNLNSJTPIM5PuJquKEt3o6zmqyJZH4LTC7CIfTonO5Jr/B2jxIq6jW3OZVYVX4edDSD6e1BAXqwgl/I2miKp+ZayOkT0CjaJww21/2bhznio7uoiL2dQB8HdhoV++ri4AdUdtgfw789mRHspzulXzyCcI1BMVQXgL5LodnP7zFfE+N9/9yOUyedxTn/SFHWWj0ifAY1ANHUleOJRlPqdCUmbO85J1jjxUfkUkgVCsg1/uGw0n/fvFm67LT2NLTLfi98Cke8dpMGl3r9QxVRnPuPrWzaIUmsAtgas0okd6ETh7AYt5d7+BeCbhfKVcQ6CtwgJjjoiP3fdgVbcbY57/otBnxidfndvo6/67BtxUf4kztJsbMg0CJaU9QxN2FskhePQBWr7La6wvzRFarTtyoBgB4hm5M//aAMT2+/Vlfzp81/vywLMWSBN1QAAAABJRU5ErkJggg==";_x000D_
var canvas = document.getElementById("theCanvas");_x000D_
var ctx = canvas.getContext("2d");_x000D_
var img = new Image;_x000D_
_x000D_
//wait for the image to load_x000D_
img.onload = function() {_x000D_
//Draw the original image so that you can fetch the colour data_x000D_
ctx.drawImage(img,0,0);_x000D_
var imgData = ctx.getImageData(0, 0, canvas.width, canvas.height);_x000D_
_x000D_
/*_x000D_
imgData.data is a one-dimensional array which contains _x000D_
the respective RGBA values for every pixel _x000D_
in the selected region of the context _x000D_
(note i+=4 in the loop)_x000D_
*/_x000D_
_x000D_
for (var i = 0; i < imgData.data.length; i+=4) {_x000D_
imgData.data[i] = 255; //Red, 0-255_x000D_
imgData.data[i+1] = 255; //Green, 0-255_x000D_
imgData.data[i+2] = 255; //Blue, 0-255_x000D_
/* _x000D_
imgData.data[i+3] contains the alpha value_x000D_
which we are going to ignore and leave_x000D_
alone with its original value_x000D_
*/_x000D_
}_x000D_
ctx.clearRect(0, 0, canvas.width, canvas.height); //clear the original image_x000D_
ctx.putImageData(imgData, 0, 0); //paint the new colorised image_x000D_
}_x000D_
_x000D_
//Load the image!_x000D_
img.src = src;
_x000D_
body {_x000D_
background: green;_x000D_
}
_x000D_
<canvas id="theCanvas"></canvas>
_x000D_
If you want to modify this I'd go with either of the following:
List<string[]> results;
-- or --
List<List<string>> results;
depending on your needs...
There is a rule in C++, for every new there is a delete.
new is never called. So the address that cout prints is the address of the memory location of myVar, or the value assigned to myPointer in this case. By writing:
myPointer = &myVar;
you say:
myPointer = The address of where the data in myVar is stored
It returns an address that points to a memory location that has been deleted. Because first you create the pointer and assign its value to myPointer, second you delete it, third you print it. So unless you assign another value to myPointer, the deleted address will remain.
NULL equals 0, you delete 0, so you delete nothing. And it's logic that it prints 0 because you did:
myPointer = NULL;
which equals:
myPointer = 0;
You can remove the border from top if the element is sibling of the row . Add this to css :
.row + .row {
border-top:0;
}
Here is the link to the fiddle http://jsfiddle.net/7cb3Y/3/
Open the port where your system is running (sample 8080). Open the port everywhere... Modem, firewalls, etc etc etc.
THen, send your ip + port to the person who will use it.
Try my code. Here you can set all properties of UIButton like text colour, background colour, corner radius, etc.
extension UIButton {
func btnCorner() {
layer.cornerRadius = 10
clipsToBounds = true
backgroundColor = .blue
}
}
Now call like this
yourBtnName.btnCorner()
isset($vars[1]) AND !empty($vars[1])
is equivalent to !empty($vars[1])
.
I prepared simple code to show it empirically.
Last row is undefined variable.
+-----------+---------+---------+----------+---------------------+
| Var value | empty() | isset() | !empty() | isset() && !empty() |
+-----------+---------+---------+----------+---------------------+
| '' | true | true | false | false |
| ' ' | false | true | true | true |
| false | true | true | false | false |
| true | false | true | true | true |
| array () | true | true | false | false |
| NULL | true | false | false | false |
| '0' | true | true | false | false |
| 0 | true | true | false | false |
| 0.0 | true | true | false | false |
| undefined | true | false | false | false |
+-----------+---------+---------+----------+---------------------+
And code
$var1 = "";
$var2 = " ";
$var3 = FALSE;
$var4 = TRUE;
$var5 = array();
$var6 = null;
$var7 = "0";
$var8 = 0;
$var9 = 0.0;
function compare($var)
{
print(var_export($var, true) . "|" .
var_export(empty($var), true) . "|" .
var_export(isset($var), true) . "|" .
var_export(!empty($var), true) . "|" .
var_export(isset($var) && !empty($var), true) . "\n");
}
for ($i = 1; $i <= 9; $i++) {
$var = 'var' . $i;
compare($$var);
}
@print(var_export($var10, true) . "|" .
var_export(empty($var10), true) . "|" .
var_export(isset($var10), true) . "|" .
var_export(!empty($var10), true) . "|" .
var_export(isset($var10) && !empty($var10), true) . "\n");
Undefined variable must be evaluated outside function, because function itself create temporary variable in the scope itself.
The best way doing this - especially if you're adding more than one condition - is:
$values = array(...); // array of your values
$qb->andWhere('where', $qb->expr()->in('r.winner', $values));
If your array of values contains strings, you can't use the setParameter method with an imploded string, because your quotes will be escaped!
im not allowed to 'add a comment' so doing this , but yea what Eru Penkman did is pretty much spot on , to get it like background cover all you need to do is change
.tall-img{_x000D_
margin-top:-50%;_x000D_
width:100%;_x000D_
}_x000D_
.wide-img{_x000D_
margin-left:-50%;_x000D_
height:100%;_x000D_
}
_x000D_
TO
.wide-img{_x000D_
margin-left:-42%;_x000D_
height:100%;_x000D_
}_x000D_
.tall-img{_x000D_
margin-top:-42%;_x000D_
width:100%;_x000D_
}
_x000D_
And, why not unobtrusive with jQuery:
$(function() {
$("#unobtrusive").click(function(e) {
e.preventDefault(); // if desired...
// other methods to call...
});
});
HTML
<a id="unobtrusive" href="http://jquery.com">jquery</a>
// simple example using the concept of setInterval
$(document).ready(function(){
var g = $('.jumping');
function blink(){
g.animate({ 'left':'50px'
}).animate({
'left':'20px'
},1000)
}
setInterval(blink,1500);
});
For a soft impact animation solution:
Swift 3:
let indexPath = IndexPath(item: row, section: 0)
tableView.reloadRows(at: [indexPath], with: .fade)
Swift 2.x:
let indexPath = NSIndexPath(forRow: row, inSection: 0)
tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
This is another way to protect the app from crashing:
Swift 3:
let indexPath = IndexPath(item: row, section: 0)
if let visibleIndexPaths = tableView.indexPathsForVisibleRows?.index(of: indexPath as IndexPath) {
if visibleIndexPaths != NSNotFound {
tableView.reloadRows(at: [indexPath], with: .fade)
}
}
Swift 2.x:
let indexPath = NSIndexPath(forRow: row, inSection: 0)
if let visibleIndexPaths = tableView.indexPathsForVisibleRows?.indexOf(indexPath) {
if visibleIndexPaths != NSNotFound {
tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
}
}
lblrepeated.Text = "";
string value = txtInput.Text;
char[] arr = value.ToCharArray();
char[] crr=new char[1];
int count1 = 0;
for (int i = 0; i < arr.Length; i++)
{
int count = 0;
char letter=arr[i];
for (int j = 0; j < arr.Length; j++)
{
char letter3 = arr[j];
if (letter == letter3)
{
count++;
}
}
if (count1 < count)
{
Array.Resize<char>(ref crr,0);
int count2 = 0;
for(int l = 0;l < crr.Length;l++)
{
if (crr[l] == letter)
count2++;
}
if (count2 == 0)
{
Array.Resize<char>(ref crr, crr.Length + 1);
crr[crr.Length-1] = letter;
}
count1 = count;
}
else if (count1 == count)
{
int count2 = 0;
for (int l = 0; l < crr.Length; l++)
{
if (crr[l] == letter)
count2++;
}
if (count2 == 0)
{
Array.Resize<char>(ref crr, crr.Length + 1);
crr[crr.Length - 1] = letter;
}
count1 = count;
}
}
for (int k = 0; k < crr.Length; k++)
lblrepeated.Text = lblrepeated.Text + crr[k] + count1.ToString();
"Ambiguous column" usually means that the same column name appears in at least two tables; the database engine can't tell which one you want. Use full table names or table aliases to remove the ambiguity.
Here's an example I happened to have in my editor. It's from someone else's problem, but should make sense anyway.
select P.*
from product_has_image P
inner join highest_priority_images H
on (H.id_product = P.id_product and H.priority = p.priority)
Both approaches will catch all exceptions. There is no significant difference between your two code examples except that the first will generate a compiler warning because ex
is declared but not used.
But note that some exceptions are special and will be rethrown automatically.
ThreadAbortException
is a special exception that can be caught, but it will automatically be raised again at the end of the catch block.
http://msdn.microsoft.com/en-us/library/system.threading.threadabortexception.aspx
As mentioned in the comments, it is usually a very bad idea to catch and ignore all exceptions. Usually you want to do one of the following instead:
Catch and ignore a specific exception that you know is not fatal.
catch (SomeSpecificException)
{
// Ignore this exception.
}
Catch and log all exceptions.
catch (Exception e)
{
// Something unexpected went wrong.
Log(e);
// Maybe it is also necessary to terminate / restart the application.
}
Catch all exceptions, do some cleanup, then rethrow the exception.
catch
{
SomeCleanUp();
throw;
}
Note that in the last case the exception is rethrown using throw;
and not throw ex;
.
Adding to Tim's answer:
#search:placeholder-shown {
// show background image, I like svg
// when using svg, do not use HEX for colour; you can use rbg/a instead
// also notice the single quotes
background-image url('data:image/svg+xml; utf8, <svg>... <g fill="grey"...</svg>')
// other background props
}
#search:not(:placeholder-shown) { background-image: none;}
To get the origin of any url, including paths within a website (/my/path
) or schemaless (//example.com/my/path
), or full (http://example.com/my/path
) I put together a quick function.
In the snippet below, all three calls should log https://stacksnippets.net
.
function getOrigin(url)_x000D_
{_x000D_
if(/^\/\//.test(url))_x000D_
{ // no scheme, use current scheme, extract domain_x000D_
url = window.location.protocol + url;_x000D_
}_x000D_
else if(/^\//.test(url))_x000D_
{ // just path, use whole origin_x000D_
url = window.location.origin + url;_x000D_
}_x000D_
return url.match(/^([^/]+\/\/[^/]+)/)[0];_x000D_
}_x000D_
_x000D_
console.log(getOrigin('https://stacksnippets.net/my/path'));_x000D_
console.log(getOrigin('//stacksnippets.net/my/path'));_x000D_
console.log(getOrigin('/my/path'));
_x000D_
Just copy and paste the sameple code below.
<!DOCTYPE html>
<html>
<head>
<script src="https://maps.googleapis.com/maps/api/jsvv=3.exp&sensor=false&libraries=places"></script>
</head>
<body>
<label for="locationTextField">Location</label>
<input id="locationTextField" type="text" size="50">
<script>
function init() {
var input = document.getElementById('locationTextField');
var autocomplete = new google.maps.places.Autocomplete(input);
}
google.maps.event.addDomListener(window, 'load', init);
</script>
</body>
</html>
Well formatted code can be found from this link. http://jon.kim/how-to-add-google-maps-autocomplete-search-box/
Try setting a custom CultureInfo for CurrentCulture and CurrentUICulture.
Globalization.CultureInfo customCulture = new Globalization.CultureInfo("en-US", true);
customCulture.DateTimeFormat.ShortDatePattern = "yyyy-MM-dd h:mm tt";
System.Threading.Thread.CurrentThread.CurrentCulture = customCulture;
System.Threading.Thread.CurrentThread.CurrentUICulture = customCulture;
DateTime newDate = System.Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd h:mm tt"));
select propety
Row Source Type => Value List
Code :
ListbName.ColumnCount=2
ListbName.AddItem "value column1;value column2"
The simplest way, based on @nosklo's comment and answer:
import tempfile
tmp = tempfile.mkdtemp()
But if you want to manually control the creation of the directories:
import os
from tempfile import gettempdir
tmp = os.path.join(gettempdir(), '.{}'.format(hash(os.times())))
os.makedirs(tmp)
That way you can easily clean up after yourself when you are done (for privacy, resources, security, whatever) with:
from shutil import rmtree
rmtree(tmp, ignore_errors=True)
This is similar to what applications like Google Chrome and Linux systemd
do. They just use a shorter hex hash and an app-specific prefix to "advertise" their presence.
If you have a hard time remembering the default values (I know I have...) here's a short extract from BalusC's answer:
Component | Submit | Refresh ------------ | --------------- | -------------- f:ajax | execute="@this" | render="@none" p:ajax | process="@this" | update="@none" p:commandXXX | process="@form" | update="@none"
You should take a look the reference documentation. It's well explained.
In your case, I think you cannot use between because you need to pass two parameters
Between - findByStartDateBetween … where x.startDate between ?1 and ?2
In your case take a look to use a combination of LessThan
or LessThanEqual
with GreaterThan
or GreaterThanEqual
LessThan - findByEndLessThan … where x.start< ?1
LessThanEqual findByEndLessThanEqual … where x.start <= ?1
GreaterThan - findByStartGreaterThan … where x.end> ?1
GreaterThanEqual - findByStartGreaterThanEqual … where x.end>= ?1
You can use the operator And
and Or
to combine both.
The problem is using with statement:
with open('strings.json') as json_data:
d = json.load(json_data)
pprint(d)
The file is going to be implicitly closed already. There is no need to call json_data.close()
again.
select * from sys.tables
order by schema_id --comments: order by 'schema_id' to get the 'tables' in 'object explorer order'
go
our project surely is configured as "library" thats why you get the message : "Android library projects cannot be launched."
right-click in your project and select Properties. In the Properties window -> "Android" -> uncheck the option "is Library" and apply -> Click "ok" to close the properties window.
You add it to the call using:
using (OperationContextScope scope = new OperationContextScope((IContextChannel)channel))
{
MessageHeader<string> header = new MessageHeader<string>("secret message");
var untyped = header.GetUntypedHeader("Identity", "http://www.my-website.com");
OperationContext.Current.OutgoingMessageHeaders.Add(untyped);
// now make the WCF call within this using block
}
And then, server-side you grab it using:
MessageHeaders headers = OperationContext.Current.IncomingMessageHeaders;
string identity = headers.GetHeader<string>("Identity", "http://www.my-website.com");
sep='\t'
is often used for Tab-delimited file.
In order for the client to be able to read cookies from cross-origin requests, you need to have:
All responses from the server need to have the following in their header:
Access-Control-Allow-Credentials: true
The client needs to send all requests with withCredentials: true
option
In my implementation with Angular 7 and Spring Boot, I achieved that with the following:
Server-side:
@CrossOrigin(origins = "http://my-cross-origin-url.com", allowCredentials = "true")
@Controller
@RequestMapping(path = "/something")
public class SomethingController {
...
}
The origins = "http://my-cross-origin-url.com"
part will add Access-Control-Allow-Origin: http://my-cross-origin-url.com
to every server's response header
The allowCredentials = "true"
part will add Access-Control-Allow-Credentials: true
to every server's response header, which is what we need in order for the client to read the cookies
Client-side:
import { HttpInterceptor, HttpXsrfTokenExtractor, HttpRequest, HttpHandler, HttpEvent } from "@angular/common/http";
import { Injectable } from "@angular/core";
import { Observable } from 'rxjs';
@Injectable()
export class CustomHttpInterceptor implements HttpInterceptor {
constructor(private tokenExtractor: HttpXsrfTokenExtractor) {
}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
// send request with credential options in order to be able to read cross-origin cookies
req = req.clone({ withCredentials: true });
// return XSRF-TOKEN in each request's header (anti-CSRF security)
const headerName = 'X-XSRF-TOKEN';
let token = this.tokenExtractor.getToken() as string;
if (token !== null && !req.headers.has(headerName)) {
req = req.clone({ headers: req.headers.set(headerName, token) });
}
return next.handle(req);
}
}
With this class you actually inject additional stuff to all your request.
The first part req = req.clone({ withCredentials: true });
, is what you need in order to send each request with withCredentials: true
option. This practically means that an OPTION request will be send first, so that you get your cookies and the authorization token among them, before sending the actual POST/PUT/DELETE requests, which need this token attached to them (in the header), in order for the server to verify and execute the request.
The second part is the one that specifically handles an anti-CSRF token for all requests. Reads it from the cookie when needed and writes it in the header of every request.
The desired result is something like this:
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, final View view, int position, long id) {
View v;
int count = parent.getChildCount();
v = parent.getChildAt(position);
parent.requestChildFocus(v, view);
v.setBackground(res.getDrawable(R.drawable.transparent_button));
for (int i = 0; i < count; i++) {
if (i != position) {
v = parent.getChildAt(i);
v.setBackground(res.getDrawable(R.drawable.not_clicked));
}
}
}
});
Basically, create two Drawables - one that is transparent, and another that is the desired color. Request focus at the clicked position (int position
as defined) and change the color of the said row. Then walk through the parent ListView
, and change all other rows accordingly. This accounts for when a user clicks on the listview
multiple times. This is done with a custom layout for each row in the ListView
. (Very simple, just create a new layout file with a TextView
- do not set focusable or clickable!).
No custom adapter required - use ArrayAdapter
You error clearly says, you are trying to use locale something was not there.
>>> locale.setlocale(locale.LC_ALL, 'de_DE')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/locale.py", line 581, in setlocale
return _setlocale(category, locale)
locale.Error: unsupported locale setting
locale.Error: unsupported locale setting
To check available setting, use locale -a
deb@deb-Latitude-E7470:/ambot$ locale -a
C
C.UTF-8
en_AG
en_AG.utf8
en_AU.utf8
en_BW.utf8
en_CA.utf8
en_DK.utf8
en_GB.utf8
en_HK.utf8
en_IE.utf8
en_IN
en_IN.utf8
en_NG
en_NG.utf8
en_NZ.utf8
en_PH.utf8
en_SG.utf8
en_US.utf8
en_ZA.utf8
en_ZM
en_ZM.utf8
en_ZW.utf8
POSIX
so you can use one among,
>>> locale.setlocale(locale.LC_ALL, 'en_AG.utf8')
'en_AG.utf8'
>>>
for de_DE
This file can either be adjusted manually or updated using the tool, update-locale.
update-locale LANG=de_DE.UTF-8
https://socket.io/docs/#What-Socket-IO-is-not (with my emphasis)
What Socket.IO is not
Socket.IO is NOT a WebSocket implementation. Although Socket.IO indeed uses WebSocket as a transport when possible, it adds some metadata to each packet: the packet type, the namespace and the packet id when a message acknowledgement is needed. That is why a WebSocket client will not be able to successfully connect to a Socket.IO server, and a Socket.IO client will not be able to connect to a WebSocket server either. Please see the protocol specification here.
// WARNING: the client will NOT be able to connect! const client = io('ws://echo.websocket.org');
You should initialize yours recordings. You are passing to adapter null
ArrayList<String> recordings = null; //You are passing this null
In Windows, you can use the following registry script to add "Delete SVN Folders" to your right click context menu. Run it on any directory containing those pesky files.
Windows Registry Editor Version 5.00
[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\Folder\shell\DeleteSVN]
@="Delete SVN Folders"
[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\Folder\shell\DeleteSVN\command]
@="cmd.exe /c \"TITLE Removing SVN Folders in %1 && COLOR 9A && FOR /r \"%1\" %%f IN (.svn) DO RD /s /q \"%%f\" \""
Here's another way to be compatible with an IHttpActionResult return type. In this case I am asking it to use the XML Serializer(optional) instead of Data Contract serializer, I'm using return ResponseMessage(
so that I get a return compatible with IHttpActionResult:
return ResponseMessage(new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new ObjectContent<SomeType>(objectToSerialize,
new System.Net.Http.Formatting.XmlMediaTypeFormatter {
UseXmlSerializer = true
})
});
Answer by Adamski is a good one and describes the steps in an encoding operation when using the general encode method (that takes a byte buffer as one of the inputs)
However, the method in question (in this discussion) is a variant of encode - encode(CharBuffer in). This is a convenience method that implements the entire encoding operation. (Please see java docs reference in P.S.)
As per the docs, This method should therefore not be invoked if an encoding operation is already in progress (which is what is happening in ZenBlender's code -- using static encoder/decoder in a multi threaded environment).
Personally, I like to use convenience methods (over the more general encode/decode methods) as they take away the burden by performing all the steps under the covers.
ZenBlender and Adamski have already suggested multiple ways options to safely do this in their comments. Listing them all here:
P.S.
java docs references:
Swift 5. Thanks to Emin Bugra Saral above for the startOfDay
suggestion.
extension Date {
func daysBetween(date: Date) -> Int {
return Date.daysBetween(start: self, end: date)
}
static func daysBetween(start: Date, end: Date) -> Int {
let calendar = Calendar.current
// Replace the hour (time) of both dates with 00:00
let date1 = calendar.startOfDay(for: start)
let date2 = calendar.startOfDay(for: end)
let a = calendar.dateComponents([.day], from: date1, to: date2)
return a.value(for: .day)!
}
}
Usage:
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let start = dateFormatter.date(from: "2017-01-01")!
let end = dateFormatter.date(from: "2018-01-01")!
let diff = Date.daysBetween(start: start, end: end) // 365
// or
let diff = start.daysBetween(date: end) // 365
<?php
$res = mysql_query('SELECT getTreeNodeName(1) AS result');
if ($res === false) {
echo mysql_errno().': '.mysql_error();
}
while ($obj = mysql_fetch_object($res)) {
echo $obj->result;
}
Why not just use all Lambda syntax?
database.Stores.Where(s => s.CompanyID == curCompany.ID)
.Select(s => new SelectListItem
{
Value = s.Name,
Text = s.ID
});
select Id, StartDate,
Case IsNull (StartDate , '01/01/1800')
When '01/01/1800' then
'Awaiting'
Else
'Approved'
END AS StartDateStatus
From MyTable
/proc/net/tcp -a list of open tcp sockets
/proc/net/udp -a list of open udp sockets
/proc/net/raw -a list all the 'raw' sockets
These are the files, use cat
command to view them. For example:
cat /proc/net/tcp
You can also use the lsof
command.
lsof is a command meaning "list open files", which is used in many Unix-like systems to report a list of all open files and the processes that opened them.
<select id="case_reason" name="case_reason" disabled="disabled">
disabled="disabled" ->
will get your value from database dan show it in the form.
readonly="readonly" ->
you can change your value in selectbox, but your value couldn't save in your database.
Please don't use any library for this effect instead use the recommended way of doing it according to Google I/O. In your recyclerView's onBindViewHolder method do this:
final boolean isExpanded = position==mExpandedPosition;
holder.details.setVisibility(isExpanded?View.VISIBLE:View.GONE);
holder.itemView.setActivated(isExpanded);
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mExpandedPosition = isExpanded ? -1:position;
TransitionManager.beginDelayedTransition(recyclerView);
notifyDataSetChanged();
}
});
And for the cool effects that you wanted, use these as your list_item attributes:
android:background="@drawable/comment_background"
android:stateListAnimator="@animator/comment_selection"
where comment_background is:
<selector
xmlns:android="http://schemas.android.com/apk/res/android"
android:constantSize="true"
android:enterFadeDuration="@android:integer/config_shortAnimTime"
android:exitFadeDuration="@android:integer/config_shortAnimTime">
<item android:state_activated="true" android:drawable="@color/selected_comment_background" />
<item android:drawable="@color/comment_background" />
</selector>
and comment_selection is:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_activated="true">
<objectAnimator
android:propertyName="translationZ"
android:valueTo="@dimen/z_card"
android:duration="2000"
android:interpolator="@android:interpolator/fast_out_slow_in" />
</item>
<item>
<objectAnimator
android:propertyName="translationZ"
android:valueTo="0dp"
android:duration="2000"
android:interpolator="@android:interpolator/fast_out_slow_in" />
</item>
</selector>
Have a look at:
http://www.codeproject.com/KB/cpp/calling_conventions_demystified.aspx
All the answers above refer to either setting the memory to a certain extent in TensorFlow 1.X
versions or to allow memory growth in TensorFlow 2.X
.
The method tf.config.experimental.set_memory_growth
indeed works for allowing dynamic growth during the allocation/preprocessing. Nevertheless one may like to allocate from the start a specific GPU memory.
The logic behind allocating a specific GPU memory would also be to prevent OOM memory during training sessions. For example, if one trains while opening video-memory consuming Chrome tabs/any other video consumption process, the tf.config.experimental.set_memory_growth(gpu, True)
could result in OOM errors thrown, hence the necessity of allocating from the start more memory in certain cases.
The recommended and correct way in which to allot memory per GPU in TensorFlow 2.X is done in the following manner:
gpus = tf.config.experimental.list_physical_devices('GPU')
if gpus:
# Restrict TensorFlow to only allocate 1GB of memory on the first GPU
try:
tf.config.experimental.set_virtual_device_configuration(
gpus[0],
[tf.config.experimental.VirtualDeviceConfiguration(memory_limit=1024)]
SOAP stands for Simple (sic) Object Access Protocol. It was intended to be a way to do Remote Procedure Calls to remote objects by sending XML over HTTP.
WSDL is Web Service Description Language. A request ending in '.wsdl' to an endpoint will result in an XML message describing request and response that a use can expect. It descibes the contract between service & client.
REST uses HTTP to send messages to services.
SOAP is a spec, REST is a style.
A cookie is just another HTTP header. You can always set it while making a HTTP call with the apache library or with HTTPUrlConnection. Either way you should be able to read and set HTTP cookies in this fashion.
You can read this article for more information.
I can share my peace of code to demonstrate how easy you can make it.
public static String getServerResponseByHttpGet(String url, String token) {
try {
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(url);
get.setHeader("Cookie", "PHPSESSID=" + token + ";");
Log.d(TAG, "Try to open => " + url);
HttpResponse httpResponse = client.execute(get);
int connectionStatusCode = httpResponse.getStatusLine().getStatusCode();
Log.d(TAG, "Connection code: " + connectionStatusCode + " for request: " + url);
HttpEntity entity = httpResponse.getEntity();
String serverResponse = EntityUtils.toString(entity);
Log.d(TAG, "Server response for request " + url + " => " + serverResponse);
if(!isStatusOk(connectionStatusCode))
return null;
return serverResponse;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
PHP 7 improved query.........
$sql = mysqli_query($conn, "SELECT * from users WHERE user_uid = '$uid'");
if (mysqli_num_rows($sql) > 0) {
echo 'Username taken.';
}
Use the str_contains
function.
if (str_contains($str, "."))
{
echo 'Found it';
}
else
{
echo 'Not found.';
}
if (strpos($str, '.') !== FALSE)
{
echo 'Found it';
}
else
{
echo 'Not found.';
}
Note that you need to use the !==
operator. If you use !=
or <>
and the '.'
is found at position 0
, the comparison will evaluate to true because 0
is loosely equal to false
.
as I expected, yeah, it's because the whole DOM element is being pushed down. You have multiple options. You can put the buttons in separate divs, and float
them so that they don't affect each other. the simpler solution is to just set the :active
button to position:relative;
and use top
instead of margin or line-height. example fiddle: http://jsfiddle.net/5CZRP/
For anyone still looking to do this in 2020. So long as you are purely using it for development purposes you can download a full featured version of SQL Server directly from Microsoft at https://www.microsoft.com/en-us/sql-server/sql-server-downloads.
I know this thread is a little bit old but I've just bumped into a similar problem (select the newest article from each category) and this is the solution I came up with :
WITH [TopCategoryArticles] AS (
SELECT
[ArticleID],
ROW_NUMBER() OVER (
PARTITION BY [ArticleCategoryID]
ORDER BY [ArticleDate] DESC
) AS [Order]
FROM [dbo].[Articles]
)
SELECT [Articles].*
FROM
[TopCategoryArticles] LEFT JOIN
[dbo].[Articles] ON
[TopCategoryArticles].[ArticleID] = [Articles].[ArticleID]
WHERE [TopCategoryArticles].[Order] = 1
This is very similar to Darrel's solution but overcomes the RANK problem that might return more rows than intended.
Use variable capture to "pass in" parameters.
var x = rawData;
Task.Run(() =>
{
// Do something with 'x'
});
You also could use rawData
directly but you must be careful, if you change the value of rawData
outside of a task (for example a iterator in a for
loop) it will also change the value inside of the task.
You mean this?
<style type="text/css">
.bgimg {
background-image: url('../images/divbg.png');
}
</style>
...
<div class="bgimg">
div with background
</div>
switch (String.valueOf(value)){
case "null":
default:
}
This should give you the result you want.
double total = 0;
int number = 0;
float percentage = number / total * 100
printf("%.2f",percentage);
Note that the first operand is a double
I also got this terrible error and found a solution for this...
- Right Click on the Solution name
- Click Clean Solution
- Restart Visual Studio
- Goto project Properties >> Build
- Change Configuration to Release
- Start Debugging (F5)
1) , 2)
4) , 5)
Hope this will help you also.
using jQuery
$("#ddl").change(function () {
alert($(this).val());
});
You can try yourself:
>>> import pandas as pd
>>> from StringIO import StringIO
>>> s = """1, 2
... 3, 4
... 5, 6"""
>>> pd.read_csv(StringIO(s), skiprows=[1], header=None)
0 1
0 1 2
1 5 6
>>> pd.read_csv(StringIO(s), skiprows=1, header=None)
0 1
0 3 4
1 5 6
One of the good things about handle.exe
is that you can run it as a subprocess and parse the output.
We do this in our deployment script - works like a charm.
This is how it would be done in a loop in C++(11):
for (const auto& attack : m_attack)
{
if (attack->m_num == input)
{
attack->makeDamage();
}
}
There is no for each
in C++. Another option is to use std::for_each with a suitable functor (this could be anything that can be called with an Attack*
as argument).
Note that Charity Leschinski's answer may have a bit of an issue when there is some delay in the response. eg:
lparstat 1 5 returns one response line and works,
lparstat 5 1 should return 5 lines, but only returns the first
I've put the command output while inside another ... I'm sure there is a better way, I had to do this as a quick fix
while (commandOutput.available() > 0) {
while (readByte != 0xffffffff) {
outputBuffer.append((char) readByte);
readByte = commandOutput.read();
}
try {Thread.sleep(1000);} catch (Exception ee) {}
}
Suposse you have
Class1
public class Class1 {
//Your class code above
}
Class2
public class Class2 {
}
and then you can use Class2 in different ways.
Class Field
public class Class1{
private Class2 class2 = new Class2();
}
Method field
public class Class1 {
public void loginAs(String username, String password)
{
Class2 class2 = new Class2();
class2.invokeSomeMethod();
//your actual code
}
}
Static methods from Class2 Imagine this is your class2.
public class Class2 {
public static void doSomething(){
}
}
from class1 you can use doSomething from Class2 whenever you want
public class Class1 {
public void loginAs(String username, String password)
{
Class2.doSomething();
//your actual code
}
}
Using answer by @Aerospace, I realized that it is legitimate for INI files to have sections without any key-values. In this case, addition to the top-level map should happen before any key-values are found, ex (minimally updated for Java 8):
Path location = ...;
try (BufferedReader br = new BufferedReader(new FileReader(location.toFile()))) {
String line;
String section = null;
while ((line = br.readLine()) != null) {
Matcher m = this.section.matcher(line);
if (m.matches()) {
section = m.group(1).trim();
entries.computeIfAbsent(section, k -> new HashMap<>());
} else if (section != null) {
m = keyValue.matcher(line);
if (m.matches()) {
String key = m.group(1).trim();
String value = m.group(2).trim();
entries.get(section).put(key, value);
}
}
}
} catch (IOException ex) {
System.err.println("Failed to read and parse INI file '" + location + "', " + ex.getMessage());
ex.printStackTrace(System.err);
}
Note that if you want to scroll an element instead of the full window, elements don't have the scrollTo
and scrollBy
methods. You should:
var el = document.getElementById("myel"); // Or whatever method to get the element
// To set the scroll
el.scrollTop = 0;
el.scrollLeft = 0;
// To increment the scroll
el.scrollTop += 100;
el.scrollLeft += 100;
You can also mimic the window.scrollTo
and window.scrollBy
functions to all the existant HTML elements in the webpage on browsers that don't support it natively:
Object.defineProperty(HTMLElement.prototype, "scrollTo", {
value: function(x, y) {
el.scrollTop = y;
el.scrollLeft = x;
},
enumerable: false
});
Object.defineProperty(HTMLElement.prototype, "scrollBy", {
value: function(x, y) {
el.scrollTop += y;
el.scrollLeft += x;
},
enumerable: false
});
so you can do:
var el = document.getElementById("myel"); // Or whatever method to get the element, again
// To set the scroll
el.scrollTo(0, 0);
// To increment the scroll
el.scrollBy(100, 100);
NOTE: Object.defineProperty
is encouraged, as directly adding properties to the prototype
is a breaking bad habit (When you see it :-).
For users that are using node and that are concerned with the context implications of eval()
nodejs offers vm
. It creates a V8 virtual machine that can sandbox the execution of your code in a separate context.
Taking things a step further is vm2
which hardens vm
allowing the vm to run untrusted code.
https://nodejs.org/api/vm.html - Official nodejs/vm
https://github.com/patriksimek/vm2 - Extended vm2
const vm = require('vm');
const x = 1;
const sandbox = { x: 2 };
vm.createContext(sandbox); // Contextify the sandbox.
const code = 'x += 40; var y = 17;';
// `x` and `y` are global variables in the sandboxed environment.
// Initially, x has the value 2 because that is the value of sandbox.x.
vm.runInContext(code, sandbox);
console.log(sandbox.x); // 42
console.log(sandbox.y); // 17
console.log(x); // 1; y is not defined.
The situation with regexes, Unicode, and Javascript sucks. It's ridiculous that programmers should have to rely on external libraries to recognize that "??fa" is a word, or even that "é" is a letter.
But so it goes.
This guy has written a good library for handling Unicode in Javascript Regexes:
http://blog.stevenlevithan.com/archives/javascript-regex-and-unicode
The Unicode stuff is a plugin to this regex library:
Here's a post about the Unicode extension:
http://blog.stevenlevithan.com/archives/xregexp-unicode-plugin
And the extension page itself:
Great work but it still bums me out that Javascript is so backwards in this regard.
(He wrote a book for O'Reilly about the topic so it's quite possible that he knows what he's talking about.)
The way he implemented it is by adding tables of characters with certain properties. Then, when you contruct a regex with his library, \p{charclass}
gets replaced with [allthecharactersintheclass]
.
# Make sure only root can run our script
if [ "$(id -u)" != "0" ]; then
echo "This script must be run as root" 1>&2
exit 1
fi
In Oracle 12c you can use the function STANDARD_HASH. It does not require any additional privileges.
select standard_hash('foo', 'MD5') from dual;
The dbms_obfuscation_toolkit is deprecated (see Note here). You can use DBMS_CRYPTO directly:
select rawtohex(
DBMS_CRYPTO.Hash (
UTL_I18N.STRING_TO_RAW ('foo', 'AL32UTF8'),
2)
) from dual;
Output:
ACBD18DB4CC2F85CEDEF654FCCC4A4D8
Add a lower function call if needed. More on DBMS_CRYPTO.
That package in fact is available through packagist. You don't need a custom repository definition in this case. Just make sure you add a require
(which is always needed) with a matching version constraint.
In general, if a package is available on packagist, do not add a VCS repo. It will just slow things down.
For packages that are not available via packagist, use a VCS (or git) repository, as shown in your question. When you do, make sure that:
require
for the package in questionrequire
matches the versions provided by the VCS repo. You can use composer show <packagename>
to find the available versions. In this case ~2.3
would be a good option.require
matches the name in the remote composer.json
. In this case, it is gedmo/doctrine-extensions
.Here is a sample composer.json
that installs the same package via a VCS repo:
{
"repositories": [
{
"url": "https://github.com/l3pp4rd/DoctrineExtensions.git",
"type": "git"
}
],
"require": {
"gedmo/doctrine-extensions": "~2.3"
}
}
The VCS repo docs explain all of this quite well.
If there is a git (or other VCS) repository with a composer.json
available, do not use a "package" repo. Package repos require you to provide all of the metadata in the definition and will completely ignore any composer.json
present in the provided dist and source. They also have additional limitations, such as not allowing for proper updates in most cases.
Avoid package repos (see also the docs).
The extglob
shell option gives you more powerful pattern matching in the command line.
You turn it on with shopt -s extglob
, and turn it off with shopt -u extglob
.
In your example, you would initially do:
$ shopt -s extglob
$ cp !(*Music*) /target_directory
The full available extended globbing operators are (excerpt from man bash
):
If the extglob shell option is enabled using the shopt builtin, several extended pattern matching operators are recognized.A pattern-list is a list of one or more patterns separated by a |. Composite patterns may be formed using one or more of the following sub-patterns:
- ?(pattern-list)
Matches zero or one occurrence of the given patterns- *(pattern-list)
Matches zero or more occurrences of the given patterns- +(pattern-list)
Matches one or more occurrences of the given patterns- @(pattern-list)
Matches one of the given patterns- !(pattern-list)
Matches anything except one of the given patterns
So, for example, if you wanted to list all the files in the current directory that are not .c
or .h
files, you would do:
$ ls -d !(*@(.c|.h))
Of course, normal shell globing works, so the last example could also be written as:
$ ls -d !(*.[ch])