Communicating between a fragment and an activity - best practices
The easiest way to communicate between your activity and fragments is using interfaces. The idea is basically to define an interface inside a given fragment A and let the activity implement that interface.
Once it has implemented that interface, you could do anything you want in the method it overrides.
The other important part of the interface is that you have to call the abstract method from your fragment and remember to cast it to your activity. It should catch a ClassCastException if not done correctly.
There is a good tutorial on Simple Developer Blog on how to do exactly this kind of thing.
I hope this was helpful to you!
Can two applications listen to the same port?
If by applications you mean multiple processes then yes but generally NO.
For example Apache server runs multiple processes on same port (generally 80).It's done by designating one of the process to actually bind to the port and then use that process to do handovers to various processes which are accepting connections.
Can Selenium interact with an existing browser session?
It is possible. But you have to hack it a little, there is a code
What you have to do is to run stand alone server and "patch" RemoteWebDriver
public class CustomRemoteWebDriver : RemoteWebDriver
{
public static bool newSession;
public static string capPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "TestFiles", "tmp", "sessionCap");
public static string sessiodIdPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "TestFiles", "tmp", "sessionid");
public CustomRemoteWebDriver(Uri remoteAddress)
: base(remoteAddress, new DesiredCapabilities())
{
}
protected override Response Execute(DriverCommand driverCommandToExecute, Dictionary<string, object> parameters)
{
if (driverCommandToExecute == DriverCommand.NewSession)
{
if (!newSession)
{
var capText = File.ReadAllText(capPath);
var sidText = File.ReadAllText(sessiodIdPath);
var cap = JsonConvert.DeserializeObject<Dictionary<string, object>>(capText);
return new Response
{
SessionId = sidText,
Value = cap
};
}
else
{
var response = base.Execute(driverCommandToExecute, parameters);
var dictionary = (Dictionary<string, object>) response.Value;
File.WriteAllText(capPath, JsonConvert.SerializeObject(dictionary));
File.WriteAllText(sessiodIdPath, response.SessionId);
return response;
}
}
else
{
var response = base.Execute(driverCommandToExecute, parameters);
return response;
}
}
}
What does hash do in python?
A hash is an fixed sized integer that identifies a particular value. Each value needs to have its own hash, so for the same value you will get the same hash even if it's not the same object.
>>> hash("Look at me!")
4343814758193556824
>>> f = "Look at me!"
>>> hash(f)
4343814758193556824
Hash values need to be created in such a way that the resulting values are evenly distributed to reduce the number of hash collisions you get. Hash collisions are when two different values have the same hash. Therefore, relatively small changes often result in very different hashes.
>>> hash("Look at me!!")
6941904779894686356
These numbers are very useful, as they enable quick look-up of values in a large collection of values. Two examples of their use are Python's set
and dict
. In a list
, if you want to check if a value is in the list, with if x in values:
, Python needs to go through the whole list and compare x
with each value in the list values
. This can take a long time for a long list
. In a set
, Python keeps track of each hash, and when you type if x in values:
, Python will get the hash-value for x
, look that up in an internal structure and then only compare x
with the values that have the same hash as x
.
The same methodology is used for dictionary lookup. This makes lookup in set
and dict
very fast, while lookup in list
is slow. It also means you can have non-hashable objects in a list
, but not in a set
or as keys in a dict
. The typical example of non-hashable objects is any object that is mutable, meaning that you can change its value. If you have a mutable object it should not be hashable, as its hash then will change over its life-time, which would cause a lot of confusion, as an object could end up under the wrong hash value in a dictionary.
Note that the hash of a value only needs to be the same for one run of Python. In Python 3.3 they will in fact change for every new run of Python:
$ /opt/python33/bin/python3
Python 3.3.2 (default, Jun 17 2013, 17:49:21)
[GCC 4.6.3] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> hash("foo")
1849024199686380661
>>>
$ /opt/python33/bin/python3
Python 3.3.2 (default, Jun 17 2013, 17:49:21)
[GCC 4.6.3] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> hash("foo")
-7416743951976404299
This is to make is harder to guess what hash value a certain string will have, which is an important security feature for web applications etc.
Hash values should therefore not be stored permanently. If you need to use hash values in a permanent way you can take a look at the more "serious" types of hashes, cryptographic hash functions, that can be used for making verifiable checksums of files etc.
git: fatal unable to auto-detect email address
Steps to solve this problem
note: This problem mainly occurs due to which we haven't assigned our user name and email id in git so what we gonna do is assigning it in git
Open git that you have installed
Now we have to assign our user name and email id
Just type git config --user.name <your_name>
and click enter
(you can mention or type any name you want)
Similarly type git config --user.email <[email protected]>
and
click enter (you have to type your primary mail id)
And that's it.
Have a Good Day!!!.
Time stamp in the C programming language
U can try routines in c time library (time.h). Plus take a look at the clock() in the same lib. It gives the clock ticks since the prog has started. But you can save its value before the operation you want to concentrate on, and then after that operation capture the cliock ticks again and find the difference between then to get the time difference.
Git error when trying to push -- pre-receive hook declined
In my case, we have hooks for commit messages, our server script accepts commits if they have the special format for commit message"<JIRA ID><Message>"
. It(hook) declines commit if respective Jira ticket does not exist or there are some special symbols in the commit message. I face this error when I add /, [, > etc. in a commit message, removing those works fine.
How do I set the selenium webdriver get timeout?
Used below code in similar situation
driver.manage().timeouts().pageLoadTimeout(60, TimeUnit.SECONDS);
and embedded driver.get code in a try catch, which solved the issue of loading pages which were taking more than 1 minute.
How to serialize SqlAlchemy result to JSON?
It is not so straighforward. I wrote some code to do this. I'm still working on it, and it uses the MochiKit framework. It basically translates compound objects between Python and Javascript using a proxy and registered JSON converters.
Browser side for database objects is db.js
It needs the basic Python proxy source in proxy.js.
On the Python side there is the base proxy module.
Then finally the SqlAlchemy object encoder in webserver.py.
It also depends on metadata extractors found in the models.py file.
Is there a css cross-browser value for "width: -moz-fit-content;"?
Why not use some br
s?
<div class="mydiv-centerer">
<div class="mydiv">Some content</div><br />
<div class="mydiv">More content than before</div><br />
<div class="mydiv">Here is a lot of content that
I was not anticipating</div>
</div>
CSS
.mydiv-centerer{
text-align: center;
}
.mydiv{
background: none no-repeat scroll 0 0 rgba(1, 56, 110, 0.7);
border-radius: 10px 10px 10px 10px;
box-shadow: 0 0 5px #0099FF;
color: white;
margin: 10px auto;
padding: 10px;
text-align: justify;
display:inline-block;
}
Example: http://jsfiddle.net/YZV25/
How to force an entire layout View refresh?
This is how i used to Refresh my layout
Intent intent = getIntent();
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_NO_ANIMATION);
finish();
startActivity(intent);
Maximum number of records in a MySQL database table
I suggest, never delete data. Don't say if the tables is longer than 1000 truncate the end of the table. There needs to be real business logic in your plan like how long has this user been inactive. For example, if it is longer than 1 year then put them in a different table. You would have this happen weekly or monthly in a maintenance script in the middle of a slow time.
When you run into to many rows in your table then you should start sharding the tables or partitioning and put old data in old tables by year such as users_2011_jan, users_2011_feb or use numbers for the month. Then change your programming to work with this model. Maybe make a new table with less information to summarize the data in less columns and then only refer to the bigger partitioned tables when you need more information such as when the user is viewing their profile. All of this should be considered very carefully so in the future it isn't too expensive to re-factor. You could also put only the users which comes to your site all the time in one table and the users that never come in an archived set of tables.
"relocation R_X86_64_32S against " linking Error
I've got a similar error when installing FCL that needs CCD lib(libccd) like this:
/usr/bin/ld: /usr/local/lib/libccd.a(ccd.o): relocation R_X86_64_32S against `a local symbol' can not be used when making a shared object; recompile with -fPIC
I find that there is two different files named "libccd.a" :
- /usr/local/lib/libccd.a
- /usr/local/lib/x86_64-linux-gnu/libccd.a
I solved the problem by removing the first file.
Inner Joining three tables
try the following code
select * from TableA A
inner join TableB B on A.Column=B.Column
inner join TableC C on A.Column=C.Column
Get query from java.sql.PreparedStatement
If you only want to log the query, then add 'logger' and 'profileSQL' to the jdbc url:
&logger=com.mysql.jdbc.log.Slf4JLogger&profileSQL=true
Then you will get the SQL statement below:
2016-01-14 10:09:43 INFO MySQL - FETCH created: Thu Jan 14 10:09:43 CST 2016 duration: 1 connection: 19130945 statement: 999 resultset: 0
2016-01-14 10:09:43 INFO MySQL - QUERY created: Thu Jan 14 10:09:43 CST 2016 duration: 1 connection: 19130945 statement: 999 resultset: 0 message: SET sql_mode='NO_ENGINE_SUBSTITUTION,STRICT_TRANS_TABLES'
2016-01-14 10:09:43 INFO MySQL - FETCH created: Thu Jan 14 10:09:43 CST 2016 duration: 1 connection: 19130945 statement: 999 resultset: 0
2016-01-14 10:09:43 INFO MySQL - QUERY created: Thu Jan 14 10:09:43 CST 2016 duration: 2 connection: 19130945 statement: 13 resultset: 17 message: select 1
2016-01-14 10:09:43 INFO MySQL - FETCH created: Thu Jan 14 10:09:43 CST 2016 duration: 0 connection: 19130945 statement: 13 resultset: 17
2016-01-14 10:09:43 INFO MySQL - QUERY created: Thu Jan 14 10:09:43 CST 2016 duration: 1 connection: 19130945 statement: 15 resultset: 18 message: select @@session.tx_read_only
2016-01-14 10:09:43 INFO MySQL - FETCH created: Thu Jan 14 10:09:43 CST 2016 duration: 0 connection: 19130945 statement: 15 resultset: 18
2016-01-14 10:09:43 INFO MySQL - QUERY created: Thu Jan 14 10:09:43 CST 2016 duration: 2 connection: 19130945 statement: 14 resultset: 0 message: update sequence set seq=seq+incr where name='demo' and seq=4602
2016-01-14 10:09:43 INFO MySQL - FETCH created: Thu Jan 14 10:09:43 CST 2016 duration: 0 connection: 19130945 statement: 14 resultset: 0
The default logger is:
com.mysql.jdbc.log.StandardLogger
Mysql jdbc property list: https://dev.mysql.com/doc/connector-j/en/connector-j-reference-configuration-properties.html
How to pass data from child component to its parent in ReactJS?
in React v16.8+
function component, you can use useState()
to create a function state that lets you update the parent state, then pass it on to child as a props attribute, then inside the child component you can trigger the parent state function, the following is a working snippet:
_x000D_
_x000D_
const { useState , useEffect } = React;_x000D_
_x000D_
function Timer({ setParentCounter }) {_x000D_
const [counter, setCounter] = React.useState(0);_x000D_
_x000D_
useEffect(() => {_x000D_
let countersystem;_x000D_
countersystem = setTimeout(() => setCounter(counter + 1), 1000);_x000D_
_x000D_
return () => {_x000D_
clearTimeout(countersystem);_x000D_
};_x000D_
}, [counter]);_x000D_
_x000D_
return (_x000D_
<div className="App">_x000D_
<button_x000D_
onClick={() => {_x000D_
setParentCounter(counter);_x000D_
}}_x000D_
>_x000D_
Set parent counter value_x000D_
</button>_x000D_
<hr />_x000D_
<div>Child Counter: {counter}</div>_x000D_
</div>_x000D_
);_x000D_
}_x000D_
_x000D_
function App() {_x000D_
const [parentCounter, setParentCounter] = useState(0);_x000D_
_x000D_
return (_x000D_
<div className="App">_x000D_
Parent Counter: {parentCounter}_x000D_
<hr />_x000D_
<Timer setParentCounter={setParentCounter} />_x000D_
</div>_x000D_
);_x000D_
}_x000D_
_x000D_
ReactDOM.render(<App />, document.getElementById('react-root'));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>_x000D_
<div id="react-root"></div>
_x000D_
_x000D_
_x000D_
"if not exist" command in batch file
When testing for directories remember that every directory contains two special files.
One is called '.' and the other '..'
. is the directory's own name while .. is the name of it's parent directory.
To avoid trailing backslash problems just test to see if the directory knows it's own name.
eg:
if not exist %temp%\buffer\. mkdir %temp%\buffer
Merge up to a specific commit
Run below command into the current branch folder to merge from this <commit-id>
to current branch, --no-commit
do not make a new commit automatically
git merge --no-commit <commit-id>
git merge --continue
can only be run after the merge has resulted in conflicts.
git merge --abort
Abort the current conflict resolution process, and try to reconstruct the pre-merge state.
Enabling the OpenSSL in XAMPP
Yes, you must open php.ini
and remove the semicolon to:
;extension=php_openssl.dll
If you don't have that line, check that you have the file (In my PC is on D:\xampp\php\ext
) and add this to php.ini
in the "Dynamic Extensions" section:
extension=php_openssl.dll
Things have changed for PHP > 7. This is what i had to do for PHP 7.2.
Step: 1: Uncomment extension=openssl
Step: 2: Uncomment extension_dir = "ext"
Step: 3: Restart xampp.
Done.
Explanation: ( From php.ini )
If you wish to have an extension loaded automatically, use the following syntax:
extension=modulename
Note : The syntax used in previous PHP versions (extension=<ext>.so
and extension='php_<ext>.dll
) is supported for legacy reasons and may be deprecated in a future PHP major version. So, when it is possible, please move to the new (extension=<ext>
) syntax.
Special Note: Be sure to appropriately set the extension_dir
directive.
Can a CSV file have a comment?
In engineering data, it is common to see the #
symbol in the first column used to signal a comment.
I use the ostermiller CSV parsing library for Java to read and process such files. That library allows you to set the comment character. After the parse operation you get an array just containing the real data, no comments.
String concatenation in Jinja
Just another hack can be like this.
I have Array of strings which I need to concatenate. So I added that array into dictionary and then used it inside for loop which worked.
{% set dict1 = {'e':''} %}
{% for i in list1 %}
{% if dict1.update({'e':dict1.e+":"+i+"/"+i}) %} {% endif %}
{% endfor %}
{% set layer_string = dict1['e'] %}
Explain ExtJS 4 event handling
Firing application wide events
How to make controllers talk to each other ...
In addition to the very great answer above I want to mention application wide events which can be very useful in an MVC setup to enable communication between controllers. (extjs4.1)
Lets say we have a controller Station (Sencha MVC examples) with a select box:
Ext.define('Pandora.controller.Station', {
extend: 'Ext.app.Controller',
...
init: function() {
this.control({
'stationslist': {
selectionchange: this.onStationSelect
},
...
});
},
...
onStationSelect: function(selModel, selection) {
this.application.fireEvent('stationstart', selection[0]);
},
...
});
When the select box triggers a change event, the function onStationSelect
is fired.
Within that function we see:
this.application.fireEvent('stationstart', selection[0]);
This creates and fires an application wide event that we can listen to from any other controller.
Thus in another controller we can now know when the station select box has been changed. This is done through listening to this.application.on
as follows:
Ext.define('Pandora.controller.Song', {
extend: 'Ext.app.Controller',
...
init: function() {
this.control({
'recentlyplayedscroller': {
selectionchange: this.onSongSelect
}
});
// Listen for an application wide event
this.application.on({
stationstart: this.onStationStart,
scope: this
});
},
....
onStationStart: function(station) {
console.info('I called to inform you that the Station controller select box just has been changed');
console.info('Now what do you want to do next?');
},
}
If the selectbox has been changed we now fire the function onStationStart
in the controller Song
also ...
From the Sencha docs:
Application events are extremely useful for events that have many controllers. Instead of listening for the same view event in each of these controllers, only one controller listens for the view event and fires an application-wide event that the others can listen for. This also allows controllers to communicate with one another without knowing about or depending on each other’s existence.
In my case: Clicking on a tree node to update data in a grid panel.
Update 2016 thanks to @gm2008 from the comments below:
In terms of firing application-wide custom events, there is a new method now after ExtJS V5.1 is published, which is using Ext.GlobalEvents
.
When you fire events, you can call: Ext.GlobalEvents.fireEvent('custom_event');
When you register a handler of the event, you call: Ext.GlobalEvents.on('custom_event', function(arguments){/* handler codes*/}, scope);
This method is not limited to controllers. Any component can handle a custom event through putting the component object as the input parameter scope.
Found in Sencha Docs: MVC Part 2
Create a date from day month and year with T-SQL
I personally Prefer Substring as it provide cleansing options and ability to split the string as needed. The assumption is that the data is of the format 'dd, mm, yyyy'.
--2012 and above
SELECT CONCAT (
RIGHT(REPLACE(@date, ' ', ''), 4)
,'-'
,RIGHT(CONCAT('00',SUBSTRING(REPLACE(@date, ' ', ''), CHARINDEX(',', REPLACE(@date, ' ', '')) + 1, LEN(REPLACE(@date, ' ', '')) - CHARINDEX(',', REPLACE(@date, ' ', '')) - 5)),2)
,'-'
,RIGHT(CONCAT('00',SUBSTRING(REPLACE(@date, ' ', ''), 1, CHARINDEX(',', REPLACE(@date, ' ', '')) - 1)),2)
)
--2008 and below
SELECT RIGHT(REPLACE(@date, ' ', ''), 4)
+'-'
+RIGHT('00'+SUBSTRING(REPLACE(@date, ' ', ''), CHARINDEX(',', REPLACE(@date, ' ', '')) + 1, LEN(REPLACE(@date, ' ', '')) - CHARINDEX(',', REPLACE(@date, ' ', '')) - 5),2)
+'-'
+RIGHT('00'+SUBSTRING(REPLACE(@date, ' ', ''), 1, CHARINDEX(',', REPLACE(@date, ' ', '')) - 1),2)
Here is a demonstration of how it can be sued if the data is stored in a column. Needless to say, its ideal to check the result-set before applying to the column
DECLARE @Table TABLE (ID INT IDENTITY(1000,1), DateString VARCHAR(50), DateColumn DATE)
INSERT INTO @Table
SELECT'12, 1, 2007',NULL
UNION
SELECT'15,3, 2007',NULL
UNION
SELECT'18, 11 , 2007',NULL
UNION
SELECT'22 , 11, 2007',NULL
UNION
SELECT'30, 12, 2007 ',NULL
UPDATE @Table
SET DateColumn = CONCAT (
RIGHT(REPLACE(DateString, ' ', ''), 4)
,'-'
,RIGHT(CONCAT('00',SUBSTRING(REPLACE(DateString, ' ', ''), CHARINDEX(',', REPLACE(DateString, ' ', '')) + 1, LEN(REPLACE(DateString, ' ', '')) - CHARINDEX(',', REPLACE(DateString, ' ', '')) - 5)),2)
,'-'
,RIGHT(CONCAT('00',SUBSTRING(REPLACE(DateString, ' ', ''), 1, CHARINDEX(',', REPLACE(DateString, ' ', '')) - 1)),2)
)
SELECT ID,DateString,DateColumn
FROM @Table
What is a web service endpoint?
Simply put, an endpoint is one end of a communication channel. When an API interacts with another system, the touch-points of this communication are considered endpoints. For APIs, an endpoint can include a URL of a server or service. Each endpoint is the location from which APIs can access the resources they need to carry out their function.
APIs work using ‘requests’ and ‘responses.’ When an API requests information from a web application or web server, it will receive a response. The place that APIs send requests and where the resource lives, is called an endpoint.
Reference:
https://smartbear.com/learn/performance-monitoring/api-endpoints/
Angular2 Routing with Hashtag to page anchor
Use this for the router module in app-routing.module.ts
:
@NgModule({
imports: [RouterModule.forRoot(routes, {
useHash: true,
scrollPositionRestoration: 'enabled',
anchorScrolling: 'enabled',
scrollOffset: [0, 64]
})],
exports: [RouterModule]
})
This will be in your HTML:
<a href="#/users/123#userInfo">
How to change the current URL in javascript?
What you're doing is appending a "1" (the string) to your URL. If you want page 1.html link to page 2.html you need to take the 1 out of the string, add one to it, then reassemble the string.
Why not do something like this:
var url = 'http://mywebsite.com/1.html';
var pageNum = parseInt( url.split("/").pop(),10 );
var nextPage = 'http://mywebsite.com/'+(pageNum+1)+'.html';
nextPage will contain the url http://mywebsite.com/2.html in this case. Should be easy to put in a function if needed.
What is the Java equivalent of PHP var_dump?
Your alternatives are to override the toString()
method of your object to output its contents in a way that you like, or to use reflection to inspect the object (in a way similar to what debuggers do).
The advantage of using reflection is that you won't need to modify your individual objects to be "analysable", but there is added complexity and if you need nested object support you'll have to write that.
This code will list the fields and their values for an Object
"o"
Field[] fields = o.getClass().getDeclaredFields();
for (int i=0; i<fields.length; i++)
{
System.out.println(fields[i].getName() + " - " + fields[i].get(o));
}
Showing an image from console in Python
In a new window using Pillow/PIL
Install Pillow (or PIL), e.g.:
$ pip install pillow
Now you can
from PIL import Image
with Image.open('path/to/file.jpg') as img:
img.show()
Using native apps
Other common alternatives include running xdg-open
or starting the browser with the image path:
import webbrowser
webbrowser.open('path/to/file.jpg')
Inline a Linux console
If you really want to show the image inline in the console and not as a new window, you may do that but only in a Linux console using fbi
see ask Ubuntu or else use ASCII-art like CACA.
LINQ equivalent of foreach for IEnumerable<T>
Many people mentioned it, but I had to write it down. Isn't this most clear/most readable?
IEnumerable<Item> items = GetItems();
foreach (var item in items) item.DoStuff();
Short and simple(st).
MongoDB Data directory /data/db not found
MongoDB needs data directory to store data.
Default path is /data/db
When you start MongoDB engine, it searches this directory which is missing in your case. Solution is create this directory and assign rwx
permission to user.
If you want to change the path of your data directory then you should specify it while starting mongod server like,
mongod --dbpath /data/<path> --port <port no>
This should help you start your mongod server with custom path and port.
How can I read an input string of unknown length?
Read directly into allocated space with fgets()
.
Special care is need to distinguish a successful read, end-of-file, input error and out-of memory. Proper memory management needed on EOF.
This method retains a line's '\n'
.
#include <stdio.h>
#include <stdlib.h>
#define FGETS_ALLOC_N 128
char* fgets_alloc(FILE *istream) {
char* buf = NULL;
size_t size = 0;
size_t used = 0;
do {
size += FGETS_ALLOC_N;
char *buf_new = realloc(buf, size);
if (buf_new == NULL) {
// Out-of-memory
free(buf);
return NULL;
}
buf = buf_new;
if (fgets(&buf[used], (int) (size - used), istream) == NULL) {
// feof or ferror
if (used == 0 || ferror(istream)) {
free(buf);
buf = NULL;
}
return buf;
}
size_t length = strlen(&buf[used]);
if (length + 1 != size - used) break;
used += length;
} while (buf[used - 1] != '\n');
return buf;
}
Sample usage
int main(void) {
FILE *istream = stdin;
char *s;
while ((s = fgets_alloc(istream)) != NULL) {
printf("'%s'", s);
free(s);
fflush(stdout);
}
if (ferror(istream)) {
puts("Input error");
} else if (feof(istream)) {
puts("End of file");
} else {
puts("Out of memory");
}
return 0;
}
How to use background thread in swift?
Since the OP question has already been answered above I just want to add some speed considerations:
I don't recommend running tasks with the .background thread priority especially on the iPhone X where the task seems to be allocated on the low power cores.
Here is some real data from a computationally intensive function that reads from an XML file (with buffering) and performs data interpolation:
Device name / .background / .utility / .default / .userInitiated / .userInteractive
- iPhone X: 18.7s / 6.3s / 1.8s / 1.8s / 1.8s
- iPhone 7: 4.6s / 3.1s / 3.0s / 2.8s / 2.6s
- iPhone 5s: 7.3s / 6.1s / 4.0s / 4.0s / 3.8s
Note that the data set is not the same for all devices. It's the biggest on the iPhone X and the smallest on the iPhone 5s.
Passing arguments to "make run"
I don't know a way to do what you want exactly, but a workaround might be:
run: ./prog
./prog $(ARGS)
Then:
make ARGS="asdf" run
# or
make run ARGS="asdf"
Bootstrap Dropdown with Hover
Try this using hover function with fadein fadeout animations
$('ul.nav li.dropdown').hover(function() {
$(this).find('.dropdown-menu').stop(true, true).delay(200).fadeIn(500);
}, function() {
$(this).find('.dropdown-menu').stop(true, true).delay(200).fadeOut(500);
});
XSLT string replace
Note: In case you wish to use the already-mentioned algo for cases where you need to replace huge number of instances in the source string (e.g. new lines in long text) there is high probability you'll end up with StackOverflowException
because of the recursive call.
I resolved this issue thanks to Xalan's (didn't look how to do it in Saxon) built-in Java type embedding:
<xsl:stylesheet version="1.0" exclude-result-prefixes="xalan str"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xalan="http://xml.apache.org/xalan"
xmlns:str="xalan://java.lang.String"
>
...
<xsl:value-of select="str:replaceAll(
str:new(text()),
$search_string,
$replace_string)"/>
...
</xsl:stylesheet>
Negation in Python
Python prefers English keywords to punctuation. Use not x
, i.e. not os.path.exists(...)
. The same thing goes for &&
and ||
which are and
and or
in Python.
How to get client IP address using jQuery
<html lang="en">
<head>
<title>Jquery - get ip address</title>
<script type="text/javascript" src="//cdn.jsdelivr.net/jquery/1/jquery.min.js"></script>
</head>
<body>
<h1>Your Ip Address : <span class="ip"></span></h1>
<script type="text/javascript">
$.getJSON("http://jsonip.com?callback=?", function (data) {
$(".ip").text(data.ip);
});
</script>
</body>
</html>
I want to multiply two columns in a pandas DataFrame and add the result into a new column
If we're willing to sacrifice the succinctness of Hayden's solution, one could also do something like this:
In [22]: orders_df['C'] = orders_df.Action.apply(
lambda x: (1 if x == 'Sell' else -1))
In [23]: orders_df # New column C represents the sign of the transaction
Out[23]:
Prices Amount Action C
0 3 57 Sell 1
1 89 42 Sell 1
2 45 70 Buy -1
3 6 43 Sell 1
4 60 47 Sell 1
5 19 16 Buy -1
6 56 89 Sell 1
7 3 28 Buy -1
8 56 69 Sell 1
9 90 49 Buy -1
Now we have eliminated the need for the if
statement. Using DataFrame.apply()
, we also do away with the for
loop. As Hayden noted, vectorized operations are always faster.
In [24]: orders_df['Value'] = orders_df.Prices * orders_df.Amount * orders_df.C
In [25]: orders_df # The resulting dataframe
Out[25]:
Prices Amount Action C Value
0 3 57 Sell 1 171
1 89 42 Sell 1 3738
2 45 70 Buy -1 -3150
3 6 43 Sell 1 258
4 60 47 Sell 1 2820
5 19 16 Buy -1 -304
6 56 89 Sell 1 4984
7 3 28 Buy -1 -84
8 56 69 Sell 1 3864
9 90 49 Buy -1 -4410
This solution takes two lines of code instead of one, but is a bit easier to read. I suspect that the computational costs are similar as well.
How do you clear the SQL Server transaction log?
DISCLAIMER: Please read comments below carefully, and I assume you've already read the accepted answer. As I said nearly 5 years ago:
if anyone has any comments to add for situations when this is NOT an
adequate or optimal solution then please comment below
I usually open the Windows Explorer directory containing the database files, so I can immediately see the effect.
I was actually quite surprised this worked! Normally I've used DBCC before, but I just tried that and it didn't shrink anything, so I tried the GUI (2005) and it worked great - freeing up 17 GB in 10 seconds
In Full recovery mode this might not work, so you have to either back up the log first, or change to Simple recovery, then shrink the file. [thanks @onupdatecascade for this]
--
PS: I appreciate what some have commented regarding the dangers of this, but in my environment I didn't have any issues doing this myself especially since I always do a full backup first. So please take into consideration what your environment is, and how this affects your backup strategy and job security before continuing. All I was doing was pointing people to a feature provided by Microsoft!
PHPMailer: SMTP Error: Could not connect to SMTP host
I had the same problem and it was because PHPMailer realized the server supported STARTTLS so it tried to automatically upgrade the connection to an encrypted connection. My mail server is on the same subnet as the web server within my network which is all behind our domain firewalls so I'm not too worried about using encryption (plus the generated emails don't contain sensitive data anyway).
So what I went ahead and did was change the SMTPAutoTLS to false in the class.phpmailer.php file.
/**
* Whether to enable TLS encryption automatically if a server supports it,
* even if `SMTPSecure` is not set to 'tls'.
* Be aware that in PHP >= 5.6 this requires that the server's certificates are valid.
* @var boolean
*/
public $SMTPAutoTLS = false;
file_get_contents("php://input") or $HTTP_RAW_POST_DATA, which one is better to get the body of JSON request?
file_get_contents(php://input) - gets the raw POST data and you need to use this when you write APIs and need XML/JSON/... input that cannot be decoded to $_POST by PHP
some example :
send by post JSON string
<input type="button" value= "click" onclick="fn()">
<script>
function fn(){
var js_obj = {plugin: 'jquery-json', version: 2.3};
var encoded = JSON.stringify( js_obj );
var data= encoded
$.ajax({
type: "POST",
url: '1.php',
data: data,
success: function(data){
console.log(data);
}
});
}
</script>
1.php
//print_r($_POST); //empty!!! don't work ...
var_dump( file_get_contents('php://input'));
Communication between multiple docker-compose projects
You just need to make sure that the containers you want to talk to each other are on the same network. Networks are a first-class docker construct, and not specific to compose.
# front/docker-compose.yml
version: '2'
services:
front:
...
networks:
- some-net
networks:
some-net:
driver: bridge
...
# api/docker-compose.yml
version: '2'
services:
api:
...
networks:
- front_some-net
networks:
front_some-net:
external: true
Note: Your app’s network is given a name based on the “project name”, which is based on the name of the directory it lives in, in this case a prefix front_
was added
They can then talk to each other using the service name. From front
you can do ping api
and vice versa.
How do you determine the size of a file in C?
Based on NilObject's code:
#include <sys/stat.h>
#include <sys/types.h>
off_t fsize(const char *filename) {
struct stat st;
if (stat(filename, &st) == 0)
return st.st_size;
return -1;
}
Changes:
- Made the filename argument a
const char
.
- Corrected the
struct stat
definition, which was missing the variable name.
- Returns
-1
on error instead of 0
, which would be ambiguous for an empty file. off_t
is a signed type so this is possible.
If you want fsize()
to print a message on error, you can use this:
#include <sys/stat.h>
#include <sys/types.h>
#include <string.h>
#include <stdio.h>
#include <errno.h>
off_t fsize(const char *filename) {
struct stat st;
if (stat(filename, &st) == 0)
return st.st_size;
fprintf(stderr, "Cannot determine size of %s: %s\n",
filename, strerror(errno));
return -1;
}
On 32-bit systems you should compile this with the option -D_FILE_OFFSET_BITS=64
, otherwise off_t
will only hold values up to 2 GB. See the "Using LFS" section of Large File Support in Linux for details.
Add new column with foreign key constraint in one command
As so often with SQL-related question, it depends on the DBMS. Some DBMS allow you to combine ALTER table operations separated by commas. For example...
Informix syntax:
ALTER TABLE one
ADD two_id INTEGER,
ADD CONSTRAINT FOREIGN KEY(two_id) REFERENCES two(id);
The syntax for IBM DB2 LUW is similar, repeating the keyword ADD but (if I read the diagram correctly) not requiring a comma to separate the added items.
Microsoft SQL Server syntax:
ALTER TABLE one
ADD two_id INTEGER,
FOREIGN KEY(two_id) REFERENCES two(id);
Some others do not allow you to combine ALTER TABLE operations like that. Standard SQL only allows a single operation in the ALTER TABLE statement, so in Standard SQL, it has to be done in two steps.
Retrofit 2.0 how to get deserialised error response.body
I did it this way for asynchronous calls using Retrofit 2.0-beta2:
@Override
public void onResponse(Response<RegistrationResponse> response,
Retrofit retrofit) {
if (response.isSuccess()) {
// Do success handling here
} else {
try {
MyError myError = (MyError)retrofit.responseConverter(
MyError.class, MyError.class.getAnnotations())
.convert(response.errorBody());
// Do error handling here
} catch (IOException e) {
e.printStackTrace();
}
}
}
ORA-06508: PL/SQL: could not find program unit being called
Based on previous answers. I resolved my issue by removing global variable at package level to procedure, since there was no impact in my case.
Original script was
create or replace PACKAGE BODY APPLICATION_VALIDATION AS
V_ERROR_NAME varchar2(200) := '';
PROCEDURE APP_ERROR_X47_VALIDATION ( PROCESS_ID IN VARCHAR2 ) AS BEGIN
------ rules for validation... END APP_ERROR_X47_VALIDATION ;
/* Some more code
*/
END APPLICATION_VALIDATION; /
Rewritten the same without global variable V_ERROR_NAME
and moved to procedure under package level as
Modified Code
create or replace PACKAGE BODY APPLICATION_VALIDATION AS
PROCEDURE APP_ERROR_X47_VALIDATION ( PROCESS_ID IN VARCHAR2 ) AS
**V_ERROR_NAME varchar2(200) := '';**
BEGIN
------ rules for validation... END APP_ERROR_X47_VALIDATION ;
/* Some more code
*/
END APPLICATION_VALIDATION; /
Difference between return and exit in Bash functions
Remember, functions are internal to a script and normally return from whence they were called by using the return statement. Calling an external script is another matter entirely, and scripts usually terminate with an exit statement.
The difference "between the return and exit statement in Bash functions with respect to exit codes" is very small. Both return a status, not values per se. A status of zero indicates success, while any other status (1 to 255) indicates a failure. The return statement will return to the script from where it was called, while the exit statement will end the entire script from wherever it is encountered.
return 0 # Returns to where the function was called. $? contains 0 (success).
return 1 # Returns to where the function was called. $? contains 1 (failure).
exit 0 # Exits the script completely. $? contains 0 (success).
exit 1 # Exits the script completely. $? contains 1 (failure).
If your function simply ends without a return statement, the status of the last command executed is returned as the status code (and will be placed in $?
).
Remember, return and exit give back a status code from 0 to 255, available in $?
. You cannot stuff anything else into a status code (e.g., return "cat"); it will not work. But, a script can pass back 255 different reasons for failure by using status codes.
You can set variables contained in the calling script, or echo results in the function and use command substitution in the calling script; but the purpose of return and exit are to pass status codes, not values or computation results as one might expect in a programming language like C.
Converting float to char*
typedef union{
float a;
char b[4];
} my_union_t;
You can access to float data value byte by byte and send it through 8-bit output buffer (e.g. USART) without casting.
How to change the color of text in javafx TextField?
Setting the -fx-text-fill
works for me.
See below:
if (passed) {
resultInfo.setText("Passed!");
resultInfo.setStyle("-fx-text-fill: green; -fx-font-size: 16px;");
} else {
resultInfo.setText("Failed!");
resultInfo.setStyle("-fx-text-fill: red; -fx-font-size: 16px;");
}
What's NSLocalizedString equivalent in Swift?
Localization with default language:
extension String {
func localized() -> String {
let defaultLanguage = "en"
let path = Bundle.main.path(forResource: defaultLanguage, ofType: "lproj")
let bundle = Bundle(path: path!)
return NSLocalizedString(self, tableName: nil, bundle: bundle!, value: "", comment: "")
}
}
Using for loop inside of a JSP
Do this
<% for(int i = 0; i < allFestivals.size(); i+=1) { %>
<tr>
<td><%=allFestivals.get(i).getFestivalName()%></td>
</tr>
<% } %>
Better way is to use c:foreach see link jstl for each
Using arrays or std::vectors in C++, what's the performance gap?
Assuming a fixed-length array (e.g. int* v = new int[1000];
vs std::vector<int> v(1000);
, with the size of v
being kept fixed at 1000), the only performance consideration that really matters (or at least mattered to me when I was in a similar dilemma) is the speed of access to an element. I looked up the STL's vector code, and here is what I found:
const_reference
operator[](size_type __n) const
{ return *(this->_M_impl._M_start + __n); }
This function will most certainly be inlined by the compiler. So, as long as the only thing that you plan to do with v
is access its elements with operator[]
, it seems like there shouldn't really be any difference in performance.
Uploading Images to Server android
Main activity class to take pick and upload
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
//import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
public class MainActivity extends Activity {
Button btpic, btnup;
private Uri fileUri;
String picturePath;
Uri selectedImage;
Bitmap photo;
String ba1;
public static String URL = "Paste your URL here";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btpic = (Button) findViewById(R.id.cpic);
btpic.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
clickpic();
}
});
btnup = (Button) findViewById(R.id.up);
btnup.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
upload();
}
});
}
private void upload() {
// Image location URL
Log.e("path", "----------------" + picturePath);
// Image
Bitmap bm = BitmapFactory.decodeFile(picturePath);
ByteArrayOutputStream bao = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 90, bao);
byte[] ba = bao.toByteArray();
//ba1 = Base64.encodeBytes(ba);
Log.e("base64", "-----" + ba1);
// Upload image to server
new uploadToServer().execute();
}
private void clickpic() {
// Check Camera
if (getApplicationContext().getPackageManager().hasSystemFeature(
PackageManager.FEATURE_CAMERA)) {
// Open default camera
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
// start the image capture Intent
startActivityForResult(intent, 100);
} else {
Toast.makeText(getApplication(), "Camera not supported", Toast.LENGTH_LONG).show();
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 100 && resultCode == RESULT_OK) {
selectedImage = data.getData();
photo = (Bitmap) data.getExtras().get("data");
// Cursor to get image uri to display
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
picturePath = cursor.getString(columnIndex);
cursor.close();
Bitmap photo = (Bitmap) data.getExtras().get("data");
ImageView imageView = (ImageView) findViewById(R.id.Imageprev);
imageView.setImageBitmap(photo);
}
}
public class uploadToServer extends AsyncTask<Void, Void, String> {
private ProgressDialog pd = new ProgressDialog(MainActivity.this);
protected void onPreExecute() {
super.onPreExecute();
pd.setMessage("Wait image uploading!");
pd.show();
}
@Override
protected String doInBackground(Void... params) {
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("base64", ba1));
nameValuePairs.add(new BasicNameValuePair("ImageName", System.currentTimeMillis() + ".jpg"));
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(URL);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
String st = EntityUtils.toString(response.getEntity());
Log.v("log_tag", "In the try Loop" + st);
} catch (Exception e) {
Log.v("log_tag", "Error in http connection " + e.toString());
}
return "Success";
}
protected void onPostExecute(String result) {
super.onPostExecute(result);
pd.hide();
pd.dismiss();
}
}
}
php code to handle upload image and also create image from base64 encoded data
<?php
error_reporting(E_ALL);
if(isset($_POST['ImageName'])){
$imgname = $_POST['ImageName'];
$imsrc = base64_decode($_POST['base64']);
$fp = fopen($imgname, 'w');
fwrite($fp, $imsrc);
if(fclose($fp)){
echo "Image uploaded";
}else{
echo "Error uploading image";
}
}
?>
don't fail jenkins build if execute shell fails
This answer is correct, but it doesn't specify the || exit 0
or || true
goes inside the shell command. Here's a more complete example:
sh "adb uninstall com.example.app || true"
The above will work, but the following will fail:
sh "adb uninstall com.example.app" || true
Perhaps it's obvious to others, but I wasted a lot of time before I realized this.
Using a cursor with dynamic SQL in a stored procedure
Working with a non-relational database (IDMS anyone?) over an ODBC connection qualifies as one of those times where cursors and dynamic SQL seems the only route.
select * from a where a=1 and b in (1,2)
takes 45 minutes to respond while re-written to use keysets without the in clause will run in under 1 second:
select * from a where (a=1 and b=1)
union all
select * from a where (a=1 and b=2)
If the in statement for column B contains 1145 rows, using a cursor to create indidivudal statements and execute them as dynamic SQL is far faster than using the in clause. Silly hey?
And yes, there's no time in a relational database that cursor's should be used. I just can't believe I've come across an instance where a cursor loop is several magnitudes quicker.
How to convert .crt to .pem
I found the OpenSSL answer given above didn't work for me, but the following did, working with a CRT file sourced from windows.
openssl x509 -inform DER -in yourdownloaded.crt -out outcert.pem -text
Global variables in AngularJS
You can also use the environment variable $window
so that a global variable declare outside a controller can be checked inside a $watch
var initWatch = function($scope,$window){
$scope.$watch(function(scope) { return $window.globalVar },
function(newValue) {
$scope.updateDisplayedVar(newValue);
});
}
Becareful, the digest cycle is longer with these global values, so it is not always real-timed updated. I need to investigate on that digest time with this configuration.
INFO: No Spring WebApplicationInitializer types detected on classpath
I found the error:
I have a library that it was built using jdk 1.6. The Spring main controller and components are in this library. And how I use jdk 1.7, It does not find the classes built in 1.6.
The solution was built all using "compiler compliance level: 1.7" and "Generated .class files compatibility: 1.6", "Source compatibility: 1.6".
I setup this option in Eclipse:
Preferences\Java\Compiler.
Thanks everybody.
Postgresql SELECT if string contains
A proper way to search for a substring is to use position
function instead of like
expression, which requires escaping %
, _
and an escape character (\
by default):
SELECT id FROM TAG_TABLE WHERE position(tag_name in 'aaaaaaaaaaa')>0;
Laravel blade check empty foreach
Using following code, one can first check variable is set or not using @isset of laravel directive and then check that array is blank or not using @unless of laravel directive
@if(@isset($names))
@unless($names)
Array has no value
@else
Array has value
@foreach($names as $name)
{{$name}}
@endforeach
@endunless
@else
Not defined
@endif
Use -notlike to filter out multiple strings in PowerShell
Scenario:
List all computers beginning with XX1 but not names where 4th character is L or P
Get-ADComputer -Filter {(name -like "XX1*")} | Select Name | Where {($_.name -notlike "XX1L*" -and $_.name -notlike "XX1P*")}
You can also count them by enclosing the above script in parens and adding a .count method like so:
(Get-ADComputer -Filter {(name -like "XX1*")} | Select Name | Where {($_.name -notlike "XX1L*" -and $_.name -notlike "XX1P*")}).count
What does [STAThread] do?
The STAThreadAttribute
is essentially a requirement for the Windows message pump to communicate with COM components. Although core Windows Forms does not use COM, many components of the OS such as system dialogs do use this technology.
MSDN explains the reason in slightly more detail:
STAThreadAttribute indicates that the
COM threading model for the
application is single-threaded
apartment. This attribute must be
present on the entry point of any
application that uses Windows Forms;
if it is omitted, the Windows
components might not work correctly.
If the attribute is not present, the
application uses the multithreaded
apartment model, which is not
supported for Windows Forms.
This blog post (Why is STAThread required?) also explains the requirement quite well. If you want a more in-depth view as to how the threading model works at the CLR level, see this MSDN Magazine article from June 2004 (Archived, Apr. 2009).
Breaking out of nested loops
Use itertools.product!
from itertools import product
for x, y in product(range(10), range(10)):
#do whatever you want
break
Here's a link to itertools.product in the python documentation:
http://docs.python.org/library/itertools.html#itertools.product
You can also loop over an array comprehension with 2 fors in it, and break whenever you want to.
>>> [(x, y) for y in ['y1', 'y2'] for x in ['x1', 'x2']]
[
('x1', 'y1'), ('x2', 'y1'),
('x1', 'y2'), ('x2', 'y2')
]
remove legend title in ggplot
You were almost there : just add theme(legend.title=element_blank())
ggplot(df, aes(x, y, colour=g)) +
geom_line(stat="identity") +
theme(legend.position="bottom") +
theme(legend.title=element_blank())
This page on Cookbook for R gives plenty of details on how to customize legends.
Max length for client ip address
For IPv4, you could get away with storing the 4 raw bytes of the IP address (each of the numbers between the periods in an IP address are 0-255, i.e., one byte). But then you would have to translate going in and out of the DB and that's messy.
IPv6 addresses are 128 bits (as opposed to 32 bits of IPv4 addresses). They are usually written as 8 groups of 4 hex digits separated by colons: 2001:0db8:85a3:0000:0000:8a2e:0370:7334
. 39 characters is appropriate to store IPv6 addresses in this format.
Edit: However, there is a caveat, see @Deepak's answer for details about IPv4-mapped IPv6 addresses. (The correct maximum IPv6 string length is 45 characters.)
What does numpy.random.seed(0) do?
If you set the np.random.seed(a_fixed_number)
every time you call the numpy's other random function, the result will be the same:
>>> import numpy as np
>>> np.random.seed(0)
>>> perm = np.random.permutation(10)
>>> print perm
[2 8 4 9 1 6 7 3 0 5]
>>> np.random.seed(0)
>>> print np.random.permutation(10)
[2 8 4 9 1 6 7 3 0 5]
>>> np.random.seed(0)
>>> print np.random.permutation(10)
[2 8 4 9 1 6 7 3 0 5]
>>> np.random.seed(0)
>>> print np.random.permutation(10)
[2 8 4 9 1 6 7 3 0 5]
>>> np.random.seed(0)
>>> print np.random.rand(4)
[0.5488135 0.71518937 0.60276338 0.54488318]
>>> np.random.seed(0)
>>> print np.random.rand(4)
[0.5488135 0.71518937 0.60276338 0.54488318]
However, if you just call it once and use various random functions, the results will still be different:
>>> import numpy as np
>>> np.random.seed(0)
>>> perm = np.random.permutation(10)
>>> print perm
[2 8 4 9 1 6 7 3 0 5]
>>> np.random.seed(0)
>>> print np.random.permutation(10)
[2 8 4 9 1 6 7 3 0 5]
>>> print np.random.permutation(10)
[3 5 1 2 9 8 0 6 7 4]
>>> print np.random.permutation(10)
[2 3 8 4 5 1 0 6 9 7]
>>> print np.random.rand(4)
[0.64817187 0.36824154 0.95715516 0.14035078]
>>> print np.random.rand(4)
[0.87008726 0.47360805 0.80091075 0.52047748]
How Stuff and 'For Xml Path' work in SQL Server?
This article covers various ways of concatenating strings in SQL, including an improved version of your code which doesn't XML-encode the concatenated values.
SELECT ID, abc = STUFF
(
(
SELECT ',' + name
FROM temp1 As T2
-- You only want to combine rows for a single ID here:
WHERE T2.ID = T1.ID
ORDER BY name
FOR XML PATH (''), TYPE
).value('.', 'varchar(max)')
, 1, 1, '')
FROM temp1 As T1
GROUP BY id
To understand what's happening, start with the inner query:
SELECT ',' + name
FROM temp1 As T2
WHERE T2.ID = 42 -- Pick a random ID from the table
ORDER BY name
FOR XML PATH (''), TYPE
Because you're specifying FOR XML
, you'll get a single row containing an XML fragment representing all of the rows.
Because you haven't specified a column alias for the first column, each row would be wrapped in an XML element with the name specified in brackets after the FOR XML PATH
. For example, if you had FOR XML PATH ('X')
, you'd get an XML document that looked like:
<X>,aaa</X>
<X>,bbb</X>
...
But, since you haven't specified an element name, you just get a list of values:
,aaa,bbb,...
The .value('.', 'varchar(max)')
simply retrieves the value from the resulting XML fragment, without XML-encoding any "special" characters. You now have a string that looks like:
',aaa,bbb,...'
The STUFF
function then removes the leading comma, giving you a final result that looks like:
'aaa,bbb,...'
It looks quite confusing at first glance, but it does tend to perform quite well compared to some of the other options.
The project cannot be built until the build path errors are resolved.
1-Right CLick on your project folder, Choose Build Path > Configure Build Path
2-Select Libraries Tab and delete any arbitrary library present there.
3-Click on Add Library option, Select JRE System Library and click Next.
4-Choose last Radiobutton option Workspace default JRE and click Finish.
5-press f5 for refresh.
6-run ur program .
How to implement Enums in Ruby?
Sometimes all I need is to be able to fetch enum's value and identify its name similar to java world.
module Enum
def get_value(str)
const_get(str)
end
def get_name(sym)
sym.to_s.upcase
end
end
class Fruits
include Enum
APPLE = "Delicious"
MANGO = "Sweet"
end
Fruits.get_value('APPLE') #'Delicious'
Fruits.get_value('MANGO') # 'Sweet'
Fruits.get_name(:apple) # 'APPLE'
Fruits.get_name(:mango) # 'MANGO'
This to me serves the purpose of enum and keeps it very extensible too. You can add more methods to the Enum class and viola get them for free in all the defined enums. for example. get_all_names and stuff like that.
Display images in asp.net mvc
It is possible to use a handler to do this, even in MVC4. Here's an example from one i made earlier:
public class ImageHandler : IHttpHandler
{
byte[] bytes;
public void ProcessRequest(HttpContext context)
{
int param;
if (int.TryParse(context.Request.QueryString["id"], out param))
{
using (var db = new MusicLibContext())
{
if (param == -1)
{
bytes = File.ReadAllBytes(HttpContext.Current.Server.MapPath("~/Images/add.png"));
context.Response.ContentType = "image/png";
}
else
{
var data = (from x in db.Images
where x.ImageID == (short)param
select x).FirstOrDefault();
bytes = data.ImageData;
context.Response.ContentType = "image/" + data.ImageFileType;
}
context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
context.Response.BinaryWrite(bytes);
context.Response.Flush();
context.Response.End();
}
}
else
{
//image not found
}
}
public bool IsReusable
{
get
{
return false;
}
}
}
In the view, i added the ID of the photo to the query string of the handler.
Turning off eslint rule for a specific line
You can use the following
/*eslint-disable */
//suppress all warnings between comments
alert('foo');
/*eslint-enable */
Which is slightly buried the "configuring rules" section of the docs;
To disable a warning for an entire file, you can include a comment at the top of the file e.g.
/*eslint eqeqeq:0*/
Update
ESlint has now been updated with a better way disable a single line, see @goofballLogic's excellent answer.
What does "hashable" mean in Python?
All the answers here have good working explanation of hashable objects in python, but I believe one needs to understand the term Hashing first.
Hashing is a concept in computer science which is used to create high performance, pseudo random access data structures where large amount of data is to be stored and accessed quickly.
For example, if you have 10,000 phone numbers, and you want to store them in an array (which is a sequential data structure that stores data in contiguous memory locations, and provides random access), but you might not have the required amount of contiguous memory locations.
So, you can instead use an array of size 100, and use a hash function to map a set of values to same indices, and these values can be stored in a linked list. This provides a performance similar to an array.
Now, a hash function can be as simple as dividing the number with the size of the array and taking the remainder as the index.
For more detail refer to https://en.wikipedia.org/wiki/Hash_function
Here is another good reference: http://interactivepython.org/runestone/static/pythonds/SortSearch/Hashing.html
urllib2.HTTPError: HTTP Error 403: Forbidden
This will work in Python 3
import urllib.request
user_agent = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.7) Gecko/2009021910 Firefox/3.0.7'
url = "http://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers"
headers={'User-Agent':user_agent,}
request=urllib.request.Request(url,None,headers) #The assembled request
response = urllib.request.urlopen(request)
data = response.read() # The data u need
Is there a difference between PhoneGap and Cordova commands?
This first choice might be a confusing one but it’s really very simple. PhoneGap is a product owned by Adobe which currently includes additional build services, and it may or may not eventually offer additional services and/or charge payments for use in the future. Cordova is owned and maintained by Apache, and will always be maintained as an open source project. Currently they both have a very similar API. I would recommend going with Cordova, unless you require the additional PhoneGap build services.
How can I autoformat/indent C code in vim?
I like to use the program Artistic Style. According to their website:
Artistic Style is a source code indenter, formatter, and beautifier for the C, C++, C# and Java programming languages.
It runs in Window, Linux and Mac. It will do things like indenting, replacing tabs with spaces or vice-versa, putting spaces around operations however you like (converting if(x<2)
to if ( x<2 )
if that's how you like it), putting braces on the same line as function definitions, or moving them to the line below, etc. All the options are controlled by command line parameters.
In order to use it in vim, just set the formatprg option to it, and then use the gq command. So, for example, I have in my .vimrc:
autocmd BufNewFile,BufRead *.cpp set formatprg=astyle\ -T4pb
so that whenever I open a .cpp file, formatprg is set with the options I like. Then, I can type gg to go to the top of the file, and gqG to format the entire file according to my standards. If I only need to reformat a single function, I can go to the top of the function, then type gq][ and it will reformat just that function.
The options I have for astyle, -T4pb
, are just my preferences. You can look through their docs, and change the options to have it format the code however you like.
Here's a demo. Before astyle:
int main(){if(x<2){x=3;}}
float test()
{
if(x<2)
x=3;
}
After astyle (gggqG):
int main()
{
if (x < 2)
{
x = 3;
}
}
float test()
{
if (x < 2)
x = 3;
}
Hope that helps.
How to make <input type="date"> supported on all browsers? Any alternatives?
best easy and working solution i have found is, working on following browsers
- Google Chrome
- Firefox
- Microsoft Edge
Safari
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
<h2>Poly Filler Script for Date/Time</h2>
<form method="post" action="">
<input type="date" />
<br/><br/>
<input type="time" />
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="http://cdn.jsdelivr.net/webshim/1.12.4/extras/modernizr-custom.js"></script>
<script src="http://cdn.jsdelivr.net/webshim/1.12.4/polyfiller.js"></script>
<script>
webshims.setOptions('waitReady', false);
webshims.setOptions('forms-ext', {type: 'date'});
webshims.setOptions('forms-ext', {type: 'time'});
webshims.polyfill('forms forms-ext');
</script>
</body>
</html>
Using boolean values in C
C has a boolean type: bool (at least for the last 10(!) years)
Include stdbool.h and true/false will work as expected.
Cannot kill Python script with Ctrl-C
I think it's best to call join() on your threads when you expect them to die. I've taken some liberty with your code to make the loops end (you can add whatever cleanup needs are required to there as well). The variable die is checked for truth on each pass and when it's True then the program exits.
import threading
import time
class MyThread (threading.Thread):
die = False
def __init__(self, name):
threading.Thread.__init__(self)
self.name = name
def run (self):
while not self.die:
time.sleep(1)
print (self.name)
def join(self):
self.die = True
super().join()
if __name__ == '__main__':
f = MyThread('first')
f.start()
s = MyThread('second')
s.start()
try:
while True:
time.sleep(2)
except KeyboardInterrupt:
f.join()
s.join()
Using Regular Expressions to Extract a Value in Java
Full example:
private static final Pattern p = Pattern.compile("^([a-zA-Z]+)([0-9]+)(.*)");
public static void main(String[] args) {
// create matcher for pattern p and given string
Matcher m = p.matcher("Testing123Testing");
// if an occurrence if a pattern was found in a given string...
if (m.find()) {
// ...then you can use group() methods.
System.out.println(m.group(0)); // whole matched expression
System.out.println(m.group(1)); // first expression from round brackets (Testing)
System.out.println(m.group(2)); // second one (123)
System.out.println(m.group(3)); // third one (Testing)
}
}
Since you're looking for the first number, you can use such regexp:
^\D+(\d+).*
and m.group(1)
will return you the first number. Note that signed numbers can contain a minus sign:
^\D+(-?\d+).*
check if jquery has been loaded, then load it if false
Method 1:
if (window.jQuery) {
// jQuery is loaded
} else {
// jQuery is not loaded
}
Method 2:
if (typeof jQuery == 'undefined') {
// jQuery is not loaded
} else {
// jQuery is loaded
}
If jquery.js file is not loaded, we can force load it like so:
if (!window.jQuery) {
var jq = document.createElement('script'); jq.type = 'text/javascript';
// Path to jquery.js file, eg. Google hosted version
jq.src = '/path-to-your/jquery.min.js';
document.getElementsByTagName('head')[0].appendChild(jq);
}
Why cannot change checkbox color whatever I do?
Transparency maybe: checkbox inside span
<span style="display:inline-block; background-color:silver;padding:0px;margin:0px;height:13px; width:13px; overflow:hidden"><input type="checkbox" style="opacity:0.50;padding:0px;margin:0px" /></span>
Inserting data into a MySQL table using VB.NET
After instantiating the connection, open it.
SQLConnection = New MySqlConnection()
SQLConnection.ConnectionString = connectionString
SQLConnection.Open()
Also, avoid building SQL statements by just appending strings. It's better if you use parameters, that way you win on performance, your program is not prone to SQL injection attacks and your program is more stable. For example:
str_carSql = "insert into members_car
(car_id, member_id, model, color, chassis_id, plate_number, code)
values
(@id,@m_id,@model,@color,@ch_id,@pt_num,@code)"
And then you do this:
sqlCommand.Parameters.AddWithValue("@id",TextBox20.Text)
sqlCommand.Parameters.AddWithValue("@m_id",TextBox23.Text)
' And so on...
Then you call:
sqlCommand.ExecuteNonQuery()
What is the technology behind wechat, whatsapp and other messenger apps?
To my knowledge, Ejabberd (http://www.ejabberd.im/) is the parent, this is XMPP server which provide quite good features of open source, Whatsapp uses some modified version of this, facebook messaging also uses a modified version of this. Some more chat applications likes Samsung's ChatOn, Nimbuzz messenger all use ejabberd based ones and Erlang solutions also have modified version of this ejabberd which they claim to be highly scalable and well tested with more performance improvements and renamed as MongooseIM.
Ejabberd is the server which has most of the featured implemented when compared to other. Since it is build in Erlang it is highly scalable horizontally.
What is the App_Data folder used for in Visual Studio?
The App_Data folder is a folder, which your asp.net worker process has files sytem rights too, but isn't published through the web server.
For example we use it to update a local CSV of a contact us form. If the preferred method of emails fails or any querying of the data source is required, the App_Data files are there.
It's not ideal, but it it's a good fall-back.
Directory Chooser in HTML page
Can't be done in pure HTML/JavaScript for security reasons.
Selecting a file for upload is the best you can do, and even then you won't get its full original path in modern browsers.
You may be able to put something together using Java or Flash (e.g. using SWFUpload as a basis), but it's a lot of work and brings additional compatibility issues.
Another thought would be opening an iframe
showing the user's C:
drive (or whatever) but even if that's possible nowadays (could be blocked for security reasons, haven't tried in a long time) it will be impossible for your web site to communicate with the iframe (again for security reasons).
What do you need this for?
Convert string date to timestamp in Python
Simply use datetime.datetime.strptime
:
import datetime
stime = "01/12/2011"
print(datetime.datetime.strptime(stime, "%d/%m/%Y").timestamp())
Result:
1322697600
To use UTC instead of the local timezone use .replace
:
datetime.datetime.strptime(stime, "%d/%m/%Y").replace(tzinfo=datetime.timezone.utc).timestamp()
JavaScript error (Uncaught SyntaxError: Unexpected end of input)
This error is mainly caused by empty returned ajax calls, when trying to parse an empty JSON.
To solve this test if the returned data is empty
$.ajax({
url: url,
type: "get",
dataType: "json",
success: function (response) {
if(response.data.length == 0){
// EMPTY
}else{
var obj =jQuery.parseJSON(response.data);
console.log(obj);
}
}
});
Getting Hour and Minute in PHP
In addressing your comment that you need your current time, and not the system time, you will have to make an adjustment yourself,
there are 3600 seconds in an hour (the unit timestamps use), so use that. for example, if your system time was one hour behind:
$time = date('H:i',time() + 3600);
How to select an item in a ListView programmatically?
Most likely, the item is being selected, you just can't tell because a different control has the focus. There are a couple of different ways that you can solve this, depending on the design of your application.
The simple solution is to set the focus to the ListView
first whenever your form is displayed. The user typically sets focus to controls by clicking on them. However, you can also specify which controls gets the focus programmatically. One way of doing this is by setting the tab index of the control to 0 (the lowest value indicates the control that will have the initial focus). A second possibility is to use the following line of code in your form's Load
event, or immediately after you set the Selected
property:
myListView.Select();
The problem with this solution is that the selected item will no longer appear highlighted when the user sets focus to a different control on your form (such as a textbox or a button).
To fix that, you will need to set the HideSelection
property of the ListView
control to False. That will cause the selected item to remain highlighted, even when the control loses the focus.
When the control has the focus, the selected item's background will be painted with the system highlight color. When the control does not have the focus, the selected item's background will be painted in the system color used for grayed (or disabled) text.
You can set this property either at design time, or through code:
myListView.HideSelection = false;
How do I extend a class with c# extension methods?
I would do the same as Kumu
namespace ExtensionMethods
{
public static class MyExtensionMethods
{
public static DateTime Tomorrow(this DateTime date)
{
return date.AddDays(1);
}
}
}
but call it like this new DateTime().Tomorrow();
Think it makes more seens than DateTime.Now.Tomorrow();
Bootstrap Element 100% Width
QUICK ANSWER
- Use multiple NOT NESTED
.container
s
- Wrap those
.container
s you want to have a full-width background in a div
- Add a CSS background to the wrapping div
Fiddles: Simple: https://jsfiddle.net/vLhc35k4/ , Container borders: https://jsfiddle.net/vLhc35k4/1/
HTML:
<div class="container">
<h2>Section 1</h2>
</div>
<div class="specialBackground">
<div class="container">
<h2>Section 2</h2>
</div>
</div>
CSS: .specialBackground{ background-color: gold; /*replace with own background settings*/ }
FURTHER INFO
DON'T USE NESTED CONTAINERS
Many people will (wrongly) suggest, that you should use nested containers.
Well, you should NOT.
They are not ment to be nested. (See to "Containers" section in the docs)
HOW IT WORKS
div
is a block element, which by default spans to the full width of a document body - there is the full-width feature. It also has a height of it's content (if you don't specify otherwise).
The bootstrap containers are not required to be direct children of a body, they are just containers with some padding and possibly some screen-width-variable fixed widths.
If a basic grid .container
has some fixed width it is also auto-centered horizontally.
So there is no difference whether you put it as a:
- Direct child of a body
- Direct child of a basic
div
that is a direct child of a body.
By "basic" div
I mean div
that does not have a CSS altering his border, padding, dimensions, position or content size. Really just a HTML element with display: block;
CSS and possibly background.
But of course setting vertical-like CSS (height, padding-top, ...) should not break the bootstrap grid :-)
Bootstrap itself is using the same approach
...All over it's own website and in it's "JUMBOTRON" example:
http://getbootstrap.com/examples/jumbotron/
Numpy: find index of the elements within range
Summary of the answers
For understanding what is the best answer we can do some timing using the different solution.
Unfortunately, the question was not well-posed so there are answers to different questions, here I try to point the answer to the same question. Given the array:
a = np.array([1, 3, 5, 6, 9, 10, 14, 15, 56])
The answer should be the indexes of the elements between a certain range, we assume inclusive, in this case, 6 and 10.
answer = (3, 4, 5)
Corresponding to the values 6,9,10.
To test the best answer we can use this code.
import timeit
setup = """
import numpy as np
import numexpr as ne
a = np.array([1, 3, 5, 6, 9, 10, 14, 15, 56])
# we define the left and right limit
ll = 6
rl = 10
def sorted_slice(a,l,r):
start = np.searchsorted(a, l, 'left')
end = np.searchsorted(a, r, 'right')
return np.arange(start,end)
"""
functions = ['sorted_slice(a,ll,rl)', # works only for sorted values
'np.where(np.logical_and(a>=ll, a<=rl))[0]',
'np.where((a >= ll) & (a <=rl))[0]',
'np.where((a>=ll)*(a<=rl))[0]',
'np.where(np.vectorize(lambda x: ll <= x <= rl)(a))[0]',
'np.argwhere((a>=ll) & (a<=rl)).T[0]', # we traspose for getting a single row
'np.where(ne.evaluate("(ll <= a) & (a <= rl)"))[0]',]
functions2 = [
'a[np.logical_and(a>=ll, a<=rl)]',
'a[(a>=ll) & (a<=rl)]',
'a[(a>=ll)*(a<=rl)]',
'a[np.vectorize(lambda x: ll <= x <= rl)(a)]',
'a[ne.evaluate("(ll <= a) & (a <= rl)")]',
]
Results
The results are reported in the following plot. On the top the fastest solutions.
If instead of the indexes you want to extract the values you can perform the tests using functions2 but the results are almost the same.
Break statement in javascript array map method
That's not possible using the built-in Array.prototype.map
. However, you could use a simple for
-loop instead, if you do not intend to map
any values:
var hasValueLessThanTen = false;
for (var i = 0; i < myArray.length; i++) {
if (myArray[i] < 10) {
hasValueLessThanTen = true;
break;
}
}
Or, as suggested by @RobW
, use Array.prototype.some
to test if there exists at least one element that is less than 10. It will stop looping when some element that matches your function is found:
var hasValueLessThanTen = myArray.some(function (val) {
return val < 10;
});
Convert list of ints to one number?
This method works in 2.x as long as each element in the list is only a single digit. But you shouldn't actually use this. It's horrible.
>>> magic = lambda l:int(`l`[1::3])
>>> magic([3,1,3,3,7])
31337
How to round a numpy array?
It is worth noting that the accepted answer will round small floats down to zero.
>>> import numpy as np
>>> arr = np.asarray([2.92290007e+00, -1.57376965e-03, 4.82011728e-08, 1.92896977e-12])
>>> print(arr)
[ 2.92290007e+00 -1.57376965e-03 4.82011728e-08 1.92896977e-12]
>>> np.round(arr, 2)
array([ 2.92, -0. , 0. , 0. ])
You can use set_printoptions
and a custom formatter to fix this and get a more numpy-esque printout with fewer decimal places:
>>> np.set_printoptions(formatter={'float': "{0:0.2e}".format})
>>> print(arr)
[2.92e+00 -1.57e-03 4.82e-08 1.93e-12]
This way, you get the full versatility of format
and maintain the full precision of numpy's datatypes.
Also note that this only affects printing, not the actual precision of the stored values used for computation.
Get a UTC timestamp
You can use Date.UTC method to get the time stamp at the UTC timezone.
Usage:
var now = new Date;
var utc_timestamp = Date.UTC(now.getUTCFullYear(),now.getUTCMonth(), now.getUTCDate() ,
now.getUTCHours(), now.getUTCMinutes(), now.getUTCSeconds(), now.getUTCMilliseconds());
Live demo here http://jsfiddle.net/naryad/uU7FH/1/
How to convert a std::string to const char* or char*?
Given say...
std::string x = "hello";
Getting a `char *` or `const char*` from a `string`
How to get a character pointer that's valid while x
remains in scope and isn't modified further
C++11 simplifies things; the following all give access to the same internal string buffer:
const char* p_c_str = x.c_str();
const char* p_data = x.data();
char* p_writable_data = x.data(); // for non-const x from C++17
const char* p_x0 = &x[0];
char* p_x0_rw = &x[0]; // compiles iff x is not const...
All the above pointers will hold the same value - the address of the first character in the buffer. Even an empty string has a "first character in the buffer", because C++11 guarantees to always keep an extra NUL/0 terminator character after the explicitly assigned string content (e.g. std::string("this\0that", 9)
will have a buffer holding "this\0that\0"
).
Given any of the above pointers:
char c = p[n]; // valid for n <= x.size()
// i.e. you can safely read the NUL at p[x.size()]
Only for the non-const
pointer p_writable_data
and from &x[0]
:
p_writable_data[n] = c;
p_x0_rw[n] = c; // valid for n <= x.size() - 1
// i.e. don't overwrite the implementation maintained NUL
Writing a NUL elsewhere in the string does not change the string
's size()
; string
's are allowed to contain any number of NULs - they are given no special treatment by std::string
(same in C++03).
In C++03, things were considerably more complicated (key differences highlighted):
x.data()
- returns
const char*
to the string's internal buffer which wasn't required by the Standard to conclude with a NUL (i.e. might be ['h', 'e', 'l', 'l', 'o']
followed by uninitialised or garbage values, with accidental accesses thereto having undefined behaviour).
x.size()
characters are safe to read, i.e. x[0]
through x[x.size() - 1]
- for empty strings, you're guaranteed some non-NULL pointer to which 0 can be safely added (hurray!), but you shouldn't dereference that pointer.
&x[0]
- for empty strings this has undefined behaviour (21.3.4)
- e.g. given
f(const char* p, size_t n) { if (n == 0) return; ...whatever... }
you mustn't call f(&x[0], x.size());
when x.empty()
- just use f(x.data(), ...)
.
- otherwise, as per
x.data()
but:
- for non-
const
x
this yields a non-const
char*
pointer; you can overwrite string content
x.c_str()
- returns
const char*
to an ASCIIZ (NUL-terminated) representation of the value (i.e. ['h', 'e', 'l', 'l', 'o', '\0']).
- although few if any implementations chose to do so, the C++03 Standard was worded to allow the string implementation the freedom to create a distinct NUL-terminated buffer on the fly, from the potentially non-NUL terminated buffer "exposed" by
x.data()
and &x[0]
x.size()
+ 1 characters are safe to read.
- guaranteed safe even for empty strings (['\0']).
Consequences of accessing outside legal indices
Whichever way you get a pointer, you must not access memory further along from the pointer than the characters guaranteed present in the descriptions above. Attempts to do so have undefined behaviour, with a very real chance of application crashes and garbage results even for reads, and additionally wholesale data, stack corruption and/or security vulnerabilities for writes.
When do those pointers get invalidated?
If you call some string
member function that modifies the string
or reserves further capacity, any pointer values returned beforehand by any of the above methods are invalidated. You can use those methods again to get another pointer. (The rules are the same as for iterators into string
s).
See also How to get a character pointer valid even after x
leaves scope or is modified further below....
So, which is better to use?
From C++11, use .c_str()
for ASCIIZ data, and .data()
for "binary" data (explained further below).
In C++03, use .c_str()
unless certain that .data()
is adequate, and prefer .data()
over &x[0]
as it's safe for empty strings....
...try to understand the program enough to use data()
when appropriate, or you'll probably make other mistakes...
The ASCII NUL '\0' character guaranteed by .c_str()
is used by many functions as a sentinel value denoting the end of relevant and safe-to-access data. This applies to both C++-only functions like say fstream::fstream(const char* filename, ...)
and shared-with-C functions like strchr()
, and printf()
.
Given C++03's .c_str()
's guarantees about the returned buffer are a super-set of .data()
's, you can always safely use .c_str()
, but people sometimes don't because:
- using
.data()
communicates to other programmers reading the source code that the data is not ASCIIZ (rather, you're using the string to store a block of data (which sometimes isn't even really textual)), or that you're passing it to another function that treats it as a block of "binary" data. This can be a crucial insight in ensuring that other programmers' code changes continue to handle the data properly.
- C++03 only: there's a slight chance that your
string
implementation will need to do some extra memory allocation and/or data copying in order to prepare the NUL terminated buffer
As a further hint, if a function's parameters require the (const
) char*
but don't insist on getting x.size()
, the function probably needs an ASCIIZ input, so .c_str()
is a good choice (the function needs to know where the text terminates somehow, so if it's not a separate parameter it can only be a convention like a length-prefix or sentinel or some fixed expected length).
How to get a character pointer valid even after x
leaves scope or is modified further
You'll need to copy the contents of the string
x
to a new memory area outside x
. This external buffer could be in many places such as another string
or character array variable, it may or may not have a different lifetime than x
due to being in a different scope (e.g. namespace, global, static, heap, shared memory, memory mapped file).
To copy the text from std::string x
into an independent character array:
// USING ANOTHER STRING - AUTO MEMORY MANAGEMENT, EXCEPTION SAFE
std::string old_x = x;
// - old_x will not be affected by subsequent modifications to x...
// - you can use `&old_x[0]` to get a writable char* to old_x's textual content
// - you can use resize() to reduce/expand the string
// - resizing isn't possible from within a function passed only the char* address
std::string old_x = x.c_str(); // old_x will terminate early if x embeds NUL
// Copies ASCIIZ data but could be less efficient as it needs to scan memory to
// find the NUL terminator indicating string length before allocating that amount
// of memory to copy into, or more efficient if it ends up allocating/copying a
// lot less content.
// Example, x == "ab\0cd" -> old_x == "ab".
// USING A VECTOR OF CHAR - AUTO, EXCEPTION SAFE, HINTS AT BINARY CONTENT, GUARANTEED CONTIGUOUS EVEN IN C++03
std::vector<char> old_x(x.data(), x.data() + x.size()); // without the NUL
std::vector<char> old_x(x.c_str(), x.c_str() + x.size() + 1); // with the NUL
// USING STACK WHERE MAXIMUM SIZE OF x IS KNOWN TO BE COMPILE-TIME CONSTANT "N"
// (a bit dangerous, as "known" things are sometimes wrong and often become wrong)
char y[N + 1];
strcpy(y, x.c_str());
// USING STACK WHERE UNEXPECTEDLY LONG x IS TRUNCATED (e.g. Hello\0->Hel\0)
char y[N + 1];
strncpy(y, x.c_str(), N); // copy at most N, zero-padding if shorter
y[N] = '\0'; // ensure NUL terminated
// USING THE STACK TO HANDLE x OF UNKNOWN (BUT SANE) LENGTH
char* y = alloca(x.size() + 1);
strcpy(y, x.c_str());
// USING THE STACK TO HANDLE x OF UNKNOWN LENGTH (NON-STANDARD GCC EXTENSION)
char y[x.size() + 1];
strcpy(y, x.c_str());
// USING new/delete HEAP MEMORY, MANUAL DEALLOC, NO INHERENT EXCEPTION SAFETY
char* y = new char[x.size() + 1];
strcpy(y, x.c_str());
// or as a one-liner: char* y = strcpy(new char[x.size() + 1], x.c_str());
// use y...
delete[] y; // make sure no break, return, throw or branching bypasses this
// USING new/delete HEAP MEMORY, SMART POINTER DEALLOCATION, EXCEPTION SAFE
// see boost shared_array usage in Johannes Schaub's answer
// USING malloc/free HEAP MEMORY, MANUAL DEALLOC, NO INHERENT EXCEPTION SAFETY
char* y = strdup(x.c_str());
// use y...
free(y);
Other reasons to want a char*
or const char*
generated from a string
So, above you've seen how to get a (const
) char*
, and how to make a copy of the text independent of the original string
, but what can you do with it? A random smattering of examples...
- give "C" code access to the C++
string
's text, as in printf("x is '%s'", x.c_str());
- copy
x
's text to a buffer specified by your function's caller (e.g. strncpy(callers_buffer, callers_buffer_size, x.c_str())
), or volatile memory used for device I/O (e.g. for (const char* p = x.c_str(); *p; ++p) *p_device = *p;
)
- append
x
's text to an character array already containing some ASCIIZ text (e.g. strcat(other_buffer, x.c_str())
) - be careful not to overrun the buffer (in many situations you may need to use strncat
)
- return a
const char*
or char*
from a function (perhaps for historical reasons - client's using your existing API - or for C compatibility you don't want to return a std::string
, but do want to copy your string
's data somewhere for the caller)
- be careful not to return a pointer that may be dereferenced by the caller after a local
string
variable to which that pointer pointed has left scope
- some projects with shared objects compiled/linked for different
std::string
implementations (e.g. STLport and compiler-native) may pass data as ASCIIZ to avoid conflicts
SQL Add foreign key to existing column
MySQL / SQL Server / Oracle / MS Access:
ALTER TABLE Orders
ADD FOREIGN KEY (P_Id)
REFERENCES Persons(P_Id)
To allow naming of a FOREIGN KEY constraint, and for defining a FOREIGN KEY constraint on multiple columns, use the following SQL syntax:
MySQL / SQL Server / Oracle / MS Access:
ALTER TABLE Orders
ADD CONSTRAINT fk_PerOrders
FOREIGN KEY (P_Id)
REFERENCES Persons(P_Id)
TypeScript-'s Angular Framework Error - "There is no directive with exportAs set to ngForm"
I've come to this same question over & over again, also due to same reason. So let me answer this by saying what wrong I was doing. Might be helpful for someone.
I was creating component via angular-cli
by command
ng g c components/something/something
What it did, was created the component as I wanted.
Also, While creating the component, it added the component in the App Module's declarations array.
If this is the case, please remove it.
And Voila! It might work.
How to disable scrolling temporarily?
Here is my solution to stop the scroll (no jQuery). I use it to disable the scroll when the side menu appears.
_x000D_
_x000D_
<button onClick="noscroll()" style="position:fixed; padding: 8px 16px;">Disable/Enable scroll</button>_x000D_
<script>_x000D_
var noscroll_var;_x000D_
function noscroll(){_x000D_
if(noscroll_var){_x000D_
document.getElementsByTagName("html")[0].style.overflowY = "";_x000D_
document.body.style.paddingRight = "0";_x000D_
noscroll_var = false_x000D_
}else{_x000D_
document.getElementsByTagName("html")[0].setAttribute('style', 'overflow-y: hidden !important');_x000D_
document.body.style.paddingRight = "17px";_x000D_
noscroll_var = true_x000D_
}_x000D_
}/*noscroll()*/_x000D_
</script>_x000D_
_x000D_
<!-- Just to fill the page -->_x000D_
<script>_x000D_
for(var i=0; i <= 80; i++){_x000D_
document.write(i + "<hr>")_x000D_
}_x000D_
</script>
_x000D_
_x000D_
_x000D_
I put 17px of padding-right to compensate for the disappearance of the scroll bar. But this is also problematic, mostly for mobile browsers. Solved by getting the bar width according to this.
All together in this Pen.
java.lang.IllegalStateException: Cannot (forward | sendRedirect | create session) after response has been committed
Bump...
I just had the same error. I noticed that I was invoking super.doPost(request, response);
when overriding the doPost()
method as well as explicitly invoking the superclass constructor
public ScheduleServlet() {
super();
// TODO Auto-generated constructor stub
}
As soon as I commented out the super.doPost(request, response);
from within doPost()
statement it worked perfectly...
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//super.doPost(request, response);
// More code here...
}
Needless to say, I need to re-read on super()
best practices :p
Cannot read property 'length' of null (javascript)
The proper test is:
if (capital != null && capital.length < 1) {
This ensures that capital
is always non null, when you perform the length check.
Also, as the comments suggest, capital
is null
because you never initialize it.
Error With Port 8080 already in use
It has been long time, but I faced the same Issue, and solved it as follow:
1. tried shutting down the application server using the shutdown.bat/.bash which might be in your application Server / bin/shutdown..
- My Issue, was that more than 1 instance of java was running, I was changing ports, and not looking back, so it kept running other java processes, with that specific port.
for windows users, : ALT+Shift+Esc, and end java processes that you are not using and now you should be able to re-use your port 8080
Can I specify maxlength in css?
Use $("input").attr("maxlength", 4)
if you're using jQuery version < 1.6
and $("input").prop("maxLength", 4)
if you are using jQuery version 1.6+.
How to clear or stop timeInterval in angularjs?
You can store the promise returned by the interval and use $interval.cancel()
to that promise, which cancels the interval of that promise. To delegate the starting and stopping of the interval, you can create start()
and stop()
functions whenever you want to stop and start them again from a specific event. I have created a snippet below showing the basics of starting and stopping an interval, by implementing it in view through the use of events (e.g. ng-click
) and in the controller.
_x000D_
_x000D_
angular.module('app', [])_x000D_
_x000D_
.controller('ItemController', function($scope, $interval) {_x000D_
_x000D_
// store the interval promise in this variable_x000D_
var promise;_x000D_
_x000D_
// simulated items array_x000D_
$scope.items = [];_x000D_
_x000D_
// starts the interval_x000D_
$scope.start = function() {_x000D_
// stops any running interval to avoid two intervals running at the same time_x000D_
$scope.stop(); _x000D_
_x000D_
// store the interval promise_x000D_
promise = $interval(setRandomizedCollection, 1000);_x000D_
};_x000D_
_x000D_
// stops the interval_x000D_
$scope.stop = function() {_x000D_
$interval.cancel(promise);_x000D_
};_x000D_
_x000D_
// starting the interval by default_x000D_
$scope.start();_x000D_
_x000D_
// stops the interval when the scope is destroyed,_x000D_
// this usually happens when a route is changed and _x000D_
// the ItemsController $scope gets destroyed. The_x000D_
// destruction of the ItemsController scope does not_x000D_
// guarantee the stopping of any intervals, you must_x000D_
// be responsible for stopping it when the scope is_x000D_
// is destroyed._x000D_
$scope.$on('$destroy', function() {_x000D_
$scope.stop();_x000D_
});_x000D_
_x000D_
function setRandomizedCollection() {_x000D_
// items to randomize 1 - 11_x000D_
var randomItems = parseInt(Math.random() * 10 + 1); _x000D_
_x000D_
// empties the items array_x000D_
$scope.items.length = 0; _x000D_
_x000D_
// loop through random N times_x000D_
while(randomItems--) {_x000D_
_x000D_
// push random number from 1 - 10000 to $scope.items_x000D_
$scope.items.push(parseInt(Math.random() * 10000 + 1)); _x000D_
}_x000D_
}_x000D_
_x000D_
});
_x000D_
<div ng-app="app" ng-controller="ItemController">_x000D_
_x000D_
<!-- Event trigger to start the interval -->_x000D_
<button type="button" ng-click="start()">Start Interval</button>_x000D_
_x000D_
<!-- Event trigger to stop the interval -->_x000D_
<button type="button" ng-click="stop()">Stop Interval</button>_x000D_
_x000D_
<!-- display all the random items -->_x000D_
<ul>_x000D_
<li ng-repeat="item in items track by $index" ng-bind="item"></li>_x000D_
</ul>_x000D_
<!-- end of display -->_x000D_
</div>_x000D_
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
_x000D_
_x000D_
_x000D_
How do I run a Python script from C#?
I am having problems with stdin/stout
- when payload size exceeds several kilobytes it hangs. I need to call Python functions not only with some short arguments, but with a custom payload that could be big.
A while ago, I wrote a virtual actor library that allows to distribute task on different machines via Redis. To call Python code, I added functionality to listen for messages from Python, process them and return results back to .NET.
Here is a brief description of how it works.
It works on a single machine as well, but requires a Redis instance. Redis adds some reliability guarantees - payload is stored until a worked acknowledges completion. If a worked dies, the payload is returned to a job queue and then is reprocessed by another worker.
How can I make a float top with CSS?
The trick that worked for me was to change the writing-mode for the duration of the div-alignment.
_x000D_
_x000D_
.outer{ _x000D_
/* Limit height of outer div so there has to be a line-break*/_x000D_
height:100px;_x000D_
_x000D_
/* Tell the browser we are writing chinese. This makes everything that is text_x000D_
top-bottom then left to right. */_x000D_
writing-mode:vertical-lr;_x000D_
_x000D_
}_x000D_
_x000D_
.outer > div{_x000D_
/* float:left behaves like float:top because this block is beeing aligned top-bottom first _x000D_
*/_x000D_
float:left;_x000D_
width:40px; _x000D_
_x000D_
/* Switch back to normal writing mode. If you leave this out, everything inside the_x000D_
div will also be top-bottom. */_x000D_
writing-mode:horizontal-tb;_x000D_
_x000D_
}
_x000D_
<div class="outer">_x000D_
<div>one</div>_x000D_
<div>two</div>_x000D_
<div>three</div>_x000D_
<div>four</div>_x000D_
<div>one</div>_x000D_
<div>two</div>_x000D_
<div>three</div>_x000D_
<div>four</div>_x000D_
<div>one</div>_x000D_
<div>two</div>_x000D_
<div>three</div>_x000D_
<div>four</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_
javascript push multidimensional array
In JavaScript, the type of key/value store you are attempting to use is an object literal, rather than an array. You are mistakenly creating a composite array object, which happens to have other properties based on the key names you provided, but the array portion contains no elements.
Instead, declare valueToPush
as an object and push that onto cookie_value_add
:
// Create valueToPush as an object {} rather than an array []
var valueToPush = {};
// Add the properties to your object
// Note, you could also use the valueToPush["productID"] syntax you had
// above, but this is a more object-like syntax
valueToPush.productID = productID;
valueToPush.itemColorTitle = itemColorTitle;
valueToPush.itemColorPath = itemColorPath;
cookie_value_add.push(valueToPush);
// View the structure of cookie_value_add
console.dir(cookie_value_add);
How do you use a variable in a regular expression?
To satisfy my need to insert a variable/alias/function into a Regular Expression, this is what I came up with:
oldre = /xx\(""\)/;
function newre(e){
return RegExp(e.toString().replace(/\//g,"").replace(/xx/g, yy), "g")
};
String.prototype.replaceAll = this.replace(newre(oldre), "withThis");
where 'oldre' is the original regexp that I want to insert a variable,
'xx' is the placeholder for that variable/alias/function,
and 'yy' is the actual variable name, alias, or function.
How does C#'s random number generator work?
I've been searching the internet for RNG for a while now. Everything I saw was either TOO complex or was just not what I was looking for. After reading a few articles I was able to come up with this simple code.
{
Random rnd = new Random(DateTime.Now.Millisecond);
int[] b = new int[10] { 5, 8, 1, 7, 3, 2, 9, 0, 4, 6 };
textBox1.Text = Convert.ToString(b[rnd.Next(10)])
}
Simple explanation,
- create a 1 dimensional integer array.
- full up the array with unordered numbers.
- use the rnd.Next to get the position of the number that will be picked.
This works well.
To obtain a random number less than 100 use
{
Random rnd = new Random(DateTime.Now.Millisecond);
int[] b = new int[10] { 5, 8, 1, 7, 3, 2, 9, 0, 4, 6 };
int[] d = new int[10] { 9, 4, 7, 2, 8, 0, 5, 1, 3, 4 };
textBox1.Text = Convert.ToString(b[rnd.Next(10)]) + Convert.ToString(d[rnd.Next(10)]);
}
and so on for 3, 4, 5, and 6 ... digit random numbers.
Hope this assists someone positively.
Global and local variables in R
A bit more along the same lines
attrs <- {}
attrs.a <- 1
f <- function(d) {
attrs.a <- d
}
f(20)
print(attrs.a)
will print "1"
attrs <- {}
attrs.a <- 1
f <- function(d) {
attrs.a <<- d
}
f(20)
print(attrs.a)
Will print "20"
Current Subversion revision command
Nobody mention for Windows world SubWCRev, which, properly used, can substitute needed data into the needed places automagically, if script call SubWCRev in form SubWCRev WC_PATH TPL-FILE READY-FILE
Sample of my post-commit hook (part of)
SubWCRev.exe CustomLocations Builder.tpl z:\Builder.bat
...
call z:\Builder.bat
where my Builder.tpl is
svn.exe export trunk z:\trunk$WCDATE=%Y%m%d$-r$WCREV$
as result, I have every time bat-file with variable part - name of dir - which corresponds to the metadata of Working Copy
"Cannot evaluate expression because the code of the current method is optimized" in Visual Studio 2010
It sounds like you are debugging an optimised / release build, despite having the optimised box un-checked. Things you can try are:
- Do a complete rebuild of your solution file (right click on the solution and select Rebuild all)
- While debugging open up the modules window (Debug -> Windows -> Modules) and find your assembly in the list of loaded modules. Check that the Path listed against your loaded assembly is what you expect it to be, and that the modified timestamp of the file indicates that the assembly was actually rebuilt.
- The modules window should also tell you whether or not the loaded module is optimised or not - make sure that the modules window indicates that it is not optimised.
If you cant't see the Modules menu item in the Debug -> Windows menu then you may need to add it in the "Customise..." menu.
Setting up MySQL and importing dump within Dockerfile
I used docker-entrypoint-initdb.d approach (Thanks to @Kuhess)
But in my case I want to create my DB based on some parameters I defined in .env file so I did these
1) First I define .env file something like this in my docker root project directory
MYSQL_DATABASE=my_db_name
MYSQL_USER=user_test
MYSQL_PASSWORD=test
MYSQL_ROOT_PASSWORD=test
MYSQL_PORT=3306
2) Then I define my docker-compose.yml file. So I used the args directive to define my environment variables and I set them from .env file
version: '2'
services:
### MySQL Container
mysql:
build:
context: ./mysql
args:
- MYSQL_DATABASE=${MYSQL_DATABASE}
- MYSQL_USER=${MYSQL_USER}
- MYSQL_PASSWORD=${MYSQL_PASSWORD}
- MYSQL_ROOT_PASSWORD=${MYSQL_ROOT_PASSWORD}
ports:
- "${MYSQL_PORT}:3306"
3) Then I define a mysql folder that includes a Dockerfile. So the Dockerfile is this
FROM mysql:5.7
RUN chown -R mysql:root /var/lib/mysql/
ARG MYSQL_DATABASE
ARG MYSQL_USER
ARG MYSQL_PASSWORD
ARG MYSQL_ROOT_PASSWORD
ENV MYSQL_DATABASE=$MYSQL_DATABASE
ENV MYSQL_USER=$MYSQL_USER
ENV MYSQL_PASSWORD=$MYSQL_PASSWORD
ENV MYSQL_ROOT_PASSWORD=$MYSQL_ROOT_PASSWORD
ADD data.sql /etc/mysql/data.sql
RUN sed -i 's/MYSQL_DATABASE/'$MYSQL_DATABASE'/g' /etc/mysql/data.sql
RUN cp /etc/mysql/data.sql /docker-entrypoint-initdb.d
EXPOSE 3306
4) Now I use mysqldump to dump my db and put the data.sql inside mysql folder
mysqldump -h <server name> -u<user> -p <db name> > data.sql
The file is just a normal sql dump file but I add 2 lines at the beginning so the file would look like this
--
-- Create a database using `MYSQL_DATABASE` placeholder
--
CREATE DATABASE IF NOT EXISTS `MYSQL_DATABASE`;
USE `MYSQL_DATABASE`;
-- Rest of queries
DROP TABLE IF EXISTS `x`;
CREATE TABLE `x` (..)
LOCK TABLES `x` WRITE;
INSERT INTO `x` VALUES ...;
...
...
...
So what happening is that I used "RUN sed -i 's/MYSQL_DATABASE/'$MYSQL_DATABASE'/g' /etc/mysql/data.sql" command to replace the MYSQL_DATABASE
placeholder with the name of my DB that I have set it in .env file.
|- docker-compose.yml
|- .env
|- mysql
|- Dockerfile
|- data.sql
Now you are ready to build and run your container
How to output loop.counter in python jinja template?
Inside of a for-loop block, you can access some special variables including loop.index
--but no loop.counter
. From the official docs:
Variable Description
loop.index The current iteration of the loop. (1 indexed)
loop.index0 The current iteration of the loop. (0 indexed)
loop.revindex The number of iterations from the end of the loop (1 indexed)
loop.revindex0 The number of iterations from the end of the loop (0 indexed)
loop.first True if first iteration.
loop.last True if last iteration.
loop.length The number of items in the sequence.
loop.cycle A helper function to cycle between a list of sequences. See the explanation below.
loop.depth Indicates how deep in a recursive loop the rendering currently is. Starts at level 1
loop.depth0 Indicates how deep in a recursive loop the rendering currently is. Starts at level 0
loop.previtem The item from the previous iteration of the loop. Undefined during the first iteration.
loop.nextitem The item from the following iteration of the loop. Undefined during the last iteration.
loop.changed(*val) True if previously called with a different value (or not called at all).
How do I view cookies in Internet Explorer 11 using Developer Tools
- Click on the Network button
- Enable capture of network traffic by
clicking on the green triangular button in top toolbar
- Capture some network traffic by interacting with the page
- Click on DETAILS/Cookies
- Step through each captured traffic segment; detailed
information about cookies will be displayed
What are the differences between the different saving methods in Hibernate?
None of the answers above are complete. Although Leo Theobald answer looks nearest answer.
The basic point is how hibernate is dealing with states of entities and how it handles them when there is a state change. Everything must be seen with respect to flushes and commits as well, which everyone seems to have ignored completely.
NEVER USE THE SAVE METHOD of HIBERNATE. FORGET THAT IT EVEN EXISTS IN HIBERNATE!
Persist
As everyone explained, Persist basically transitions an entity from "Transient" state to "Managed" State. At this point, a slush or a commit can create an insert statement. But the entity will still remains in "Managed" state. That doesn't change with flush.
At this point, if you "Persist" again there will be no change. And there wont be any more saves if we try to persist a persisted entity.
The fun begins when we try to evict the entity.
An evict is a special function of Hibernate which will transition the entity from "Managed" to "Detached". We cannot call a persist on a detached entity. If we do that, then Hibernate raises an exception and entire transaction gets rolled back on commit.
Merge vs Update
These are 2 interesting functions doing different stuff when dealt in different ways. Both of them are trying to transition the entity from "Detached" state to "Managed" state. But doing it differently.
Understand a fact that Detached means kind of an "offline" state. and managed means "Online" state.
Observe the code below:
Session ses1 = sessionFactory.openSession();
Transaction tx1 = ses1.beginTransaction();
HibEntity entity = getHibEntity();
ses1.persist(entity);
ses1.evict(entity);
ses1.merge(entity);
ses1.delete(entity);
tx1.commit();
When you do this? What do you think will happen?
If you said this will raise exception, then you are correct. This will raise exception because, merge has worked on entity object, which is detached state. But it doesn't alter the state of object.
Behind the scene, merge will raise a select query and basically returns a copy of entity which is in attached state. Observe the code below:
Session ses1 = sessionFactory.openSession();
Transaction tx1 = ses1.beginTransaction();
HibEntity entity = getHibEntity();
ses1.persist(entity);
ses1.evict(entity);
HibEntity copied = (HibEntity)ses1.merge(entity);
ses1.delete(copied);
tx1.commit();
The above sample works because merge has brought a new entity into the context which is in persisted state.
When applied with Update the same works fine because update doesn't actually bring a copy of entity like merge.
Session ses1 = sessionFactory.openSession();
Transaction tx1 = ses1.beginTransaction();
HibEntity entity = getHibEntity();
ses1.persist(entity);
ses1.evict(entity);
ses1.update(entity);
ses1.delete(entity);
tx1.commit();
At the same time in debug trace we can see that Update hasn't raised SQL query of select like merge.
delete
In the above example I used delete without talking about delete. Delete will basically transition the entity from managed state to "removed" state. And when flushed or commited will issue a delete command to store.
However it is possible to bring the entity back to "managed" state from "removed" state using the persist method.
Hope the above explanation clarified any doubts.
Timeout jQuery effects
You can do something like this:
$('.notice')
.fadeIn()
.animate({opacity: '+=0'}, 2000) // Does nothing for 2000ms
.fadeOut('fast');
Sadly, you can't just do .animate({}, 2000) -- I think this is a bug, and will report it.
NLS_NUMERIC_CHARACTERS setting for decimal
To know SESSION decimal separator, you can use following SQL command:
ALTER SESSION SET NLS_NUMERIC_CHARACTERS = ', ';
select SUBSTR(value,1,1) as "SEPARATOR"
,'using NLS-PARAMETER' as "Explanation"
from nls_session_parameters
where parameter = 'NLS_NUMERIC_CHARACTERS'
UNION ALL
select SUBSTR(0.5,1,1) as "SEPARATOR"
,'using NUMBER IMPLICIT CASTING' as "Explanation"
from DUAL;
The first SELECT command find NLS Parameter defined in NLS_SESSION_PARAMETERS
table. The decimal separator is the first character of the returned value.
The second SELECT command convert IMPLICITELY the 0.5
rational number into a String using (by default) NLS_NUMERIC_CHARACTERS defined at session level.
The both command return same value.
I have already tested the same SQL command in PL/SQL script and this is always the same value COMMA or POINT that is displayed. Decimal Separator displayed in PL/SQL script is equal to what is displayed in SQL.
To test what I say, I have used following SQL commands:
ALTER SESSION SET NLS_NUMERIC_CHARACTERS = ', ';
select 'DECIMAL-SEPARATOR on CLIENT: (' || TO_CHAR(.5,) || ')' from dual;
DECLARE
S VARCHAR2(10) := '?';
BEGIN
select .5 INTO S from dual;
DBMS_OUTPUT.PUT_LINE('DECIMAL-SEPARATOR in PL/SQL: (' || S || ')');
END;
/
The shorter command to know decimal separator is:
SELECT .5 FROM DUAL;
That return 0,5
if decimal separator is a COMMA and 0.5
if decimal separator is a POINT.
Where does one get the "sys/socket.h" header/source file?
Try to reinstall cygwin with selected package:gcc-g++ : gnu compiler collection c++ (from devel category), openssh server and client program (net), make: the gnu version (devel), ncurses terminal (utils), enhanced vim editors (editors), an ANSI common lisp implementation (math) and libncurses-devel (lib).
This library files should be under cygwin\usr\include
Regards.
pySerial write() won't take my string
It turns out that the string needed to be turned into a bytearray and to do this I editted the code to
ser.write("%01#RDD0010000107**\r".encode())
This solved the problem
Convert multidimensional array into single array
If you come across a multidimensional array that is pure data, like this one below, then you can use a single call to array_merge() to do the job via reflection:
$arrayMult = [ ['a','b'] , ['c', 'd'] ];
$arraySingle = call_user_func_array('array_merge', $arrayMult);
// $arraySingle is now = ['a','b', 'c', 'd'];
Git reset single file in feature branch to be the same as in master
you are almost there; you just need to give the reference to master; since you want to get the file from the master branch:
git checkout master -- filename
Note that the differences will be cached; so if you want to see the differences you obtained; use
git diff --cached
Setting Environment Variables for Node to retrieve
A very good way of doing environment variables I have successfully used is below:
A. Have different config files:
dev.js // this has all environment variables for development only
The file contains:
module.exports = {
ENV: 'dev',
someEnvKey1 : 'some DEV Value1',
someEnvKey2 : 'some DEV Value2'
};
stage.js // this has all environment variables for development only
..
qa.js // this has all environment variables for qa testing only
The file contains:
module.exports = {
ENV: 'dev',
someEnvKey1 : 'some QA Value1',
someEnvKey2 : 'some QA Value2'
};
NOTE: the values are changing with the environment, mostly, but keys remain same.
you can have more
z__prod.js // this has all environment variables for production/live only
NOTE: This file is never bundled for deployment
Put all these config files in /config/ folder
<projectRoot>/config/dev.js
<projectRoot>/config/qa.js
<projectRoot>/config/z__prod.js
<projectRoot>/setenv.js
<projectRoot>/setenv.bat
<projectRoot>/setenv.sh
NOTE: The name of prod is different than others, as it would not be used by all.
B. Set the OS/ Lambda/ AzureFunction/ GoogleCloudFunction environment variables from config file
Now ideally, these config variables in file, should go as OS environment variables (or, LAMBDA function variables, or, Azure function variables, Google Cloud Functions, etc.)
so, we write automation in Windows OS (or other)
Assume we write 'setenv' bat file, which takes one argument that is environment that we want to set
Now run "setenv dev"
a) This takes the input from the passed argument variable ('dev' for now)
b) read the corresponding file ('config\dev.js')
c) sets the environment variables in Windows OS (or other)
For example,
The setenv.bat contents might be:
node setenv.js
The setenv.js contents might be:
// import "process.env.ENV".js file (dev.js example)
// loop the imported file contents
// set the environment variables in Windows OS (or, Lambda, etc.)
That's all, your environment is ready for use.
When you do 'setenv qa', all qa environment variables will be ready for use from qa.js, and ready for use by same program (which always asks for process.env.someEnvKey1, but the value it gets is qa one).
Hope that helps.
MongoDb shuts down with Code 100
This exit code will also be given if you are changing MongoDB versions and the data directory is incompatible, such as with a downgrade. Move the old directory elsewhere, and create a new directory (as per the instructions given in other answers).
How to round a number to significant figures in Python
I ran into this as well but I needed control over the rounding type. Thus, I wrote a quick function (see code below) that can take value, rounding type, and desired significant digits into account.
import decimal
from math import log10, floor
def myrounding(value , roundstyle='ROUND_HALF_UP',sig = 3):
roundstyles = [ 'ROUND_05UP','ROUND_DOWN','ROUND_HALF_DOWN','ROUND_HALF_UP','ROUND_CEILING','ROUND_FLOOR','ROUND_HALF_EVEN','ROUND_UP']
power = -1 * floor(log10(abs(value)))
value = '{0:f}'.format(value) #format value to string to prevent float conversion issues
divided = Decimal(value) * (Decimal('10.0')**power)
roundto = Decimal('10.0')**(-sig+1)
if roundstyle not in roundstyles:
print('roundstyle must be in list:', roundstyles) ## Could thrown an exception here if you want.
return_val = decimal.Decimal(divided).quantize(roundto,rounding=roundstyle)*(decimal.Decimal(10.0)**-power)
nozero = ('{0:f}'.format(return_val)).rstrip('0').rstrip('.') # strips out trailing 0 and .
return decimal.Decimal(nozero)
for x in list(map(float, '-1.234 1.2345 0.03 -90.25 90.34543 9123.3 111'.split())):
print (x, 'rounded UP: ',myrounding(x,'ROUND_UP',3))
print (x, 'rounded normal: ',myrounding(x,sig=3))
Java Date - Insert into database
pst.setDate(6, new java.sql.Date(txtDate.getDate().getTime()));
this is the code I used to save date into the database using jdbc works fine for me
pst
is a variable for preparedstatement
txtdate
is the name for the JDateChooser
how to remove pagination in datatable
$('#table_id').dataTable({
"bInfo": false, //Dont display info e.g. "Showing 1 to 4 of 4 entries"
"paging": false,//Dont want paging
"bPaginate": false,//Dont want paging
})
Try this code
Which data type for latitude and longitude?
Use Point data type to store Longitude and Latitude in a single column:
CREATE TABLE table_name (
id integer NOT NULL,
name text NOT NULL,
location point NOT NULL,
created_on timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT table_name_pkey PRIMARY KEY (id)
)
Create an Indexing on a 'location' column :
CREATE INDEX ON table_name USING GIST(location);
GiST index is capable of optimizing “nearest-neighbor” search :
SELECT * FROM table_name ORDER BY location <-> point '(-74.013, 40.711)' LIMIT 10;
Note: The point first element is longitude and the second element is latitude.
For more info check this Query Operators.
How do I use Spring Boot to serve static content located in Dropbox folder?
Based on @Dave Syer, @kaliatech and @asmaier answers the springboot v2+ way would be:
@Configuration
@AutoConfigureAfter(DispatcherServletAutoConfiguration.class)
public class StaticResourceConfiguration implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
String myExternalFilePath = "file:///C:/temp/whatever/m/";
registry.addResourceHandler("/m/**").addResourceLocations(myExternalFilePath);
}
}
javascript compare strings without being case sensitive
Another method using a regular expression (this is more correct than Zachary's answer):
var string1 = 'someText',
string2 = 'SometexT',
regex = new RegExp('^' + string1 + '$', 'i');
if (regex.test(string2)) {
return true;
}
RegExp.test() will return true or false.
Also, adding the '^' (signifying the start of the string) to the beginning and '$' (signifying the end of the string) to the end make sure that your regular expression will match only if 'sometext' is the only text in stringToTest. If you're looking for text that contains the regular expression, it's ok to leave those off.
It might just be easier to use the string.toLowerCase() method.
So... regular expressions are powerful, but you should only use them if you understand how they work. Unexpected things can happen when you use something you don't understand.
There are tons of regular expression 'tutorials', but most appear to be trying to push a certain product. Here's what looks like a decent tutorial... granted, it's written for using php, but otherwise, it appears to be a nice beginner's tutorial:
http://weblogtoolscollection.com/regex/regex.php
This appears to be a good tool to test regular expressions:
http://gskinner.com/RegExr/
ASP.NET IIS Web.config [Internal Server Error]
I had a problem with runAllManagedModulesForAllRequests, code 0x80070021 and http error 500.19 and managed to solve it
With command prompt launched as Admnistrator, go to : C:\Windows\Microsoft.NET\Framework64\v4.0.30319>
execute
aspnet_regiis -i
bingo!
SQL statement to get column type
For SQL Server, this system stored procedure will return all table information, including column datatypes:
exec sp_help YOURTABLENAME
More than one file was found with OS independent path 'META-INF/LICENSE'
This error is caused by adding a support library instead of AndroidX.
Make sure you use which one:
for AndroidX:
dependencies {
def multidex_version = "2.0.1"
implementation 'androidx.multidex:multidex:$multidex_version'
}
If you aren't using AndroidX:
dependencies {
implementation 'com.android.support:multidex:1.0.3'
}
Also in manifest use the application class name instead of "android.support.multidex.MultiDexApplication" in the application tag(my application class name is G):
the mistake:
<application
android:name="android.support.multidex.MultiDexApplication" >
...
</application>
right:
<application
android:name=".G" >
...
</application>