What is /var/www/html?
In the most shared hosts you can't set it.
On a VPS or dedicated server, you can set it, but everything has its price.
On shared hosts, in general you receive a Linux account, something such as /home/(your username)/, and the equivalent of /var/www/html turns to /home/(your username)/public_html/ (or something similar, such as /home/(your username)/www)
If you're accessing your account via FTP, you automatically has accessing the your */home/(your username)/ folder, just find the www or public_html and put your site in it.
If you're using absolute path in the code, bad news, you need to refactor it to use relative paths in the code, at least in a shared host.
Find the IP address of the client in an SSH session
You can get it in a programmatic way via an SSH library (https://code.google.com/p/sshxcute)
public static String getIpAddress() throws TaskExecFailException{
ConnBean cb = new ConnBean(host, username, password);
SSHExec ssh = SSHExec.getInstance(cb);
ssh.connect();
CustomTask sampleTask = new ExecCommand("echo \"${SSH_CLIENT%% *}\"");
String Result = ssh.exec(sampleTask).sysout;
ssh.disconnect();
return Result;
}
How to get a dependency tree for an artifact?
If you bother creating a sample project and adding your 3rd party dependency to that, then you can run the following in order to see the full hierarchy of the dependencies.
You can search for a specific artifact using this maven command:
mvn dependency:tree -Dverbose -Dincludes=[groupId]:[artifactId]:[type]:[version]
According to the documentation:
where each pattern segment is optional and supports full and partial * wildcards. An empty pattern segment is treated as an implicit wildcard.
Imagine you are trying to find 'log4j-1.2-api' jar file among different modules of your project:
mvn dependency:tree -Dverbose -Dincludes=org.apache.logging.log4j:log4j-1.2-api
more information can be found here.
Edit: Please note that despite the advantages of using verbose parameter, it might not be so accurate in some conditions. Because it uses Maven 2 algorithm and may give wrong results when used with Maven 3.
download a file from Spring boot rest service
Option 1 using an InputStreamResource
Resource implementation for a given InputStream.
Should only be used if no other specific Resource implementation is > applicable. In particular, prefer ByteArrayResource or any of the file-based Resource implementations where possible.
@RequestMapping(path = "/download", method = RequestMethod.GET)
public ResponseEntity<Resource> download(String param) throws IOException {
// ...
InputStreamResource resource = new InputStreamResource(new FileInputStream(file));
return ResponseEntity.ok()
.headers(headers)
.contentLength(file.length())
.contentType(MediaType.APPLICATION_OCTET_STREAM)
.body(resource);
}
Option2 as the documentation of the InputStreamResource suggests - using a ByteArrayResource:
@RequestMapping(path = "/download", method = RequestMethod.GET)
public ResponseEntity<Resource> download(String param) throws IOException {
// ...
Path path = Paths.get(file.getAbsolutePath());
ByteArrayResource resource = new ByteArrayResource(Files.readAllBytes(path));
return ResponseEntity.ok()
.headers(headers)
.contentLength(file.length())
.contentType(MediaType.APPLICATION_OCTET_STREAM)
.body(resource);
}
How can I loop through enum values for display in radio buttons?
Two options:
for (let item in MotifIntervention) {
if (isNaN(Number(item))) {
console.log(item);
}
}
Or
Object.keys(MotifIntervention).filter(key => !isNaN(Number(MotifIntervention[key])));
(code in playground)
Edit
String enums look different than regular ones, for example:
enum MyEnum {
A = "a",
B = "b",
C = "c"
}
Compiles into:
var MyEnum;
(function (MyEnum) {
MyEnum["A"] = "a";
MyEnum["B"] = "b";
MyEnum["C"] = "c";
})(MyEnum || (MyEnum = {}));
Which just gives you this object:
{
A: "a",
B: "b",
C: "c"
}
You can get all the keys (["A", "B", "C"]
) like this:
Object.keys(MyEnum);
And the values (["a", "b", "c"]
):
Object.keys(MyEnum).map(key => MyEnum[key])
Or using Object.values():
Object.values(MyEnum)
Java - get the current class name?
I've found this to work for my code,, however my code is getting the class out of an array within a for loop.
String className="";
className = list[i].getClass().getCanonicalName();
System.out.print(className); //Use this to test it works
CSS how to make an element fade in and then fade out?
If you need a single fadeIn/Out without an explicit user action (like a mouseover/mouseout) you may use a CSS3 animation
: http://codepen.io/anon/pen/bdEpwW
.elementToFadeInAndOut {
animation: fadeinout 4s linear 1 forwards;
}
@keyframes fadeinout {
0% { opacity: 0; }
50% { opacity: 1; }
100% { opacity: 0; }
}
By setting animation-fill-mode: forwards
the animation will retain its last keyframe
By setting animation-iteration-count: 1
the animation will run just once (change this value if you need to repeat the effect more than once)
Circular (or cyclic) imports in Python
I completely agree with pythoneer's answer here. But I have stumbled on some code that was flawed with circular imports and caused issues when trying to add unit tests. So to quickly patch it without changing everything you can resolve the issue by doing a dynamic import.
# Hack to import something without circular import issue
def load_module(name):
"""Load module using imp.find_module"""
names = name.split(".")
path = None
for name in names:
f, path, info = imp.find_module(name, path)
path = [path]
return imp.load_module(name, f, path[0], info)
constants = load_module("app.constants")
Again, this isn't a permanent fix but may help someone that wants to fix an import error without changing too much of the code.
Cheers!
Python: Removing spaces from list objects
Presuming that you don't want to remove internal spaces:
def normalize_space(s):
"""Return s stripped of leading/trailing whitespace
and with internal runs of whitespace replaced by a single SPACE"""
# This should be a str method :-(
return ' '.join(s.split())
replacement = [normalize_space(i) for i in hello]
Count all values in a matrix greater than a value
The numpy.where
function is your friend. Because it's implemented to take full advantage of the array datatype, for large images you should notice a speed improvement over the pure python solution you provide.
Using numpy.where directly will yield a boolean mask indicating whether certain values match your conditions:
>>> data
array([[1, 8],
[3, 4]])
>>> numpy.where( data > 3 )
(array([0, 1]), array([1, 1]))
And the mask can be used to index the array directly to get the actual values:
>>> data[ numpy.where( data > 3 ) ]
array([8, 4])
Exactly where you take it from there will depend on what form you'd like the results in.
Apache2: 'AH01630: client denied by server configuration'
If you have https host then don't forget to make Require all granted
changes for ssl config too.
Also, sometimes it's useful to check permissions as the apache user:
# ps -eFH | grep http # get the username used by httpd
...
apache 18837 2692 0 119996 9328 9 10:33 ? 00:00:00 /usr/sbin/httpd -DFOREGROUND
# su -s/bin/bash apache # switch to that user
bash-4.2$ whoami
apache
bash-4.2$ cd /home
bash-4.2$ ls
bash-4.2$ cd mysite.com
bash-4.2$ ls
bash-4.2$ cat file-which-does-not-work.txt
Get Value of Row in Datatable c#
Dont use a foreach then. Use a 'for loop'. Your code is a bit messed up but you could do something like...
for (Int32 i = 0; i < dt_pattern.Rows.Count; i++)
{
double yATmax = ToDouble(dt_pattern.Rows[i+1]["Ampl"].ToString()) + AT;
}
Note you would have to take into account during the last row there will be no 'i+1' so you will have to use an if statement to catch that.
How to use export with Python on Linux
Not that simple:
python -c "import os; os.putenv('MY_DATA','1233')"
$ echo $MY_DATA # <- empty
But:
python -c "import os; os.putenv('MY_DATA','123'); os.system('bash')"
$ echo $MY_DATA #<- 123
Auto-indent in Notepad++
This may seem silly, but in the original question, Turion was editing a plain text file. Make sure you choose the correct language from the Language menu
git rebase merge conflict
When you have a conflict during rebase you have three options:
You can run git rebase --abort
to completely undo the rebase. Git will return you to your branch's state as it was before git rebase was called.
You can run git rebase --skip
to completely skip the commit. That means
that none of the changes introduced by the problematic commit will be included. It is very rare that you would choose this option.
You can fix the conflict as iltempo said. When you're finished, you'll need to call git rebase --continue
. My mergetool is kdiff3 but there are many more which you can use to solve conflicts. You only need to set your merge tool in git's settings so it can be invoked when you call git mergetool
https://git-scm.com/docs/git-mergetool
If none of the above works for you, then go for a walk and try again :)
How to work with progress indicator in flutter?
1. Without plugin
class IndiSampleState extends State<ProgHudPage> {
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text('Demo'),
),
body: Center(
child: RaisedButton(
color: Colors.blueAccent,
child: Text('Login'),
onPressed: () async {
showDialog(
context: context,
builder: (BuildContext context) {
return Center(child: CircularProgressIndicator(),);
});
await loginAction();
Navigator.pop(context);
},
),
));
}
Future<bool> loginAction() async {
//replace the below line of code with your login request
await new Future.delayed(const Duration(seconds: 2));
return true;
}
}
2. With plugin
check this plugin progress_hud
add the dependency in the pubspec.yaml file
dev_dependencies:
progress_hud:
import the package
import 'package:progress_hud/progress_hud.dart';
Sample code is given below to show and hide the indicator
class ProgHudPage extends StatefulWidget {
@override
_ProgHudPageState createState() => _ProgHudPageState();
}
class _ProgHudPageState extends State<ProgHudPage> {
ProgressHUD _progressHUD;
@override
void initState() {
_progressHUD = new ProgressHUD(
backgroundColor: Colors.black12,
color: Colors.white,
containerColor: Colors.blue,
borderRadius: 5.0,
loading: false,
text: 'Loading...',
);
super.initState();
}
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text('ProgressHUD Demo'),
),
body: new Stack(
children: <Widget>[
_progressHUD,
new Positioned(
child: RaisedButton(
color: Colors.blueAccent,
child: Text('Login'),
onPressed: () async{
_progressHUD.state.show();
await loginAction();
_progressHUD.state.dismiss();
},
),
bottom: 30.0,
right: 10.0)
],
));
}
Future<bool> loginAction()async{
//replace the below line of code with your login request
await new Future.delayed(const Duration(seconds: 2));
return true;
}
}
Switch to another Git tag
As of Git v2.23.0 (August 2019), git switch
is preferred over git checkout
when you’re simply switching branches/tags. I’m guessing they did this since git checkout
had two functions: for switching branches and for restoring files. So in v2.23.0, they added two new commands, git switch
, and git restore
, to separate those concerns. I would predict at some point in the future, git checkout
will be deprecated.
To switch to a normal branch, use git switch <branch-name>
. To switch to a commit-like object, including single commits and tags, use git switch --detach <commitish>
, where <commitish>
is the tag name or commit number.
The --detach
option forces you to recognize that you’re in a mode of “inspection and discardable experiments”. To create a new branch from the commitish you’re switching to, use git switch -c <new-branch> <start-point>
.
JAX-RS — How to return JSON and HTTP status code together?
There are several use cases for setting HTTP status codes in a REST web service, and at least one was not sufficiently documented in the existing answers (i.e. when you are using auto-magical JSON/XML serialization using JAXB, and you want to return an object to be serialized, but also a status code different than the default 200).
So let me try and enumerate the different use cases and the solutions for each one:
1. Error code (500, 404,...)
The most common use case when you want to return a status code different than 200 OK
is when an error occurs.
For example:
- an entity is requested but it doesn't exist (404)
- the request is semantically incorrect (400)
- the user is not authorized (401)
- there is a problem with the database connection (500)
- etc..
a) Throw an exception
In that case, I think that the cleanest way to handle the problem is to throw an exception. This exception will be handled by an ExceptionMapper
, that will translate the exception into a response with the appropriate error code.
You can use the default ExceptionMapper
that comes pre-configured with Jersey (and I guess it's the same with other implementations) and throw any of the existing sub-classes of javax.ws.rs.WebApplicationException
. These are pre-defined exception types that are pre-mapped to different error codes, for example:
- BadRequestException (400)
- InternalServerErrorException (500)
- NotFoundException (404)
Etc. You can find the list here: API
Alternatively, you can define your own custom exceptions and ExceptionMapper
classes, and add these mappers to Jersey by the mean of the @Provider
annotation (source of this example):
public class MyApplicationException extends Exception implements Serializable
{
private static final long serialVersionUID = 1L;
public MyApplicationException() {
super();
}
public MyApplicationException(String msg) {
super(msg);
}
public MyApplicationException(String msg, Exception e) {
super(msg, e);
}
}
Provider :
@Provider
public class MyApplicationExceptionHandler implements ExceptionMapper<MyApplicationException>
{
@Override
public Response toResponse(MyApplicationException exception)
{
return Response.status(Status.BAD_REQUEST).entity(exception.getMessage()).build();
}
}
Note: you can also write ExceptionMappers for existing exception types that you use.
b) Use the Response builder
Another way to set a status code is to use a Response
builder to build a response with the intended code.
In that case, your method's return type must be javax.ws.rs.core.Response
. This is described in various other responses such as hisdrewness' accepted answer and looks like this :
@GET
@Path("myresource({id}")
public Response retrieveSomething(@PathParam("id") String id) {
...
Entity entity = service.getById(uuid);
if(entity == null) {
return Response.status(Response.Status.NOT_FOUND).entity("Resource not found for ID: " + uuid).build();
}
...
}
2. Success, but not 200
Another case when you want to set the return status is when the operation was successful, but you want to return a success code different than 200, along with the content that you return in the body.
A frequent use case is when you create a new entity (POST
request) and want to return info about this new entity or maybe the entity itself, together with a 201 Created
status code.
One approach is to use the response object just like described above and set the body of the request yourself. However, by doing this you loose the ability to use the automatic serialization to XML or JSON provided by JAXB.
This is the original method returning an entity object that will be serialized to JSON by JAXB:
@Path("/")
@POST
@Consumes({ MediaType.APPLICATION_JSON })
@Produces({ MediaType.APPLICATION_JSON })
public User addUser(User user){
User newuser = ... do something like DB insert ...
return newuser;
}
This will return a JSON representation of the newly created user, but the return status will be 200, not 201.
Now the problem is if I want to use the Response
builder to set the return code, I have to return a Response
object in my method. How do I still return the User
object to be serialized?
a) Set the code on the servlet response
One approach to solve this is to obtain a servlet request object and set the response code manually ourselves, like demonstrated in Garett Wilson's answer :
@Path("/")
@POST
@Consumes({ MediaType.APPLICATION_JSON })
@Produces({ MediaType.APPLICATION_JSON })
public User addUser(User user, @Context final HttpServletResponse response){
User newUser = ...
//set HTTP code to "201 Created"
response.setStatus(HttpServletResponse.SC_CREATED);
try {
response.flushBuffer();
}catch(Exception e){}
return newUser;
}
The method still returns an entity object and the status code will be 201.
Note that to make it work, I had to flush the response. This is an unpleasant resurgence of low-level Servlet API code in our nice JAX_RS resource, and much worse, it causes the headers to be unmodifiable after this because they were already sent on the wire.
b) Use the response object with the entity
The best solution, in that case, is to use the Response object and set the entity to be serialized on this response object. It would be nice to make the Response object generic to indicate the type of the payload entity in that case, but is not the currently the case.
@Path("/")
@POST
@Consumes({ MediaType.APPLICATION_JSON })
@Produces({ MediaType.APPLICATION_JSON })
public Response addUser(User user){
User newUser = ...
return Response.created(hateoas.buildLinkUri(newUser, "entity")).entity(restResponse).build();
}
In that case, we use the created method of the Response builder class in order to set the status code to 201. We pass the entity object (user) to the response via the entity() method.
The result is that the HTTP code is 401 as we wanted, and the body of the response is the exact same JSON as we had before when we just returned the User object. It also adds a location header.
The Response class has a number of builder method for different statuses (stati ?) such as :
Response.accepted()
Response.ok()
Response.noContent()
Response.notAcceptable()
NB: the hateoas object is a helper class that I developed to help generate resources URIs. You will need to come up with your own mechanism here ;)
That's about it.
I hope this lengthy response helps somebody :)
What is a NoReverseMatch error, and how do I fix it?
It may be that it's not loading the template you expect. I added a new class that inherited from UpdateView
- I thought it would automatically pick the template from what I named my class, but it actually loaded it based on the model
property on the class, which resulted in another (wrong) template being loaded. Once I explicitly set template_name
for the new class, it worked fine.
How to replace ${} placeholders in a text file?
template.txt
Variable 1 value: ${var1}
Variable 2 value: ${var2}
data.sh
#!/usr/bin/env bash
declare var1="value 1"
declare var2="value 2"
parser.sh
#!/usr/bin/env bash
# args
declare file_data=$1
declare file_input=$2
declare file_output=$3
source $file_data
eval "echo \"$(< $file_input)\"" > $file_output
./parser.sh data.sh template.txt parsed_file.txt
parsed_file.txt
Variable 1 value: value 1
Variable 2 value: value 2
How does one sum only those rows in excel not filtered out?
When you use autofilter to filter results, Excel doesn't even bother to hide them: it just sets the height of the row to zero (up to 2003 at least, not sure on 2007).
So the following custom function should give you a starter to do what you want (tested with integers, haven't played with anything else):
Function SumVis(r As Range)
Dim cell As Excel.Range
Dim total As Variant
For Each cell In r.Cells
If cell.Height <> 0 Then
total = total + cell.Value
End If
Next
SumVis = total
End Function
Edit:
You'll need to create a module in the workbook to put the function in, then you can just call it on your sheet like any other function (=SumVis(A1:A14)). If you need help setting up the module, let me know.
How to create a windows service from java app
I didn't like the licensing for the Java Service Wrapper. I went with ActiveState Perl to write a service that does the work.
I thought about writing a service in C#, but my time constraints were too tight.
Could not load file or assembly "Oracle.DataAccess" or one of its dependencies
In my case I had a console application, I just unchecked Prefer 32-bit on Build projet properties tab and then I add this to my app.config:
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="Oracle.DataAccess" publicKeyToken="89b483f429c47342" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-5.0.0.0" newVersion="2.112.1.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
How do I access the $scope variable in browser's console using AngularJS?
Just define a JavaScript variable outside the scope and assign it to your scope in your controller:
var myScope;
...
app.controller('myController', function ($scope,log) {
myScope = $scope;
...
That's it! It should work in all browsers (tested at least in Chrome and Mozilla).
It is working, and I'm using this method.
Making Maven run all tests, even when some fail
From the Maven Embedder documentation:
-fae
,--fail-at-end
Only fail the build afterwards; allow all non-impacted builds to continue
-fn
,--fail-never
NEVER fail the build, regardless of project result
So if you are testing one module than you are safe using -fae
.
Otherwise, if you have multiple modules, and if you want all of them tested (even the ones that depend on the failing tests module), you should run mvn clean install -fn
.
-fae
will continue with the module that has a failing test (will run all other tests), but all modules that depend on it will be skipped.
HTML5 - mp4 video does not play in IE9
Try the following and see if it works:
<video width="400" height="300" preload controls>
<source src="video.mp4" type="video/mp4" />
Your browser does not support the video tag.
</video>
Add borders to cells in POI generated Excel File
Setting up borders in the style used in the cells will accomplish this. Example:
style.setBorderBottom(HSSFCellStyle.BORDER_MEDIUM);
style.setBorderTop(HSSFCellStyle.BORDER_MEDIUM);
style.setBorderRight(HSSFCellStyle.BORDER_MEDIUM);
style.setBorderLeft(HSSFCellStyle.BORDER_MEDIUM);
Choice between vector::resize() and vector::reserve()
reserve when you do not want the objects to be initialized when reserved. also, you may prefer to logically differentiate and track its count versus its use count when you resize. so there is a behavioral difference in the interface - the vector will represent the same number of elements when reserved, and will be 100 elements larger when resized in your scenario.
Is there any better choice in this kind of scenario?
it depends entirely on your aims when fighting the default behavior. some people will favor customized allocators -- but we really need a better idea of what it is you are attempting to solve in your program to advise you well.
fwiw, many vector implementations will simply double the allocated element count when they must grow - are you trying to minimize peak allocation sizes or are you trying to reserve enough space for some lock free program or something else?
How to create a cron job using Bash automatically without the interactive editor?
You can probably change the default editor to ed and use a heredoc to edit.
EDITOR=ed
export EDITOR
crontab -e << EOF
> a
> * * * * * Myscript
> * * * * * AnotherScript
> * * * * * MoreScript
> .
> w
> q
> EOF
Note the leading > in that code means the return/enter key is pressed to create a new line.
The a means APPEND so it will not overwrite anything.
The . means you're done editing.
The w means WRITE the changes.
The q means QUIT or exit ed.
you can check it out
crontab -l
You can delete an entry too.
EDITOR=ed
export EDITOR
crontab -e << EOF
> /Myscript/
> d
> .
> w
> q
> EOF
That will delete the crontab entry with Myscript in it.
The d means delete the pattern inside the / /.
No check it again
crontab -l
This solution works inside a script too less the > of course :-)
input() error - NameError: name '...' is not defined
There are two ways to fix these issues,
1st is simple without code change that is
run your script by Python3,
if you still want to run on python2 then
after running your python script, when you are entering the input keep in mind
- if you want to enter
string
then just start typing down with "input goes with double-quote" and it will work in python2.7 and
- if you want to enter character then use the input with a single quote like 'your input goes here'
- if you want to enter number not an issue you simply type the number
2nd way is with code changes
use the below import and run with any version of python
from six.moves import input
- Use
raw_input()
function instead of input()
function in your code with any import
- sanitise your code with
str()
function like str(input())
and then assign to any variable
As error implies:
name 'dude' is not defined
i.e. for python 'dude' become variable here and it's not having any value of python defined type assigned
so only its crying like baby so if we define a 'dude' variable and assign any value and pass to it, it will work but that's not what we want as we don't know what user will enter and moreover we want to capture the user input.
Fact about these method:
input()
function: This function takes the value and type of the input you enter as it is without modifying it type.
raw_input()
function: This function explicitly converts the input you give into type string,
Note:
The vulnerability in input() method lies in the fact that
the variable accessing the value of input can be accessed by anyone
just by using the name of variable or method.
How to align texts inside of an input?
Use the text-align property in your CSS:
input {
text-align: right;
}
This will take effect in all the inputs of the page.
Otherwise, if you want to align the text of just one input, set the style inline:
<input type="text" style="text-align:right;"/>
Replace given value in vector
Perhaps replace
is what you are looking for:
> x = c(3, 2, 1, 0, 4, 0)
> replace(x, x==0, 1)
[1] 3 2 1 1 4 1
Or, if you don't have x
(any specific reason why not?):
replace(c(3, 2, 1, 0, 4, 0), c(3, 2, 1, 0, 4, 0)==0, 1)
Many people are familiar with gsub
, so you can also try either of the following:
as.numeric(gsub(0, 1, x))
as.numeric(gsub(0, 1, c(3, 2, 1, 0, 4, 0)))
Update
After reading the comments, perhaps with
is an option:
with(data.frame(x = c(3, 2, 1, 0, 4, 0)), replace(x, x == 0, 1))
Java: Calculating the angle between two points in degrees
you could add the following:
public float getAngle(Point target) {
float angle = (float) Math.toDegrees(Math.atan2(target.y - y, target.x - x));
if(angle < 0){
angle += 360;
}
return angle;
}
by the way, why do you want to not use a double here?
How to get a Char from an ASCII Character Code in c#
You can simply write:
char c = (char) 2;
or
char c = Convert.ToChar(2);
or more complex option for ASCII encoding only
char[] characters = System.Text.Encoding.ASCII.GetChars(new byte[]{2});
char c = characters[0];
setting min date in jquery datepicker
The problem is that the default option of "yearRange" is 10 years.
So 2012 - 10 = 2002
.
So change the yearRange to c-20:c
or just 1999 (yearRange: '1999:c'
), and use that in combination with restrict dates (mindate, maxdate).
For more info: http://jqueryui.com/demos/datepicker/#option-yearRange
See example: http://jsfiddle.net/kGjdL/
And your code with the addition:
$(function () {
$('#datepicker').datepicker({
dateFormat: 'yy-mm-dd',
showButtonPanel: true,
changeMonth: true,
changeYear: true,
showOn: "button",
buttonImage: "images/calendar.gif",
buttonImageOnly: true,
minDate: new Date(1999, 10 - 1, 25),
maxDate: '+30Y',
yearRange: '1999:c',
inline: true
});
});
Which method performs better: .Any() vs .Count() > 0?
If you are using the Entity Framework and have a huge table with many records Any() will be much faster. I remember one time I wanted to check to see if a table was empty and it had millions of rows. It took 20-30 seconds for Count() > 0 to complete. It was instant with Any().
Any() can be a performance enhancement because it may not have to iterate the collection to get the number of things. It just has to hit one of them. Or, for, say, LINQ-to-Entities, the generated SQL will be IF EXISTS(...) rather than SELECT COUNT ... or even SELECT * ....
How to ignore SSL certificate errors in Apache HttpClient 4.0
If you are using Apache httpClient 4.5.x then try this:
public static void main(String... args) {
try (CloseableHttpClient httpclient = createAcceptSelfSignedCertificateClient()) {
HttpGet httpget = new HttpGet("https://example.com");
System.out.println("Executing request " + httpget.getRequestLine());
httpclient.execute(httpget);
System.out.println("----------------------------------------");
} catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException | IOException e) {
throw new RuntimeException(e);
}
}
private static CloseableHttpClient createAcceptSelfSignedCertificateClient()
throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException {
// use the TrustSelfSignedStrategy to allow Self Signed Certificates
SSLContext sslContext = SSLContextBuilder
.create()
.loadTrustMaterial(new TrustSelfSignedStrategy())
.build();
// we can optionally disable hostname verification.
// if you don't want to further weaken the security, you don't have to include this.
HostnameVerifier allowAllHosts = new NoopHostnameVerifier();
// create an SSL Socket Factory to use the SSLContext with the trust self signed certificate strategy
// and allow all hosts verifier.
SSLConnectionSocketFactory connectionFactory = new SSLConnectionSocketFactory(sslContext, allowAllHosts);
// finally create the HttpClient using HttpClient factory methods and assign the ssl socket factory
return HttpClients
.custom()
.setSSLSocketFactory(connectionFactory)
.build();
}
How do I rename a MySQL schema?
If you're on the Model Overview page you get a tab with the schema. If you rightclick on that tab you get an option to "edit schema". From there you can rename the schema by adding a new name, then click outside the field. This goes for MySQL Workbench 5.2.30 CE
Edit: On the model overview it's under Physical Schemata
Screenshot:
Converting from a string to boolean in Python?
If you have control over the entity that's returning true
/false
, one option is to have it return 1
/0
instead of true
/false
, then:
boolean_response = bool(int(response))
The extra cast to int
handles responses from a network, which are always string.
Update 2021: "which are always string" -- this is a naive observation. It depends on the serialization protocol used by the library. Default serialization of high-level libraries (the ones used by most web devs) is typically to convert to string before being serialized to bytes. And then on the other side, it's deserialized from bytes to string, so you've lost any type information.
How do I make a WinForms app go Full Screen
You can use the following code to fit your system screen and task bar is visible.
private void Form1_Load(object sender, EventArgs e)
{
// hide max,min and close button at top right of Window
this.FormBorderStyle = FormBorderStyle.None;
// fill the screen
this.Bounds = Screen.PrimaryScreen.Bounds;
}
No need to use:
this.TopMost = true;
That line interferes with alt+tab
to switch to other application. ("TopMost" means the window stays on top of other windows, unless they are also marked "TopMost".)
mysql said: Cannot connect: invalid settings. xampp
I'm using MAMP, but looks like the exact same issue.
I changed my root password via phpMyAdmin and got locked out as described. I saw this thread and tried to get it working with the new password but the config updates didn't seem to work for me.
I tried to revert, changed the root password back, but it wasn't working, so I hunted around to try and revert my password back to the original. Eventually I discovered that for some strange reason there were multiple root users, root@localhost, [email protected], root@::1!
To get it back working basically I did this:
mysql -u root -p
mysql> use mysql;
mysql> update user set password=PASSWORD("root") where User='root';
mysql> flush privileges;
mysql> quit
After that I removed all the root users other than localhost (using phpMyAdmin), and I could still login... so, not sure why they were there in the first place.
Then, I discovered that MAMP Pro has a button under the MySQL tab that sets the root password. I'm not sure what files it edits, or services it restarts, etc... but it worked.
References:
Styling input buttons for iPad and iPhone
I recently came across this problem myself.
<!--Instead of using input-->
<input type="submit"/>
<!--Use button-->
<button type="submit">
<!--You can then attach your custom CSS to the button-->
Hope that helps.
Disable sorting on last column when using jQuery DataTables
I would like to develop the current answer.
The good way is to use aoColumnDefs
as mentioned.
The default value for the bSortable
parameter is true
(for each column).
You've got 2 options...
By index :
var table = $('#example').DataTable({
'aoColumnDefs': [{
'bSortable': false,
'aTargets': [-1] /* 1st one, start by the right */
}]
});
By class :
var table = $('#example').DataTable({
'aoColumnDefs': [{
'bSortable': false,
'aTargets': ['nosort']
}]
});
Adding the class on the <th>
:
<table>
<thead>
<tr>
<th>Foo</th>
<th>Bar</th>
<th class="nosort">Baz</th>
</tr>
</thead>
<tbody>...</tbody>
</table>
Documentation about columns
JSBin
Command output redirect to file and terminal
In case somebody needs to append the output and not overriding, it is possible to use "-a" or "--append" option of "tee" command :
ls 2>&1 | tee -a /tmp/ls.txt
ls 2>&1 | tee --append /tmp/ls.txt
how to avoid extra blank page at end while printing?
You could maybe add
.print:last-child {
page-break-after: auto;
}
so the last print
element will not get the extra page break.
Do note that the :last-child selector is not supported in IE8, if you're targetting that wretch of a browser.
What is the proper way to test if a parameter is empty in a batch file?
I created this small batch script based on the answers here, as there are many valid ones. Feel free to add to this so long as you follow the same format:
REM Parameter-testing
Setlocal EnableDelayedExpansion EnableExtensions
IF NOT "%~1"=="" (echo Percent Tilde 1 failed with quotes) ELSE (echo SUCCESS)
IF NOT [%~1]==[] (echo Percent Tilde 1 failed with brackets) ELSE (echo SUCCESS)
IF NOT "%1"=="" (echo Quotes one failed) ELSE (echo SUCCESS)
IF NOT [%1]==[] (echo Brackets one failed) ELSE (echo SUCCESS)
IF NOT "%1."=="." (echo Appended dot quotes one failed) ELSE (echo SUCCESS)
IF NOT [%1.]==[.] (echo Appended dot brackets one failed) ELSE (echo SUCCESS)
pause
Explode string by one or more spaces or tabs
In order to account for full width space such as
full width
you can extend Bens answer to this:
$searchValues = preg_split("@[\s+ ]@u", $searchString);
Sources:
(I don't have enough reputation to post a comment, so I'm wrote this as an answer.)
Check that a input to UITextField is numeric only
@property (strong) NSNumberFormatter *numberFormatter;
@property (strong) NSString *oldStringValue;
- (void)awakeFromNib
{
[super awakeFromNib];
self.numberFormatter = [[NSNumberFormatter alloc] init];
self.oldStringValue = self.stringValue;
[self setDelegate:self];
}
- (void)controlTextDidChange:(NSNotification *)obj
{
NSNumber *number = [self.numberFormatter numberFromString:self.stringValue];
if (number) {
self.oldStringValue = self.stringValue;
} else {
self.stringValue = self.oldStringValue;
}
}
Curl Command to Repeat URL Request
You could use URL sequence substitution with a dummy query string (if you want to use CURL and save a few keystrokes):
curl http://www.myurl.com/?[1-20]
If you have other query strings in your URL, assign the sequence to a throwaway variable:
curl http://www.myurl.com/?myVar=111&fakeVar=[1-20]
Check out the URL section on the man page: https://curl.haxx.se/docs/manpage.html
How to concatenate two strings in SQL Server 2005
DECLARE @COMBINED_STRINGS AS VARCHAR(50),
@STRING1 AS VARCHAR(20),
@STRING2 AS VARCHAR(20);
SET @STRING1 = 'rupesh''s';
SET @STRING2 = 'malviya';
SET @COMBINED_STRINGS = @STRING1 + @STRING2;
SELECT @COMBINED_STRINGS;
SELECT '2' + '3';
I typed this in a sql file named TEST.sql and I run it. I got the following out put.
+-------------------+
| @COMBINED_STRINGS |
+-------------------+
| 0 |
+-------------------+
1 row in set (0.00 sec)
+-----------+
| '2' + '3' |
+-----------+
| 5 |
+-----------+
1 row in set (0.00 sec)
After looking into this issue a bit more I found the best and sure sort way for string concatenation in SQL is by using CONCAT method.
So I made the following changes in the same file.
#DECLARE @COMBINED_STRINGS AS VARCHAR(50),
# @STRING1 AS VARCHAR(20),
# @STRING2 AS VARCHAR(20);
SET @STRING1 = 'rupesh''s';
SET @STRING2 = 'malviya';
#SET @COMBINED_STRINGS = @STRING1 + @STRING2;
SET @COMBINED_STRINGS = (SELECT CONCAT(@STRING1, @STRING2));
SELECT @COMBINED_STRINGS;
#SELECT '2' + '3';
SELECT CONCAT('2','3');
and after executing the file this was the output.
+-------------------+
| @COMBINED_STRINGS |
+-------------------+
| rupesh'smalviya |
+-------------------+
1 row in set (0.00 sec)
+-----------------+
| CONCAT('2','3') |
+-----------------+
| 23 |
+-----------------+
1 row in set (0.00 sec)
SQL version I am using is: 14.14
When to use IMG vs. CSS background-image?
Use CSS background-image in a case of multiple skins or versions of design. Javascript can be used to dynamically change a class of an element, which will force it to render a different image. With an IMG tag, it may be more tricky.
Custom "confirm" dialog in JavaScript?
You should take a look at SweetAlert as an option to save some work. It's beautiful from the default state and is highly customizable.
Confirm Example
sweetAlert(
{
title: "Are you sure?",
text: "You will not be able to recover this imaginary file!",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "Yes, delete it!"
},
deleteIt()
);
Get user location by IP address
IPInfoDB has an API that you can call in order to find a location based on an IP address.
For "City Precision", you call it like this (you'll need to register to get a free API key):
http://api.ipinfodb.com/v2/ip_query.php?key=<your_api_key>&ip=74.125.45.100&timezone=false
Here's an example in both VB and C# that shows how to call the API.
Is there a regular expression to detect a valid regular expression?
No, if you use standard regular expressions.
The reason is that you cannot satisfy the pumping lemma for regular languages. The pumping lemma states that a string belonging to language "L" is regular if there exists a number "N" such that, after dividing the string into three substrings x
, y
, z
, such that |x|>=1 && |xy|<=N
, you can repeat y
as many times as you want and the entire string will still belong to L
.
A consequence of the pumping lemma is that you cannot have regular strings in the form a^Nb^Mc^N
, that is, two substrings having the same length separated by another string. In any way you split such strings in x
, y
and z
, you cannot "pump" y
without obtaining a string with a different number of "a" and "c", thus leaving the original language. That's the case, for example, with parentheses in regular expressions.
SCRIPT438: Object doesn't support property or method IE
After some days searching the Internet I found that this error usually occurs when an html element id has the same id as some variable in the javascript function. After changing the name of one of them my code was working fine.
Could not resolve '...' from state ''
Had the same issue with Ionic routing.
Simple solution is to use the name of the state - basically state.go(state name)
.state('tab.search', {
url: '/search',
views: {
'tab-search': {
templateUrl: 'templates/search.html',
controller: 'SearchCtrl'
}
}
})
And in controller you can use $state.go('tab.search');
How do I limit the number of decimals printed for a double?
Use a DecimalFormatter:
double number = 0.9999999999999;
DecimalFormat numberFormat = new DecimalFormat("#.00");
System.out.println(numberFormat.format(number));
Will give you "0.99". You can add or subtract 0 on the right side to get more or less decimals.
Or use '#' on the right to make the additional digits optional, as in with #.## (0.30) would drop the trailing 0 to become (0.3).
Creating a LinkedList class from scratch
Sure, a Linked List is a bit confusing for programming n00bs, pretty much the temptation is to look at it as Russian Dolls, because that's what it seems like, a LinkedList Object in a LinkedList Object. But that's a touch difficult to visualize, instead look at it like a computer.
LinkedList = Data + Next Member
Where it's the last member of the list if next is NULL
So a 5 member LinkedList would be:
LinkedList(Data1, LinkedList(Data2, LinkedList(Data3, LinkedList(Data4, LinkedList(Data5, NULL)))))
But you can think of it as simply:
Data1 -> Data2 -> Data3 -> Data4 -> Data5 -> NULL
So, how do we find the end of this? Well, we know that the NULL is the end so:
public void append(LinkedList myNextNode) {
LinkedList current = this; //Make a variable to store a pointer to this LinkedList
while (current.next != NULL) { //While we're not at the last node of the LinkedList
current = current.next; //Go further down the rabbit hole.
}
current.next = myNextNode; //Now we're at the end, so simply replace the NULL with another Linked List!
return; //and we're done!
}
This is very simple code of course, and it will infinitely loop if you feed it a circularly linked list! But that's the basics.
What is the difference between a URI, a URL and a URN?
Here is my simplification:
URN: unique resource name, i.e. "what" (eg urn:issn:1234-5678 ). This is meant to be unique .. as in no two different docs can have the same urn. A bit like "uuid"
URL: "where" to find it ( eg https://google.com/pub?issnid=1234-5678 .. or
ftp://somesite.com/doc8.pdf )
URI: can be either a URN or a URL. This fuzzy definition is thanks to RFC 3986 produced by W3C and IETF.
The definition of URI has changed over the years, so it makes sense for most people to be confused. However, you can now take solace in the fact that you can refer to http://somesite.com/something as either a URL or URI ... an you will be right either way (at least fot the time being anyway...)
How to parse a JSON file in swift?
Here is a code to make the conversions between JSON and NSData in Swift 2.0
// Convert from NSData to json object
func nsdataToJSON(data: NSData) -> AnyObject? {
do {
return try NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers)
} catch let myJSONError {
print(myJSONError)
}
return nil
}
// Convert from JSON to nsdata
func jsonToNSData(json: AnyObject) -> NSData?{
do {
return try NSJSONSerialization.dataWithJSONObject(json, options: NSJSONWritingOptions.PrettyPrinted)
} catch let myJSONError {
print(myJSONError)
}
return nil;
}
How to put a UserControl into Visual Studio toolBox
I had many users controls but one refused to show in the Toolbox, even though I rebuilt the solution and it was checked in the Choose Items... dialog.
Solution:
- From Solution Explorer I Right-Clicked the offending user control file and selected Exclude From Project
- Rebuild the solution
- Right-Click the user control and select Include in Project (assuming you have the Show All Files enabled in the Solution Explorer)
Note this also requires you have the AutoToolboxPopulate option enabled. As @DaveF answer suggests.
Alternate Solution: I'm not sure if this works, and I couldn't try it since I already resolved my issue, but if you unchecked the user control from the Choose Items... dialog, hit OK, then opened it back up and checked the user control. That might also work.
get current url in twig template?
{{ path(app.request.attributes.get('_route'),
app.request.attributes.get('_route_params')) }}
If you want to read it into a view variable:
{% set currentPath = path(app.request.attributes.get('_route'),
app.request.attributes.get('_route_params')) %}
The app
global view variable contains all sorts of useful shortcuts, such as app.session
and app.security.token.user
, that reference the services you might use in a controller.
HTML5 Canvas vs. SVG vs. div
For your purposes, I recommend using SVG, since you get DOM events, like mouse handling, including drag and drop, included, you don't have to implement your own redraw, and you don't have to keep track of the state of your objects. Use Canvas when you have to do bitmap image manipulation and use a regular div when you want to manipulate stuff created in HTML. As to performance, you'll find that modern browsers are now accelerating all three, but that canvas has received the most attention so far. On the other hand, how well you write your javascript is critical to getting the most performance with canvas, so I'd still recommend using SVG.
How to reduce the image size without losing quality in PHP
You can resize and then use imagejpeg()
Don't pass 100 as the quality for imagejpeg() - anything over 90 is generally overkill and just gets you a bigger JPEG. For a thumbnail, try 75 and work downwards until the quality/size tradeoff is acceptable.
imagejpeg($tn, $save, 75);
How to remove all files from directory without removing directory in Node.js
Building on @Waterscroll's response, if you want to use async and await in node 8+:
const fs = require('fs');
const util = require('util');
const readdir = util.promisify(fs.readdir);
const unlink = util.promisify(fs.unlink);
const directory = 'test';
async function toRun() {
try {
const files = await readdir(directory);
const unlinkPromises = files.map(filename => unlink(`${directory}/${filename}`));
return Promise.all(unlinkPromises);
} catch(err) {
console.log(err);
}
}
toRun();
How to enable MySQL Query Log?
Take a look on this answer to another related question. It shows how to enable, disable and to see the logs on live servers without restarting.
Log all queries in mysql
Here is a summary:
If you don't want or cannot restart the MySQL server you can proceed like this on your running server:
SET global general_log = 1;
SET global log_output = 'table';
select * from mysql.general_log;
- Disable Query logging on the database
SET global general_log = 0;
- Clear query logs without disabling
TRUNCATE mysql.general_log
Update React component every second
class ShowDateTime extends React.Component {
constructor() {
super();
this.state = {
curTime : null
}
}
componentDidMount() {
setInterval( () => {
this.setState({
curTime : new Date().toLocaleString()
})
},1000)
}
render() {
return(
<div>
<h2>{this.state.curTime}</h2>
</div>
);
}
}
Get current time in milliseconds using C++ and Boost
You can use boost::posix_time::time_duration
to get the time range. E.g like this
boost::posix_time::time_duration diff = tick - now;
diff.total_milliseconds();
And to get a higher resolution you can change the clock you are using. For example to the boost::posix_time::microsec_clock
, though this can be OS dependent. On Windows, for example, boost::posix_time::microsecond_clock
has milisecond resolution, not microsecond.
An example which is a little dependent on the hardware.
int main(int argc, char* argv[])
{
boost::posix_time::ptime t1 = boost::posix_time::second_clock::local_time();
boost::this_thread::sleep(boost::posix_time::millisec(500));
boost::posix_time::ptime t2 = boost::posix_time::second_clock::local_time();
boost::posix_time::time_duration diff = t2 - t1;
std::cout << diff.total_milliseconds() << std::endl;
boost::posix_time::ptime mst1 = boost::posix_time::microsec_clock::local_time();
boost::this_thread::sleep(boost::posix_time::millisec(500));
boost::posix_time::ptime mst2 = boost::posix_time::microsec_clock::local_time();
boost::posix_time::time_duration msdiff = mst2 - mst1;
std::cout << msdiff.total_milliseconds() << std::endl;
return 0;
}
On my win7 machine. The first out is either 0 or 1000. Second resolution.
The second one is nearly always 500, because of the higher resolution of the clock. I hope that help a little.
Add User to Role ASP.NET Identity
Below is an alternative implementation of a 'create user' controller method using Claims based roles.
The created claims then work with the Authorize attribute e.g. [Authorize(Roles = "Admin, User.*, User.Create")]
// POST api/User/Create
[Route("Create")]
public async Task<IHttpActionResult> Create([FromBody]CreateUserModel model)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
// Generate long password for the user
var password = System.Web.Security.Membership.GeneratePassword(25, 5);
// Create the user
var user = new ApiUser() { UserName = model.UserName };
var result = await UserManager.CreateAsync(user, password);
if (!result.Succeeded)
{
return GetErrorResult(result);
}
// Add roles (permissions) for the user
foreach (var perm in model.Permissions)
{
await UserManager.AddClaimAsync(user.Id, new Claim(ClaimTypes.Role, perm));
}
return Ok<object>(new { UserName = user.UserName, Password = password });
}
".addEventListener is not a function" why does this error occur?
Try this one:
var comment = document.querySelector("button");
function showComment() {
var place = document.querySelector('#textfield');
var commentBox = document.createElement('textarea');
place.appendChild(commentBox);
}
comment.addEventListener('click', showComment, false);
Use querySelector
instead of className
Ignore cells on Excel line graph
There are many cases in which gaps are desired in a chart.
I am currently trying to make a plot of flow rate in a heating system vs. the time of day. I have data for two months. I want to plot only vs. the time of day from 00:00 to 23:59, which causes lines to be drawn between 23:59 and 00:01 of the next day which extend across the chart and disturb the otherwise regular daily variation.
Using the NA() formula (in German NV()) causes Excel to ignore the cells, but instead the previous and following points are simply connected, which has the same problem with lines across the chart.
The only solution I have been able to find is to delete the formulas from the cells which should create the gaps.
Using an IF formula with "" as its value for the gaps makes Excel interpret the X-values as string labels (shudder) for the chart instead of numbers (and makes me swear about the people who wrote that requirement).
WCF ServiceHost access rights
Open a command prompt as the administrator and you write below command to add your URL:
netsh http add urlacl url=http://+:8000/YourServiceLibrary/YourService user=Everyone
Using Gulp to Concatenate and Uglify files
It turns out that I needed to use gulp-rename
and also output the concatenated file first before 'uglification'. Here's the code:
var gulp = require('gulp'),
gp_concat = require('gulp-concat'),
gp_rename = require('gulp-rename'),
gp_uglify = require('gulp-uglify');
gulp.task('js-fef', function(){
return gulp.src(['file1.js', 'file2.js', 'file3.js'])
.pipe(gp_concat('concat.js'))
.pipe(gulp.dest('dist'))
.pipe(gp_rename('uglify.js'))
.pipe(gp_uglify())
.pipe(gulp.dest('dist'));
});
gulp.task('default', ['js-fef'], function(){});
Coming from grunt
it was a little confusing at first but it makes sense now. I hope it helps the gulp
noobs.
And, if you need sourcemaps, here's the updated code:
var gulp = require('gulp'),
gp_concat = require('gulp-concat'),
gp_rename = require('gulp-rename'),
gp_uglify = require('gulp-uglify'),
gp_sourcemaps = require('gulp-sourcemaps');
gulp.task('js-fef', function(){
return gulp.src(['file1.js', 'file2.js', 'file3.js'])
.pipe(gp_sourcemaps.init())
.pipe(gp_concat('concat.js'))
.pipe(gulp.dest('dist'))
.pipe(gp_rename('uglify.js'))
.pipe(gp_uglify())
.pipe(gp_sourcemaps.write('./'))
.pipe(gulp.dest('dist'));
});
gulp.task('default', ['js-fef'], function(){});
See gulp-sourcemaps for more on options and configuration.
Excel: macro to export worksheet as CSV file without leaving my current Excel sheet
Almost what I wanted @Ralph, but here is the best answer. It'll solve your code problems:
- it exports just the hardcoded sheet named "Sheet1";
- it always exports to the same temp file, overwriting it;
- it ignores the locale separation char.
To solve these problems, and meet all my requirements, I've adapted the code from here. I've cleaned it a little to make it more readable.
Option Explicit
Sub ExportAsCSV()
Dim MyFileName As String
Dim CurrentWB As Workbook, TempWB As Workbook
Set CurrentWB = ActiveWorkbook
ActiveWorkbook.ActiveSheet.UsedRange.Copy
Set TempWB = Application.Workbooks.Add(1)
With TempWB.Sheets(1).Range("A1")
.PasteSpecial xlPasteValues
.PasteSpecial xlPasteFormats
End With
Dim Change below to "- 4" to become compatible with .xls files
MyFileName = CurrentWB.Path & "\" & Left(CurrentWB.Name, Len(CurrentWB.Name) - 5) & ".csv"
Application.DisplayAlerts = False
TempWB.SaveAs Filename:=MyFileName, FileFormat:=xlCSV, CreateBackup:=False, Local:=True
TempWB.Close SaveChanges:=False
Application.DisplayAlerts = True
End Sub
There are still some small thing with the code above that you should notice:
.Close
and DisplayAlerts=True
should be in a finally clause, but I don't know how to do it in VBA
- It works just if the current filename has 4 letters, like .xlsm. Wouldn't work in .xls excel old files. For file extensions of 3 chars, you must change the
- 5
to - 4
when setting MyFileName.
- As a collateral effect, your clipboard will be substituted with current sheet contents.
Edit: put Local:=True
to save with my locale CSV delimiter.
Add column to dataframe with constant value
Summing up what the others have suggested, and adding a third way
You can:
where the argument loc ( 0 <= loc <= len(columns) ) allows you to insert the column where you want.
'loc' gives you the index that your column will be at after the insertion. For example, the code above inserts the column Name as the 0-th column, i.e. it will be inserted before the first column, becoming the new first column. (Indexing starts from 0).
All these methods allow you to add a new column from a Series as well (just substitute the 'abc' default argument above with the series).
Serializing/deserializing with memory stream
Use Method to Serialize and Deserialize Collection object from memory. This works on Collection Data Types. This Method will Serialize collection of any type to a byte stream. Create a Seperate Class SerilizeDeserialize
and add following two methods:
public class SerilizeDeserialize
{
// Serialize collection of any type to a byte stream
public static byte[] Serialize<T>(T obj)
{
using (MemoryStream memStream = new MemoryStream())
{
BinaryFormatter binSerializer = new BinaryFormatter();
binSerializer.Serialize(memStream, obj);
return memStream.ToArray();
}
}
// DSerialize collection of any type to a byte stream
public static T Deserialize<T>(byte[] serializedObj)
{
T obj = default(T);
using (MemoryStream memStream = new MemoryStream(serializedObj))
{
BinaryFormatter binSerializer = new BinaryFormatter();
obj = (T)binSerializer.Deserialize(memStream);
}
return obj;
}
}
How To use these method in your Class:
ArrayList arrayListMem = new ArrayList() { "One", "Two", "Three", "Four", "Five", "Six", "Seven" };
Console.WriteLine("Serializing to Memory : arrayListMem");
byte[] stream = SerilizeDeserialize.Serialize(arrayListMem);
ArrayList arrayListMemDes = new ArrayList();
arrayListMemDes = SerilizeDeserialize.Deserialize<ArrayList>(stream);
Console.WriteLine("DSerializing From Memory : arrayListMemDes");
foreach (var item in arrayListMemDes)
{
Console.WriteLine(item);
}
Disabling contextual LOB creation as createClob() method threw error
For anyone who is facing this problem with Spring Boot 2
by default spring boot was using hibernate 5.3.x version, I have added following property in my pom.xml
<hibernate.version>5.4.2.Final</hibernate.version>
and error was gone. Reason for error is already explained in posts above
Recreate the default website in IIS
I suppose you want to publish and access your applications/websites from LAN; probably as virtual directories under the default website.The steps could vary depending on your IIS version, but basically it comes down to these steps:
Restore your "Default Website" Website :
create a new website
set "Default Website" as its name
In the Binding section (bottom panel), enter your local IP address in the "IP Address" edit.
- Keep the "Host" edit empty
that's it: now whenever you type your local ip address in your browser, you will get the website you just added.
Now if you want to access any of your other webapplications/websites from LAN, just add a virtual application under your default website pointing to the directory containing your published application/website. Now you can type : http://yourLocalIPAddress/theNameOfYourApplication to access it from your LAN.
SQL Query Where Date = Today Minus 7 Days
DECLARE @Daysforward int
SELECT @Daysforward = 25 (no of days required)
Select * from table name
where CAST( columnDate AS date) < DATEADD(day,1+@Daysforward,CAST(GETDATE() AS date))
Directory.GetFiles of certain extension
I would have done using just single line like
List<string> imageFiles = Directory.GetFiles(dir, "*.*", SearchOption.AllDirectories)
.Where(file => new string[] { ".jpg", ".gif", ".png" }
.Contains(Path.GetExtension(file)))
.ToList();
Changing Underline color
You can wrap your <span>
with a <a>
and use this little JQuery plugin to color the underline.
You can modify the color by passing a parameter to the plugin.
(function ($) {
$.fn.useful = function (params) {
var aCSS = {
'color' : '#d43',
'text-decoration' : 'underline'
};
$.extend(aCSS, params);
this.wrap('<a></a>');
var element = this.closest('a');
element.css(aCSS);
return element;
};
})(jQuery);
Then you call by writing this :
$("span.name").useful({color:'red'});
_x000D_
_x000D_
$(function () {_x000D_
_x000D_
var spanCSS = {_x000D_
'color' : '#000',_x000D_
'text-decoration': 'none'_x000D_
};_x000D_
_x000D_
$.fn.useful = function (params) {_x000D_
_x000D_
var aCSS = {_x000D_
'color' : '#d43',_x000D_
'text-decoration' : 'underline'_x000D_
};_x000D_
_x000D_
$.extend(aCSS, params);_x000D_
this.wrap('<a></a>');_x000D_
this.closest('a').css(aCSS);_x000D_
};_x000D_
_x000D_
// Use example:_x000D_
$("span.name").css(spanCSS).useful({color:'red'});_x000D_
_x000D_
_x000D_
_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<section class="container">_x000D_
_x000D_
<div class="user important">_x000D_
<span class="name">Bob</span>_x000D_
-_x000D_
<span class="location">Bali</span>_x000D_
</div>_x000D_
_x000D_
<div class="user">_x000D_
<span class="name">Dude</span>_x000D_
-_x000D_
<span class="location">Los Angeles</span>_x000D_
</div>_x000D_
_x000D_
_x000D_
<div class="user">_x000D_
<span class="name">Gérard</span>_x000D_
-_x000D_
<span class="location">Paris</span>_x000D_
</div>_x000D_
_x000D_
</section>
_x000D_
_x000D_
_x000D_
Wait until page is loaded with Selenium WebDriver for Python
How about putting WebDriverWait in While loop and catching the exceptions.
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException
browser = webdriver.Firefox()
browser.get("url")
delay = 3 # seconds
while True:
try:
WebDriverWait(browser, delay).until(EC.presence_of_element_located(browser.find_element_by_id('IdOfMyElement')))
print "Page is ready!"
break # it will break from the loop once the specific element will be present.
except TimeoutException:
print "Loading took too much time!-Try again"
How can I send a Firebase Cloud Messaging notification without use the Firebase Console?
Notification or data message can be sent to firebase base cloud messaging server using FCM HTTP v1 API endpoint.
https://fcm.googleapis.com/v1/projects/zoftino-stores/messages:send.
You need to generate and download private key of service account using Firebase console and generate access key using google api client library. Use any http library to post message to above end point, below code shows posting message using OkHTTP. You can find complete server side and client side code at firebase cloud messaging and sending messages to multiple clients using fcm topic example
If a specific client message needs to sent, you need to get firebase registration key of the client, see sending client or device specific messages to FCM server example
String SCOPE = "https://www.googleapis.com/auth/firebase.messaging";
String FCM_ENDPOINT
= "https://fcm.googleapis.com/v1/projects/zoftino-stores/messages:send";
GoogleCredential googleCredential = GoogleCredential
.fromStream(new FileInputStream("firebase-private-key.json"))
.createScoped(Arrays.asList(SCOPE));
googleCredential.refreshToken();
String token = googleCredential.getAccessToken();
final MediaType mediaType = MediaType.parse("application/json");
OkHttpClient httpClient = new OkHttpClient();
Request request = new Request.Builder()
.url(FCM_ENDPOINT)
.addHeader("Content-Type", "application/json; UTF-8")
.addHeader("Authorization", "Bearer " + token)
.post(RequestBody.create(mediaType, jsonMessage))
.build();
Response response = httpClient.newCall(request).execute();
if (response.isSuccessful()) {
log.info("Message sent to FCM server");
}
Difference between arguments and parameters in Java
In java, there are two types of parameters, implicit parameters and explicit parameters. Explicit parameters are the arguments passed into a method. The implicit parameter of a method is the instance that the method is called from. Arguments are simply one of the two types of parameters.
"unrecognized import path" with go get
I had the same problem on MacOS 10.10. And I found that the problem caused by OhMyZsh shell. Then I switched back to bash everything went ok.
Here is my go env
bash-3.2$ go env
GOARCH="amd64"
GOBIN=""
GOCHAR="6"
GOEXE=""
GOHOSTARCH="amd64"
GOHOSTOS="darwin"
GOOS="darwin"
GOPATH="/Users/bis/go"
GORACE=""
GOROOT="/usr/local/go"
GOTOOLDIR="/usr/local/go/pkg/tool/darwin_amd64"
CC="clang"
GOGCCFLAGS="-fPIC -m64 -pthread -fno-caret-diagnostics -Qunused-arguments -fmessage-length=0 -fno-common"
CXX="clang++"
CGO_ENABLED="1
The ScriptManager must appear before any controls that need it
It simply wants the ASP control on your ASPX page. I usually place mine right under the tag, or inside first Content area in the master's body (if your using a master page)
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="scriptManager" runat="server"></asp:ScriptManager>
<div>
[Content]
</div>
</form>
</body>
Deep copy in ES6 using the spread syntax
const a = {
foods: {
dinner: 'Pasta'
}
}
let b = JSON.parse(JSON.stringify(a))
b.foods.dinner = 'Soup'
console.log(b.foods.dinner) // Soup
console.log(a.foods.dinner) // Pasta
Using JSON.stringify
and JSON.parse
is the best way. Because by using the spread operator we will not get the efficient answer when the json object contains another object inside it. we need to manually specify that.
Last Run Date on a Stored Procedure in SQL Server
The below code should do the trick (>= 2008)
SELECT o.name,
ps.last_execution_time
FROM sys.dm_exec_procedure_stats ps
INNER JOIN
sys.objects o
ON ps.object_id = o.object_id
WHERE DB_NAME(ps.database_id) = ''
ORDER BY
ps.last_execution_time DESC
Edit 1 : Please take note of Jeff Modens advice below. If you find a procedure here, you can be sure that it is accurate. If you do not then you just don't know - you cannot conclude it is not running.
How to update core-js to core-js@3 dependency?
Install
npm i core-js
Modular standard library for JavaScript. Includes polyfills for ECMAScript up to 2019: promises, symbols, collections, iterators, typed arrays, many other features, ECMAScript proposals, some cross-platform WHATWG / W3C features and proposals like URL. You can load only required features or use it without global namespace pollution.
Read: https://www.npmjs.com/package/core-js
Converting JSONarray to ArrayList
With Kotlin, you can avoid a loop by wrapping the JSONArray with a MutableList, e.g.
val artistMetadata = player.metadata.optJSONArray("artist")
val artists = MutableList<String>(artistMetadata.length()) { i -> artistMetadata.getString(i)}
mysql update multiple columns with same now()
You can store the value of a now() in a variable before running the update query and then use that variable to update both the fields last_update
and last_monitor
.
This will ensure the now() is executed only once and same value is updated on both columns you need.
How to resize an Image C#
If you're working with a BitmapSource
:
var resizedBitmap = new TransformedBitmap(
bitmapSource,
new ScaleTransform(scaleX, scaleY));
If you want finer control over quality, run this first:
RenderOptions.SetBitmapScalingMode(
bitmapSource,
BitmapScalingMode.HighQuality);
(Default is BitmapScalingMode.Linear
which is equivalent to BitmapScalingMode.LowQuality
.)
Oracle SQL Developer spool output?
I have found that if I save my query(spool_script_file.sql) and call it using this
@c:\client\queries\spool_script_file.sql as script(F5)
My output now is just the results with out the commands at the top.
I found this solution on the oracle forums.
How to state in requirements.txt a direct github source
requirements.txt
allows the following ways of specifying a dependency on a package in a git repository as of pip 7.0:1
[-e] git+git://git.myproject.org/SomeProject#egg=SomeProject
[-e] git+https://git.myproject.org/SomeProject#egg=SomeProject
[-e] git+ssh://git.myproject.org/SomeProject#egg=SomeProject
-e [email protected]:SomeProject#egg=SomeProject (deprecated as of Jan 2020)
For Github that means you can do (notice the omitted -e
):
git+git://github.com/mozilla/elasticutils.git#egg=elasticutils
Why the extra answer?
I got somewhat confused by the -e
flag in the other answers so here's my clarification:
The -e
or --editable
flag means that the package is installed in <venv path>/src/SomeProject
and thus not in the deeply buried <venv path>/lib/pythonX.X/site-packages/SomeProject
it would otherwise be placed in.2
Documentation
What exactly is std::atomic?
Each instantiation and full specialization of std::atomic<> represents a type that different threads can simultaneously operate on (their instances), without raising undefined behavior:
Objects of atomic types are the only C++ objects that are free from data races; that is, if one thread writes to an atomic object while another thread reads from it, the behavior is well-defined.
In addition, accesses to atomic objects may establish inter-thread synchronization and order non-atomic memory accesses as specified by std::memory_order
.
std::atomic<>
wraps operations that, in pre-C++ 11 times, had to be performed using (for example) interlocked functions with MSVC or atomic bultins in case of GCC.
Also, std::atomic<>
gives you more control by allowing various memory orders that specify synchronization and ordering constraints. If you want to read more about C++ 11 atomics and memory model, these links may be useful:
Note that, for typical use cases, you would probably use overloaded arithmetic operators or another set of them:
std::atomic<long> value(0);
value++; //This is an atomic op
value += 5; //And so is this
Because operator syntax does not allow you to specify the memory order, these operations will be performed with std::memory_order_seq_cst
, as this is the default order for all atomic operations in C++ 11. It guarantees sequential consistency (total global ordering) between all atomic operations.
In some cases, however, this may not be required (and nothing comes for free), so you may want to use more explicit form:
std::atomic<long> value {0};
value.fetch_add(1, std::memory_order_relaxed); // Atomic, but there are no synchronization or ordering constraints
value.fetch_add(5, std::memory_order_release); // Atomic, performs 'release' operation
Now, your example:
a = a + 12;
will not evaluate to a single atomic op: it will result in a.load()
(which is atomic itself), then addition between this value and 12
and a.store()
(also atomic) of final result. As I noted earlier, std::memory_order_seq_cst
will be used here.
However, if you write a += 12
, it will be an atomic operation (as I noted before) and is roughly equivalent to a.fetch_add(12, std::memory_order_seq_cst)
.
As for your comment:
A regular int
has atomic loads and stores. Whats the point of wrapping it with atomic<>
?
Your statement is only true for architectures that provide such guarantee of atomicity for stores and/or loads. There are architectures that do not do this. Also, it is usually required that operations must be performed on word-/dword-aligned address to be atomic std::atomic<>
is something that is guaranteed to be atomic on every platform, without additional requirements. Moreover, it allows you to write code like this:
void* sharedData = nullptr;
std::atomic<int> ready_flag = 0;
// Thread 1
void produce()
{
sharedData = generateData();
ready_flag.store(1, std::memory_order_release);
}
// Thread 2
void consume()
{
while (ready_flag.load(std::memory_order_acquire) == 0)
{
std::this_thread::yield();
}
assert(sharedData != nullptr); // will never trigger
processData(sharedData);
}
Note that assertion condition will always be true (and thus, will never trigger), so you can always be sure that data is ready after while
loop exits. That is because:
store()
to the flag is performed after sharedData
is set (we assume that generateData()
always returns something useful, in particular, never returns NULL
) and uses std::memory_order_release
order:
memory_order_release
A store operation with this memory order performs the release
operation: no reads or writes in the current thread can be reordered
after this store. All writes in the current thread are visible in
other threads that acquire the same atomic variable
sharedData
is used after while
loop exits, and thus after load()
from flag will return a non-zero value. load()
uses std::memory_order_acquire
order:
std::memory_order_acquire
A load operation with this memory order performs the acquire operation
on the affected memory location: no reads or writes in the current
thread can be reordered before this load. All writes in other threads
that release the same atomic variable are visible in the current
thread.
This gives you precise control over the synchronization and allows you to explicitly specify how your code may/may not/will/will not behave. This would not be possible if only guarantee was the atomicity itself. Especially when it comes to very interesting sync models like the release-consume ordering.
How to NodeJS require inside TypeScript file?
Typescript will always complain when it is unable to find a symbol. The compiler comes together with a set of default definitions for window
, document
and such specified in a file called lib.d.ts
. If I do a grep for require
in this file I can find no definition of a function require
. Hence, we have to tell the compiler ourselves that this function will exist at runtime using the declare
syntax:
declare function require(name:string);
var sampleModule = require('modulename');
On my system, this compiles just fine.
how to set start page in webconfig file in asp.net c#
You can achieve it by code also, In you Global.asax file in Session_Start event write response.redirect to your start page like following.
void Session_Start(object sender, EventArgs e)
{
// Code that runs when a new session is started
Response.Redirect("~/Index.aspx");
}
You can get redirect page name from database or any other storage to change the application start page while application is running no need to edit web.config or change any IIS settings
Generate a Hash from string in Javascript
Thanks to the example by mar10, I found a way to get the same results in C# AND Javascript for an FNV-1a. If unicode chars are present, the upper portion is discarded for the sake of performance. Don't know why it would be helpful to maintain those when hashing, as am only hashing url paths for now.
C# Version
private static readonly UInt32 FNV_OFFSET_32 = 0x811c9dc5; // 2166136261
private static readonly UInt32 FNV_PRIME_32 = 0x1000193; // 16777619
// Unsigned 32bit integer FNV-1a
public static UInt32 HashFnv32u(this string s)
{
// byte[] arr = Encoding.UTF8.GetBytes(s); // 8 bit expanded unicode array
char[] arr = s.ToCharArray(); // 16 bit unicode is native .net
UInt32 hash = FNV_OFFSET_32;
for (var i = 0; i < s.Length; i++)
{
// Strips unicode bits, only the lower 8 bits of the values are used
hash = hash ^ unchecked((byte)(arr[i] & 0xFF));
hash = hash * FNV_PRIME_32;
}
return hash;
}
// Signed hash for storing in SQL Server
public static Int32 HashFnv32s(this string s)
{
return unchecked((int)s.HashFnv32u());
}
JavaScript Version
var utils = utils || {};
utils.FNV_OFFSET_32 = 0x811c9dc5;
utils.hashFnv32a = function (input) {
var hval = utils.FNV_OFFSET_32;
// Strips unicode bits, only the lower 8 bits of the values are used
for (var i = 0; i < input.length; i++) {
hval = hval ^ (input.charCodeAt(i) & 0xFF);
hval += (hval << 1) + (hval << 4) + (hval << 7) + (hval << 8) + (hval << 24);
}
return hval >>> 0;
}
utils.toHex = function (val) {
return ("0000000" + (val >>> 0).toString(16)).substr(-8);
}
What are some good SSH Servers for windows?
I've been using Bitvise SSH Server and it's really great. From install to administration it does it all through a GUI so you won't be putting together a sshd_config file. Plus if you use their client, Tunnelier, you get some bonus features (like mapping shares, port forwarding setup up server side, etc.) If you don't use their client it will still work with the Open Source SSH clients.
It's not Open Source and it costs $39.95, but I think it's worth it.
UPDATE 2009-05-21 11:10: The pricing has changed. The current price is $99.95 per install for commercial, but now free for non-commercial/personal use. Here is the current pricing.
Can't find how to use HttpContent
Just leaving the way using Microsoft.AspNet.WebApi.Client
here.
Example:
var client = HttpClientFactory.Create();
var result = await client.PostAsync<ExampleClass>("http://www.sample.com/write", new ExampleClass(), new JsonMediaTypeFormatter());
Mix Razor and Javascript code
Use <text>
:
<script type="text/javascript">
var data = [];
@foreach (var r in Model.rows)
{
<text>
data.push([ @r.UnixTime * 1000, @r.Value ]);
</text>
}
</script>
Omitting the first line from any Linux command output
This is a quick hacky way: ls -lart | grep -v ^total
.
Basically, remove any lines that start with "total", which in ls
output should only be the first line.
A more general way (for anything):
ls -lart | sed "1 d"
sed "1 d"
means only print everything but first line.
How can I change the date format in Java?
tl;dr
LocalDate.parse(
"23/01/2017" ,
DateTimeFormatter.ofPattern( "dd/MM/uuuu" , Locale.UK )
).format(
DateTimeFormatter.ofPattern( "uuuu/MM/dd" , Locale.UK )
)
2017/01/23
Avoid legacy date-time classes
The answer by Christopher Parker is correct but outdated. The troublesome old date-time classes such as java.util.Date
, java.util.Calendar
, and java.text.SimpleTextFormat
are now legacy, supplanted by the java.time classes.
Using java.time
Parse the input string as a date-time object, then generate a new String object in the desired format.
The LocalDate
class represents a date-only value without time-of-day and without time zone.
DateTimeFormatter fIn = DateTimeFormatter.ofPattern( "dd/MM/uuuu" , Locale.UK ); // As a habit, specify the desired/expected locale, though in this case the locale is irrelevant.
LocalDate ld = LocalDate.parse( "23/01/2017" , fIn );
Define another formatter for the output.
DateTimeFormatter fOut = DateTimeFormatter.ofPattern( "uuuu/MM/dd" , Locale.UK );
String output = ld.format( fOut );
2017/01/23
By the way, consider using standard ISO 8601 formats for strings representing date-time values.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
Joda-Time
UPDATE: The Joda-Time project is now in maintenance mode, with the team advising migration to the java.time classes. This section here is left for the sake of history.
For fun, here is his code adapted for using the Joda-Time library.
// © 2013 Basil Bourque. This source code may be used freely forever by anyone taking full responsibility for doing so.
// import org.joda.time.*;
// import org.joda.time.format.*;
final String OLD_FORMAT = "dd/MM/yyyy";
final String NEW_FORMAT = "yyyy/MM/dd";
// August 12, 2010
String oldDateString = "12/08/2010";
String newDateString;
DateTimeFormatter formatterOld = DateTimeFormat.forPattern(OLD_FORMAT);
DateTimeFormatter formatterNew = DateTimeFormat.forPattern(NEW_FORMAT);
LocalDate localDate = formatterOld.parseLocalDate( oldDateString );
newDateString = formatterNew.print( localDate );
Dump to console…
System.out.println( "localDate: " + localDate );
System.out.println( "newDateString: " + newDateString );
When run…
localDate: 2010-08-12
newDateString: 2010/08/12
Angular 5 Service to read local .json file
Let’s create a JSON file, we name it navbar.json you can name it whatever you want!
navbar.json
[
{
"href": "#",
"text": "Home",
"icon": ""
},
{
"href": "#",
"text": "Bundles",
"icon": "",
"children": [
{
"href": "#national",
"text": "National",
"icon": "assets/images/national.svg"
}
]
}
]
Now we’ve created a JSON file with some menu data. We’ll go to app component file and paste the below code.
app.component.ts
import { Component } from '@angular/core';
import menudata from './navbar.json';
@Component({
selector: 'lm-navbar',
templateUrl: './navbar.component.html'
})
export class NavbarComponent {
mainmenu:any = menudata;
}
Now your Angular 7 app is ready to serve the data from the local JSON file.
Go to app.component.html and paste the following code in it.
app.component.html
<ul class="navbar-nav ml-auto">
<li class="nav-item" *ngFor="let menu of mainmenu">
<a class="nav-link" href="{{menu.href}}">{{menu.icon}} {{menu.text}}</a>
<ul class="sub_menu" *ngIf="menu.children && menu.children.length > 0">
<li *ngFor="let sub_menu of menu.children"><a class="nav-link" href="{{sub_menu.href}}"><img src="{{sub_menu.icon}}" class="nav-img" /> {{sub_menu.text}}</a></li>
</ul>
</li>
</ul>
PHP convert XML to JSON
This is an improvement of the most upvoted solution by Antonio Max, which also works with XML that has namespaces (by replacing the colon with an underscore). It also has some extra options (and does parse <person my-attribute='name'>John</person>
correctly).
function parse_xml_into_array($xml_string, $options = array()) {
/*
DESCRIPTION:
- parse an XML string into an array
INPUT:
- $xml_string
- $options : associative array with any of these keys:
- 'flatten_cdata' : set to true to flatten CDATA elements
- 'use_objects' : set to true to parse into objects instead of associative arrays
- 'convert_booleans' : set to true to cast string values 'true' and 'false' into booleans
OUTPUT:
- associative array
*/
// Remove namespaces by replacing ":" with "_"
if (preg_match_all("|</([\\w\\-]+):([\\w\\-]+)>|", $xml_string, $matches, PREG_SET_ORDER)) {
foreach ($matches as $match) {
$xml_string = str_replace('<'. $match[1] .':'. $match[2], '<'. $match[1] .'_'. $match[2], $xml_string);
$xml_string = str_replace('</'. $match[1] .':'. $match[2], '</'. $match[1] .'_'. $match[2], $xml_string);
}
}
$output = json_decode(json_encode(@simplexml_load_string($xml_string, 'SimpleXMLElement', ($options['flatten_cdata'] ? LIBXML_NOCDATA : 0))), ($options['use_objects'] ? false : true));
// Cast string values "true" and "false" to booleans
if ($options['convert_booleans']) {
$bool = function(&$item, $key) {
if (in_array($item, array('true', 'TRUE', 'True'), true)) {
$item = true;
} elseif (in_array($item, array('false', 'FALSE', 'False'), true)) {
$item = false;
}
};
array_walk_recursive($output, $bool);
}
return $output;
}
How can I use a custom font in Java?
If you want to use the font to draw with graphics2d or similar, this works:
InputStream stream = ClassLoader.getSystemClassLoader().getResourceAsStream("roboto-bold.ttf")
Font font = Font.createFont(Font.TRUETYPE_FONT, stream).deriveFont(48f)
How can I reload .emacs after changing it?
Although M-x eval-buffer
will work you may run into problems with toggles and other similar things. A better approach might be to "mark" or highlight whats new in your .emacs (or even scratch buffer if your just messing around) and then M-x eval-region
. Hope this helps.
ReactJS - Get Height of an element
For those who are interested in using react hooks
, this might help you get started.
import React, { useState, useEffect, useRef } from 'react'
export default () => {
const [height, setHeight] = useState(0)
const ref = useRef(null)
useEffect(() => {
setHeight(ref.current.clientHeight)
})
return (
<div ref={ref}>
{height}
</div>
)
}
Java read file and store text in an array
If you don't know the number of lines in your file, you don't have a size with which to init an array. In this case, it makes more sense to use a List :
List<String> tokens = new ArrayList<String>();
while (inFile1.hasNext()) {
tokens.add(inFile1.nextLine());
}
After that, if you need to, you can copy to an array :
String[] tokenArray = tokens.toArray(new String[0]);
SFTP file transfer using Java JSch
Below code works for me
public static void sftpsript(String filepath) {
try {
String user ="demouser"; // username for remote host
String password ="demo123"; // password of the remote host
String host = "demo.net"; // remote host address
JSch jsch = new JSch();
Session session = jsch.getSession(user, host);
session.setPassword(password);
session.connect();
ChannelSftp sftpChannel = (ChannelSftp) session.openChannel("sftp");
sftpChannel.connect();
sftpChannel.put("I:/demo/myOutFile.txt", "/tmp/QA_Auto/myOutFile.zip");
sftpChannel.disconnect();
session.disconnect();
}catch(Exception ex){
ex.printStackTrace();
}
}
OR using StrictHostKeyChecking as "NO" (security consequences)
public static void sftpsript(String filepath) {
try {
String user ="demouser"; // username for remote host
String password ="demo123"; // password of the remote host
String host = "demo.net"; // remote host address
JSch jsch = new JSch();
Session session = jsch.getSession(user, host, 22);
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);;
session.setPassword(password);
System.out.println("user=="+user+"\n host=="+host);
session.connect();
ChannelSftp sftpChannel = (ChannelSftp) session.openChannel("sftp");
sftpChannel.connect();
sftpChannel.put("I:/demo/myOutFile.txt", "/tmp/QA_Auto/myOutFile.zip");
sftpChannel.disconnect();
session.disconnect();
}catch(Exception ex){
ex.printStackTrace();
}
}
Find unused code
It's a great question, but be warned that you're treading in dangerous waters here. When you're deleting code you will have to make sure you're compiling and testing often.
One great tool come to mind:
NDepend - this tool is just amazing. It takes a little while to grok, and after the first 10 minutes I think most developers just say "Screw it!" and delete the app. Once you get a good feel for NDepend, it gives you amazing insight to how your apps are coupled. Check it out: http://www.ndepend.com/. Most importantly, this tool will allow you to view methods which do not have any direct callers. It will also show you the inverse, a complete call tree for any method in the assembly (or even between assemblies).
Whatever tool you choose, it's not a task to take lightly. Especially if you're dealing with public methods on library type assemblies, as you may never know when an app is referencing them.
Filter output in logcat by tagname
In case someone stumbles in on this like I did, you can filter on multiple tags by adding a comma in between, like so:
adb logcat -s "browser","webkit"
How to install Intellij IDEA on Ubuntu?
In a simple manner you can also try to just run a pre-packaged docker with intellij, I found the good job of @dlsniper : https://hub.docker.com/r/dlsniper/docker-intellij/
you just need to have docker installed and to run :
docker run -tdi \
--net="host" \
--privileged=true \
-e DISPLAY=${DISPLAY} \
-v /tmp/.X11-unix:/tmp/.X11-unix \
-v ${HOME}/.IdeaIC2016.1_docker:/home/developer/.IdeaIC2016.1 \
-v ${GOPATH}:/home/developer/go \
dlsniper/docker-intellij
How to delete specific columns with VBA?
To answer the question
How to delete specific columns in vba for excel.
I use Array as below.
sub del_col()
dim myarray as variant
dim i as integer
myarray = Array(10, 9, 8)'Descending to Ascending
For i = LBound(myarray) To UBound(myarray)
ActiveSheet.Columns(myarray(i)).EntireColumn.Delete
Next i
end sub
Error while sending QUERY packet
You cannot have the WHERE
clause in an INSERT
statement.
insert into table1(data) VALUES(:data) where sno ='45830'
Should be
insert into table1(data) VALUES(:data)
Update: You have removed that from your code (I assume you copied the code in wrong). You want to increase your allowed packet size:
SET GLOBAL max_allowed_packet=32M
Change the 32M
(32 megabytes) up/down as required. Here is a link to the MySQL documentation on the subject.
Python if-else short-hand
Try this:
x = a > b and 10 or 11
This is a sample of execution:
>>> a,b=5,7
>>> x = a > b and 10 or 11
>>> print x
11
I can't install python-ldap
I had problems with the installation on Windows, so one of the solutions is to install the ldap
package manually.
A few steps:
- Go to the page pyldap or/and python-ldap and download the latest version
*whl
.
- Open a console then cd to where you've downloaded your file like
some-package.whl
and use:
pip install some-package.whl
The current version for pyldap
is 2.4.45
. On a concrete example the installation would be:
pip install .\pyldap-2.4.45-cp37-cp37m-win_amd64.whl
# or
pip install .\python_ldap-3.3.1-cp39-cp39-win_amd64.whl
Output:
Installing collected packages: pyldap
Successfully installed pyldap-2.4.45
EDIT
You can install the proper version for Python-3.X though using following command:
# if pip3 is the default pip alias for python-3
pip3 install python3-ldap
# otherwise
pip install python3-ldap
Also here is the link of PiPy package for further information: python3-ldap 0.9.8.4
OR
ldap3 is a strictly RFC 4510 conforming LDAP V3 pure Python client library. The same codebase runs in Python 2, Python 3, PyPy and PyPy3: https://github.com/cannatag/ldap3
pip install ldap3
from ldap3 import Server, Connection, SAFE_SYNC
server = Server('my_server')
conn = Connection(server, 'my_user', 'my_password', client_strategy=SAFE_SYNC, auto_bind=True)
status, result, response, _ = conn.search('o=test', '(objectclass=*)')
# usually you don't need the original request (4th element of the returned tuple)
Int or Number DataType for DataAnnotation validation attribute
You can write a custom validation attribute:
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = false)]
public class Numeric : ValidationAttribute
{
public Numeric(string errorMessage) : base(errorMessage)
{
}
/// <summary>
/// Check if given value is numeric
/// </summary>
/// <param name="value">The input value</param>
/// <returns>True if value is numeric</returns>
public override bool IsValid(object value)
{
return decimal.TryParse(value?.ToString(), out _);
}
}
On your property you can then use the following annotation:
[Numeric("Please fill in a valid number.")]
public int NumberOfBooks { get; set; }
Laravel - Form Input - Multiple select for a one to many relationship
Just single if conditions
<select name="category_type[]" id="category_type" class="select2 m-b-10 select2-multiple" style="width: 100%" multiple="multiple" data-placeholder="Choose" tooltip="Select Category Type">
@foreach ($categoryTypes as $categoryType)
<option value="{{ $categoryType->id }}"
**@if(in_array($categoryType->id,
request()->get('category_type')??[]))selected="selected"
@endif**>
{{ ucfirst($categoryType->title) }}</option>
@endforeach
</select>
Git: Find the most recent common ancestor of two branches
As noted in a prior answer, although git merge-base
works,
$ git merge-base myfeature develop
050dc022f3a65bdc78d97e2b1ac9b595a924c3f2
If myfeature
is the current branch, as is common, you can use --fork-point
:
$ git merge-base --fork-point develop
050dc022f3a65bdc78d97e2b1ac9b595a924c3f2
This argument works only in sufficiently recent versions of git. Unfortunately it doesn't always work, however, and it is not clear why. Please refer to the limitations noted toward the end of this answer.
For full commit info, consider:
$ git log -1 $(git merge-base --fork-point develop)
How to re-create database for Entity Framework?
My solution is best suited for :
- deleted your mdf file
- want to re-create your db.
In order to recreate your database you need add the connection using Visual Studio.
Step 1 : Go to Server Explorer add new connection( or look for a add db icon).
Step 2 : Change Datasource to Microsoft SQL Server Database File.
Step 3 : add any database name you desire in the Database file name field.(preferably the same name you have in the web.config AttachDbFilename attribute)
Step 4 : click browse and navigate to where you will like it to be located.
Step 5 : in the package manager console run command update-database
<embed> vs. <object>
Embed is not a standard tag, though object is. Here's an article that looks like it will help you, since it seems the situation is not so simple. An example for PDF is included.
How to count the number of true elements in a NumPy bool array
That question solved a quite similar question for me and I thought I should share :
In raw python you can use sum()
to count True
values in a list
:
>>> sum([True,True,True,False,False])
3
But this won't work :
>>> sum([[False, False, True], [True, False, True]])
TypeError...
JQUERY ajax passing value from MVC View to Controller
View Data
==============
@model IEnumerable<DemoApp.Models.BankInfo>
<p>
<b>Search Results</b>
</p>
@if (!Model.Any())
{
<tr>
<td colspan="4" style="text-align:center">
No Bank(s) found
</td>
</tr>
}
else
{
<table class="table">
<tr>
<th>
@Html.DisplayNameFor(model => model.Name)
</th>
<th>
@Html.DisplayNameFor(model => model.Address)
</th>
<th>
@Html.DisplayNameFor(model => model.Postcode)
</th>
<th></th>
</tr>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.Name)
</td>
<td>
@Html.DisplayFor(modelItem => item.Address)
</td>
<td>
@Html.DisplayFor(modelItem => item.Postcode)
</td>
<td>
<input type="button" class="btn btn-default bankdetails" value="Select" data-id="@item.Id" />
</td>
</tr>
}
</table>
}
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
$(function () {
$("#btnSearch").off("click.search").on("click.search", function () {
if ($("#SearchBy").val() != '') {
$.ajax({
url: '/home/searchByName',
data: { 'name': $("#SearchBy").val() },
dataType: 'html',
success: function (data) {
$('#dvBanks').html(data);
}
});
}
else {
alert('Please enter Bank Name');
}
});
}
});
public ActionResult SearchByName(string name)
{
var banks = GetBanksInfo();
var filteredBanks = banks.Where(x => x.Name.ToLower().Contains(name.ToLower())).ToList();
return PartialView("_banks", filteredBanks);
}
/// <summary>
/// Get List of Banks Basically it should get from Database
/// </summary>
/// <returns></returns>
private List<BankInfo> GetBanksInfo()
{
return new List<BankInfo>
{
new BankInfo {Id = 1, Name = "Bank of America", Address = "1438 Potomoc Avenue, Pittsburge", Postcode = "PA 15220" },
new BankInfo {Id = 2, Name = "Bank of America", Address = "643 River Hwy, Mooresville", Postcode = "NC 28117" },
new BankInfo {Id = 3, Name = "Bank of Barroda", Address = "643 Hyderabad", Postcode = "500061" },
new BankInfo {Id = 4, Name = "State Bank of India", Address = "AsRao Nagar", Postcode = "500061" },
new BankInfo {Id = 5, Name = "ICICI", Address = "AsRao Nagar", Postcode = "500061" }
};
}
Oracle SQL - DATE greater than statement
You need to convert the string to date using the to_date()
function
SELECT * FROM OrderArchive
WHERE OrderDate <= to_date('31-Dec-2014','DD-MON-YYYY');
OR
SELECT * FROM OrderArchive
WHERE OrderDate <= to_date('31 Dec 2014','DD MON YYYY');
OR
SELECT * FROM OrderArchive
WHERE OrderDate <= to_date('2014-12-31','yyyy-MM-dd');
This will work only if OrderDate
is stored in Date format
. If it is Varchar
you should apply to_date()
func on that column also like
SELECT * FROM OrderArchive
WHERE to_date(OrderDate,'yyyy-Mm-dd') <= to_date('2014-12-31','yyyy-MM-dd');
How do I measure a time interval in C?
If your Linux system supports it, clock_gettime(CLOCK_MONOTONIC) should be a high resolution timer that is unaffected by system date changes (e.g. NTP daemons).
Syntax error: Illegal return statement in JavaScript
This can happen in ES6 if you use the incorrect (older) syntax for static methods:
export default class MyClass
{
constructor()
{
...
}
myMethod()
{
...
}
}
MyClass.someEnum = {Red: 0, Green: 1, Blue: 2}; //works
MyClass.anotherMethod() //or
MyClass.anotherMethod = function()
{
return something; //doesn't work
}
Whereas the correct syntax is:
export default class MyClass
{
constructor()
{
...
}
myMethod()
{
...
}
static anotherMethod()
{
return something; //works
}
}
MyClass.someEnum = {Red: 0, Green: 1, Blue: 2}; //works
Good examples of python-memcache (memcached) being used in Python?
It's fairly simple. You write values using keys and expiry times. You get values using keys. You can expire keys from the system.
Most clients follow the same rules. You can read the generic instructions and best practices on the memcached homepage.
If you really want to dig into it, I'd look at the source. Here's the header comment:
"""
client module for memcached (memory cache daemon)
Overview
========
See U{the MemCached homepage<http://www.danga.com/memcached>} for more about memcached.
Usage summary
=============
This should give you a feel for how this module operates::
import memcache
mc = memcache.Client(['127.0.0.1:11211'], debug=0)
mc.set("some_key", "Some value")
value = mc.get("some_key")
mc.set("another_key", 3)
mc.delete("another_key")
mc.set("key", "1") # note that the key used for incr/decr must be a string.
mc.incr("key")
mc.decr("key")
The standard way to use memcache with a database is like this::
key = derive_key(obj)
obj = mc.get(key)
if not obj:
obj = backend_api.get(...)
mc.set(key, obj)
# we now have obj, and future passes through this code
# will use the object from the cache.
Detailed Documentation
======================
More detailed documentation is available in the L{Client} class.
"""
How do I get textual contents from BLOB in Oracle SQL
In case your text is compressed inside the blob using DEFLATE algorithm and it's quite large, you can use this function to read it
CREATE OR REPLACE PACKAGE read_gzipped_entity_package AS
FUNCTION read_entity(entity_id IN VARCHAR2)
RETURN VARCHAR2;
END read_gzipped_entity_package;
/
CREATE OR REPLACE PACKAGE BODY read_gzipped_entity_package IS
FUNCTION read_entity(entity_id IN VARCHAR2) RETURN VARCHAR2
IS
l_blob BLOB;
l_blob_length NUMBER;
l_amount BINARY_INTEGER := 10000; -- must be <= ~32765.
l_offset INTEGER := 1;
l_buffer RAW(20000);
l_text_buffer VARCHAR2(32767);
BEGIN
-- Get uncompressed BLOB
SELECT UTL_COMPRESS.LZ_UNCOMPRESS(COMPRESSED_BLOB_COLUMN_NAME)
INTO l_blob
FROM TABLE_NAME
WHERE ID = entity_id;
-- Figure out how long the BLOB is.
l_blob_length := DBMS_LOB.GETLENGTH(l_blob);
-- We'll loop through the BLOB as many times as necessary to
-- get all its data.
FOR i IN 1..CEIL(l_blob_length/l_amount) LOOP
-- Read in the given chunk of the BLOB.
DBMS_LOB.READ(l_blob
, l_amount
, l_offset
, l_buffer);
-- The DBMS_LOB.READ procedure dictates that its output be RAW.
-- This next procedure converts that RAW data to character data.
l_text_buffer := UTL_RAW.CAST_TO_VARCHAR2(l_buffer);
-- For the next iteration through the BLOB, bump up your offset
-- location (i.e., where you start reading from).
l_offset := l_offset + l_amount;
END LOOP;
RETURN l_text_buffer;
EXCEPTION
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE('!ERROR: ' || SUBSTR(SQLERRM,1,247));
END;
END read_gzipped_entity_package;
/
Then run select to get text
SELECT read_gzipped_entity_package.read_entity('entity_id') FROM DUAL;
Hope this will help someone.
Which Android IDE is better - Android Studio or Eclipse?
My first choice is Android Studio. its has great feature to develop android application.
Eclipse is not that hard to learn also.If you're going to be learning Android development from the start, I can recommend Hello, Android, which I just finished. It shows you exactly how to use all the features of Eclipse that are useful for developing Android apps. There's also a brief section on getting set up to develop from the command line and from other IDEs.
Cassandra "no viable alternative at input"
Wrong syntax. Here you are:
insert into user_by_category (game_category,customer_id) VALUES
('Goku','12');
or:
insert into user_by_category ("game_category","customer_id") VALUES
('Kakarot','12');
The second one is normally used for case-sensitive column names.
How to edit the size of the submit button on a form?
That's easy!
First, give your button an id
such as <input type="button" value="I am a button!" id="myButton" />
Then, for height, and width, use CSS code:
.myButton {
width: 100px;
height: 100px;
}
You could also do this CSS:
input[type="button"] {
width: 100px;
height: 100px;
}
But that would affect all the buttons on the Page.
Working example - JSfiddle
Twitter Bootstrap add active class to li
Try this.
// Remove active for all items.
$('.page-sidebar-menu li').removeClass('active');
// highlight submenu item
$('li a[href="' + this.location.pathname + '"]').parent().addClass('active');
// Highlight parent menu item.
$('ul a[href="' + this.location.pathname + '"]').parents('li').addClass('active');
Stop a youtube video with jquery?
for those who are looking javascript solution
let iframeDiv = document.getElementById('demoVideo');
let video = iframeDiv.src;
iframeDiv.src = "";
iframeDiv.src = video;
It perfectly worked for me just put id='demoVideo' in your iframe tag and you are good to go :)
How to compare two Carbon Timestamps?
First, convert the timestamp using the built-in eloquent functionality, as described in this answer.
Then you can just use Carbon's min()
or max()
function for comparison. For example:
$dt1 = Carbon::create(2012, 1, 1, 0, 0, 0);
$dt2 = Carbon::create(2014, 1, 30, 0, 0, 0);
echo $dt1->min($dt2);
This will echo
the lesser of the two dates, which in this case is $dt1
.
See http://carbon.nesbot.com/docs/
Free c# QR-Code generator
ZXing is an open source project that can detect and parse a number of different barcodes. It can also generate QR-codes. (Only QR-codes, though).
There are a number of variants for different languages: ActionScript, Android (java), C++, C#, IPhone (Obj C), Java ME, Java SE, JRuby, JSP. Support for generating QR-codes comes with some of those: ActionScript, Android, C# and the Java variants.
Split a string by another string in C#
Regex.Split(string, "xx")
is the way I do it usually.
Of course you'll need:
using System.Text.RegularExpressions;
or :
System.Text.RegularExpressions.Regex.Split(string, "xx")
but then again I need that library all the time.
Save string to the NSUserDefaults?
update for Swift 3
func setObject(value:AnyObject ,key:String)
{
let pref = UserDefaults.standard
pref.set(value, forKey: key)
pref.synchronize()
}
func getObject(key:String) -> AnyObject
{
let pref = UserDefaults.standard
return pref.object(forKey: key)! as AnyObject
}
How to get the start time of a long-running Linux process?
As a follow-up to Adam Matan's answer, the /proc/<pid>
directory's time stamp as such is not necessarily directly useful, but you can use
awk -v RS=')' 'END{print $20}' /proc/12345/stat
to get the start time in clock ticks since system boot.1
This is a slightly tricky unit to use; see also convert jiffies to seconds for details.
awk -v ticks="$(getconf CLK_TCK)" 'NR==1 { now=$1; next }
END { printf "%9.0f\n", now - ($20/ticks) }' /proc/uptime RS=')' /proc/12345/stat
This should give you seconds, which you can pass to strftime()
to get a (human-readable, or otherwise) timestamp.
awk -v ticks="$(getconf CLK_TCK)" 'NR==1 { now=$1; next }
END { print strftime("%c", systime() - (now-($20/ticks))) }' /proc/uptime RS=')' /proc/12345/stat
Updated with some fixes from Stephane Chazelas in the comments; thanks as always!
If you only have Mawk, maybe try
awk -v ticks="$(getconf CLK_TCK)" -v epoch="$(date +%s)" '
NR==1 { now=$1; next }
END { printf "%9.0f\n", epoch - (now-($20/ticks)) }' /proc/uptime RS=')' /proc/12345/stat |
xargs -i date -d @{}
1 man proc; search for starttime.