Converting milliseconds to a date (jQuery/JavaScript)
Assume the date as milliseconds date is 1526813885836
, so you can access the date as string with this sample code:
console.log(new Date(1526813885836).toString());
For clearness see below code:
const theTime = new Date(1526813885836);
console.log(theTime.toString());
What is the difference between call and apply?
Another example with Call, Apply and Bind.
The difference between Call and Apply is evident, but Bind works like this:
- Bind returns an instance of a function that can be executed
- First Parameter is 'this'
- Second parameter is a Comma separated list of arguments (like Call)
}
function Person(name) {
this.name = name;
}
Person.prototype.getName = function(a,b) {
return this.name + " " + a + " " + b;
}
var reader = new Person('John Smith');
reader.getName = function() {
// Apply and Call executes the function and returns value
// Also notice the different ways of extracting 'getName' prototype
var baseName = Object.getPrototypeOf(this).getName.apply(this,["is a", "boy"]);
console.log("Apply: " + baseName);
var baseName = Object.getPrototypeOf(reader).getName.call(this, "is a", "boy");
console.log("Call: " + baseName);
// Bind returns function which can be invoked
var baseName = Person.prototype.getName.bind(this, "is a", "boy");
console.log("Bind: " + baseName());
}
reader.getName();
/* Output
Apply: John Smith is a boy
Call: John Smith is a boy
Bind: John Smith is a boy
*/
Update query PHP MySQL
Need to add quote for that need to use dot operator:
mysql_query("UPDATE blogEntry SET content = '".$udcontent."', title = '".$udtitle."' WHERE id = '".$id."'");
Aligning a button to the center
Here is what worked for me:
<input type="submit" style="margin-left: 50%">
If you only add margin, without the left part, it will center the submit button into the middle of your entire page, making it difficult to find and rendering your form incomplete for people who don't have the patience to find a submit button lol. margin-left centers it within the same line, so it's not further down your page than you intended.
You can also use pixels instead of percentage if you just want to indent the submit button a bit and not all the way halfway across the page.
Overcoming "Display forbidden by X-Frame-Options"
Not mentioned but can help in some instances:
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState !== 4) return;
if (xhr.status === 200) {
var doc = iframe.contentWindow.document;
doc.open();
doc.write(xhr.responseText);
doc.close();
}
}
xhr.open('GET', url, true);
xhr.send(null);
javascript : sending custom parameters with window.open() but its not working
You can use this but there remains a security issue
<script type="text/javascript">
function fnc1()
{
var a=window.location.href;
username="p";
password=1234;
window.open(a+'?username='+username+'&password='+password,"");
}
</script>
<input type="button" onclick="fnc1()" />
<input type="text" id="atext" />
Set ImageView width and height programmatically?
It may be too late but for the sake of others who have the same problem, to set the height of the ImageView
:
imageView.getLayoutParams().height = 20;
Important. If you're setting the height after the layout has already been 'laid out', make sure you also call:
imageView.requestLayout();
set serveroutput on in oracle procedure
To understand the use of "SET SERVEROUTPUT ON" I will take an example
DECLARE
a number(10) :=10;
BEGIN
dbms_output.put_line(a) ;
dbms_output.put_line('Hello World ! ') ;
END ;
With an output : PL/SQl procedure successfully completed i.e without the expected output
And the main reason behind is that ,whatever we pass inside dbms_output.put_line(' ARGUMENT '/VALUES) i.e. ARGUMENT/VALUES , is internally stored inside a buffer in SGA(Shared Global Area ) memory area upto 2000 bytes .
*NOTE :***However one should note that this buffer is only created when we use **dbms_output package. And we need to set the environment variable only once for a session !!
And in order to fetch it from that buffer we need to set the environment variable for the session . It makes a lot of confusion to the beginners that we are setting the server output on ( because of its nomenclature ) , but unfortunately its nothing like that . Using SET SERVER OUTPUT ON are just telling the PL/SQL engine that
*Hey please print the ARGUMENT/VALUES that I will be passing inside dbms_output.put_line
and in turn PL/SQl run time engine prints the argument on the main console .
I think I am clear to you all . Wish you all the best .
To know more about it with the architectural structure of Oracle Server Engine you can see my answer on Quora http://qr.ae/RojAn8
And to answer your question "One should use SET SERVER OUTPUT in the beginning of the session. "
How to printf "unsigned long" in C?
The correct specifier for unsigned long is %lu
.
If you are not getting the exact value you are expecting then there may be some problems in your code.
Please copy your code here. Then maybe someone can tell you better what the problem is.
How does delete[] know it's an array?
It's up to the runtime which is responsible for the memory allocation, in the same way that you can delete an array created with malloc in standard C using free. I think each compiler implements it differently. One common way is to allocate an extra cell for the array size.
However, the runtime is not smart enough to detect whether or not it is an array or a pointer, you have to inform it, and if you are mistaken, you either don't delete correctly (E.g., ptr instead of array), or you end up taking an unrelated value for the size and cause significant damage.
Creating NSData from NSString in Swift
In Swift 3
let data = string.data(using: .utf8)
In Swift 2 (or if you already have a NSString
instance)
let data = string.dataUsingEncoding(NSUTF8StringEncoding)
In Swift 1 (or if you have a swift String
):
let data = (string as NSString).dataUsingEncoding(NSUTF8StringEncoding)
Also note that data
is an Optional<NSData>
(since the conversion might fail), so you'll need to unwrap it before using it, for instance:
if let d = data {
println(d)
}
Convert .cer certificate to .jks
Just to be sure that this is really the "conversion" you need, please note that jks
files are keystores, a file format used to store more than one certificate and allows you to retrieve them programmatically using the Java security API, it's not a one-to-one conversion between equivalent formats.
So, if you just want to import that certificate in a new ad-hoc keystore you can do it with Keystore Explorer, a graphical tool. You'll be able to modify the keystore and the certificates contained therein like you would have done with the java terminal utilities like keytool
(but in a more accessible way).
Sending intent to BroadcastReceiver from adb
As many already noticed, the problem manifests itself only if the extra string contains whitespaces.
The root cause is that OP's host OS/shell (i.e. Windows/cmd.exe) mangles the entered command - the "
characters get lost, --es sms_body "test from adb"
becomes --es sms_body test from adb
. Which results in sms_body
string extra getting assigned the value of test
and the rest of the string becoming <URI>|<PACKAGE>|<COMPONENT>
specifier.
To avoid all that you could use:
adb shell "am broadcast -a com.whereismywifeserver.intent.TEST --es sms_body 'test from adb' -n com.whereismywifeserver/.IntentReceiver"
or just start the interactive adb shell
session first and run the am broadcast
command from inside of it.
Python loop for inside lambda
Just in case, if someone is looking for a similar problem...
Most solutions given here are one line and are quite readable and simple. Just wanted to add one more that does not need the use of lambda(I am assuming that you are trying to use lambda just for the sake of making it a one line code).
Instead, you can use a simple list comprehension.
[print(i) for i in x]
BTW, the return values will be a list on None s.
ng-if check if array is empty
To overcome the null
/ undefined
issue, try using the ?
operator to check existence:
<p ng-if="post?.capabilities?.items?.length > 0">
Sidenote, if anyone got to this page looking for an Ionic Framework answer, ensure you use *ngIf
:
<p *ngIf="post?.capabilities?.items?.length > 0">
Executing set of SQL queries using batch file?
Save the commands in a .SQL
file, ex: ClearTables.sql
, say in your C:\temp
folder.
Contents of C:\Temp\ClearTables.sql
Delete from TableA;
Delete from TableB;
Delete from TableC;
Delete from TableD;
Delete from TableE;
Then use sqlcmd
to execute it as follows. Since you said the database is remote, use the following syntax (after updating for your server and database instance name).
sqlcmd -S <ComputerName>\<InstanceName> -i C:\Temp\ClearTables.sql
For example, if your remote computer name is SQLSVRBOSTON1 and Database instance name is MyDB1, then the command would be.
sqlcmd -E -S SQLSVRBOSTON1\MyDB1 -i C:\Temp\ClearTables.sql
Also note that -E
specifies default authentication. If you have a user name and password to connect, use -U
and -P
switches.
You will execute all this by opening a CMD
command window.
Using a Batch File.
If you want to save it in a batch file and double-click to run it, do it as follows.
Create, and save the ClearTables.bat
like so.
echo off
sqlcmd -E -S SQLSVRBOSTON1\MyDB1 -i C:\Temp\ClearTables.sql
set /p delExit=Press the ENTER key to exit...:
Then double-click it to run it. It will execute the commands and wait until you press a key to exit, so you can see the command output.
Spring: @Component versus @Bean
@Component
and @Bean
do two quite different things, and shouldn't be confused.
@Component
(and @Service
and @Repository
) are used to auto-detect and auto-configure beans using classpath scanning. There's an implicit one-to-one mapping between the annotated class and the bean (i.e. one bean per class). Control of wiring is quite limited with this approach, since it's purely declarative.
@Bean
is used to explicitly declare a single bean, rather than letting Spring do it automatically as above. It decouples the declaration of the bean from the class definition, and lets you create and configure beans exactly how you choose.
To answer your question...
would it have been possible to re-use the @Component
annotation instead of introducing @Bean
annotation?
Sure, probably; but they chose not to, since the two are quite different. Spring's already confusing enough without muddying the waters further.
How to install pip3 on Windows?
On Windows pip3
should be in the Scripts
path of your Python installation:
C:\path\to\python\Scripts\pip3
Use:
where python
to find out where your Python executable(s) is/are located. The result should look like this:
C:\path\to\python\python.exe
or:
C:\path\to\python\python3.exe
You can check if pip3
works with this absolute path:
C:\path\to\python\Scripts\pip3
if yes, add C:\path\to\python\Scripts
to your environmental variable PATH
.
How to export SQL Server 2005 query to CSV
I had to do one more thing than what Sijin said to get it to add quotes properly in SQL Server Management Studio 2005. Go to
Tools->Options->Query Results->Sql Server->Results To Grid
Put a check next to this option:
Quote strings containing list separators when saving .csv results
Note: the above method will not work for SSMS 2005 Express! As far as I know there's no way to quote the fields when exporting results to .csv using SSMS 2005 Express.
JSF(Primefaces) ajax update of several elements by ID's
If the to-be-updated component is not inside the same NamingContainer
component (ui:repeat
, h:form
, h:dataTable
, etc), then you need to specify the "absolute" client ID. Prefix with :
(the default NamingContainer
separator character) to start from root.
<p:ajax process="@this" update="count :subTotal"/>
To be sure, check the client ID of the subTotal
component in the generated HTML for the actual value. If it's inside for example a h:form
as well, then it's prefixed with its client ID as well and you would need to fix it accordingly.
<p:ajax process="@this" update="count :formId:subTotal"/>
Space separation of IDs is more recommended as <f:ajax>
doesn't support comma separation and starters would otherwise get confused.
Why does Vim save files with a ~ extension?
You're correct that the .swp
file is used by vim for locking and as a recovery file.
Try putting set nobackup
in your vimrc if you don't want these files. See the Vim docs for various backup related options if you want the whole scoop, or want to have .bak files instead...
Iterate over object in Angular
try to use this pipe
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({ name: 'values', pure: false })
export class ValuesPipe implements PipeTransform {
transform(value: any, args: any[] = null): any {
return Object.keys(value).map(key => value[key]);
}
}
<div *ngFor="#value of object | values"> </div>
How to encrypt String in Java
How about this:
private static byte[] xor(final byte[] input, final byte[] secret) {
final byte[] output = new byte[input.length];
if (secret.length == 0) {
throw new IllegalArgumentException("empty security key");
}
int spos = 0;
for (int pos = 0; pos < input.length; ++pos) {
output[pos] = (byte) (input[pos] ^ secret[spos]);
++spos;
if (spos >= secret.length) {
spos = 0;
}
}
return output;
}
Works fine for me and is rather compact.
Google Maps API v2: How to make markers clickable?
Step 1
public class TopAttractions extends Fragment implements OnMapReadyCallback,
GoogleMap.OnMarkerClickListener
Step 2
gMap.setOnMarkerClickListener(this);
Step 3
@Override
public boolean onMarkerClick(Marker marker) {
if(marker.getTitle().equals("sharm el-shek"))
Toast.makeText(getActivity().getApplicationContext(), "Hamdy", Toast.LENGTH_SHORT).show();
return false;
}
Overlapping Views in Android
Android handles transparency across views and drawables (including PNG images) natively, so the scenario you describe (a partially transparent ImageView
in front of a Gallery
) is certainly possible.
If you're having problems it may be related to either the layout or your image. I've replicated the layout you describe and successfully achieved the effect you're after. Here's the exact layout I used.
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/gallerylayout"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<Gallery
android:id="@+id/overview"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<ImageView
android:id="@+id/navigmaske"
android:background="#0000"
android:src="@drawable/navigmask"
android:scaleType="fitXY"
android:layout_alignTop="@id/overview"
android:layout_alignBottom="@id/overview"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
</RelativeLayout>
Note that I've changed the parent RelativeLayout
to a height and width of fill_parent
as is generally what you want for a main Activity. Then I've aligned the top and bottom of the ImageView
to the top and bottom of the Gallery
to ensure it's centered in front of it.
I've also explicitly set the background of the ImageView
to be transparent.
As for the image drawable itself, if you put the PNG file somewhere for me to look at I can use it in my project and see if it's responsible.
How to get list of dates between two dates in mysql select query
Try:
select * from
(select adddate('1970-01-01',t4.i*10000 + t3.i*1000 + t2.i*100 + t1.i*10 + t0.i) selected_date from
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t0,
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t1,
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t2,
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t3,
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t4) v
where selected_date between '2012-02-10' and '2012-02-15'
-for date ranges up to nearly 300 years in the future.
[Corrected following a suggested edit by UrvishAtSynapse.]
How can I auto-elevate my batch file, so that it requests from UAC administrator rights if required?
Following solution is clean and works perfectly.
Download Elevate zip file from https://www.winability.com/download/Elevate.zip
Inside zip you should find two files: Elevate.exe and Elevate64.exe. (The latter is a native 64-bit compilation, if you require that, although the regular 32-bit version, Elevate.exe, should work fine with both the 32- and 64-bit versions of Windows)
Copy the file Elevate.exe into a folder where Windows can always find it (such as C:/Windows). Or you better you can copy in same folder where you are planning to keep your bat file.
To use it in a batch file, just prepend the command you want to execute as administrator with the elevate command, like this:
elevate net start service ...
Get filename from file pointer
You can get the path via fp.name
. Example:
>>> f = open('foo/bar.txt')
>>> f.name
'foo/bar.txt'
You might need os.path.basename
if you want only the file name:
>>> import os
>>> f = open('foo/bar.txt')
>>> os.path.basename(f.name)
'bar.txt'
File object docs (for Python 2) here.
How do I show multiple recaptchas on a single page?
This answer is an extension to @raphadko's answer.
If you need to extract manually the captcha code (like in ajax requests) you have to call:
grecaptcha.getResponse(widget_id)
But how can you retrieve the widget id parameter?
I use this definition of CaptchaCallback to store the widget id of each g-recaptcha box (as an HTML data attribute):
var CaptchaCallback = function() {
jQuery('.g-recaptcha').each(function(index, el) {
var widgetId = grecaptcha.render(el, {'sitekey' : 'your code'});
jQuery(this).attr('data-widget-id', widgetId);
});
};
Then I can call:
grecaptcha.getResponse(jQuery('#your_recaptcha_box_id').attr('data-widget-id'));
to extract the code.
OpenSSL and error in reading openssl.conf file
I know this question is old but here is how I solved it.
I copied the openssl.cnf
file from the bin
directory to the parent directory which is C:/Openssl/openssl.cnf
instead of C:/Openssl/bin/openssl.cnf
and worked fine.
php multidimensional array get values
This is the way to iterate on this array:
foreach($hotels as $row) {
foreach($row['rooms'] as $k) {
echo $k['boards']['board_id'];
echo $k['boards']['price'];
}
}
You want to iterate on the hotels and the rooms (the ones with numeric indexes), because those seem to be the "collections" in this case. The other arrays only hold and group properties.
How to execute a shell script on a remote server using Ansible?
local_action
runs the command on the local server, not on the servers you specify in hosts
parameter.
Change your "Execute the script" task to
- name: Execute the script
command: sh /home/test_user/test.sh
and it should do it.
You don't need to repeat sudo in the command line because you have defined it already in the playbook.
According to Ansible Intro to Playbooks user
parameter was renamed to remote_user
in Ansible 1.4 so you should change it, too
remote_user: test_user
So, the playbook will become:
---
- name: Transfer and execute a script.
hosts: server
remote_user: test_user
sudo: yes
tasks:
- name: Transfer the script
copy: src=test.sh dest=/home/test_user mode=0777
- name: Execute the script
command: sh /home/test_user/test.sh
Swapping two variable value without using third variable
Of course, the C++ answer should be std::swap
.
However, there is also no third variable in the following implementation of swap
:
template <typename T>
void swap (T &a, T &b) {
std::pair<T &, T &>(a, b) = std::make_pair(b, a);
}
Or, as a one-liner:
std::make_pair(std::ref(a), std::ref(b)) = std::make_pair(b, a);
Add Items to ListView - Android
ListView myListView = (ListView) rootView.findViewById(R.id.myListView);
ArrayList<String> myStringArray1 = new ArrayList<String>();
myStringArray1.add("something");
adapter = new CustomAdapter(getActivity(), R.layout.row, myStringArray1);
myListView.setAdapter(adapter);
Try it like this
public OnClickListener moreListener = new OnClickListener() {
@Override
public void onClick(View v) {
adapter = null;
myStringArray1.add("Andrea");
adapter = new CustomAdapter(getActivity(), R.layout.row, myStringArray1);
myListView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
};
Fill SVG path element with a background-image
You can do it by making the background into a pattern:
<defs>
<pattern id="img1" patternUnits="userSpaceOnUse" width="100" height="100">
<image href="wall.jpg" x="0" y="0" width="100" height="100" />
</pattern>
</defs>
Adjust the width and height according to your image, then reference it from the path like this:
<path d="M5,50
l0,100 l100,0 l0,-100 l-100,0
M215,100
a50,50 0 1 1 -100,0 50,50 0 1 1 100,0
M265,50
l50,100 l-100,0 l50,-100
z"
fill="url(#img1)" />
Working example
sscanf in Python
You could install pandas and use pandas.read_fwf
for fixed width format files. Example using /proc/net/arp
:
In [230]: df = pandas.read_fwf("/proc/net/arp")
In [231]: print(df)
IP address HW type Flags HW address Mask Device
0 141.38.28.115 0x1 0x2 84:2b:2b:ad:e1:f4 * eth0
1 141.38.28.203 0x1 0x2 c4:34:6b:5b:e4:7d * eth0
2 141.38.28.140 0x1 0x2 00:19:99:ce:00:19 * eth0
3 141.38.28.202 0x1 0x2 90:1b:0e:14:a1:e3 * eth0
4 141.38.28.17 0x1 0x2 90:1b:0e:1a:4b:41 * eth0
5 141.38.28.60 0x1 0x2 00:19:99:cc:aa:58 * eth0
6 141.38.28.233 0x1 0x2 90:1b:0e:8d:7a:c9 * eth0
7 141.38.28.55 0x1 0x2 00:19:99:cc:ab:00 * eth0
8 141.38.28.224 0x1 0x2 90:1b:0e:8d:7a:e2 * eth0
9 141.38.28.148 0x1 0x0 4c:52:62:a8:08:2c * eth0
10 141.38.28.179 0x1 0x2 90:1b:0e:1a:4b:50 * eth0
In [232]: df["HW address"]
Out[232]:
0 84:2b:2b:ad:e1:f4
1 c4:34:6b:5b:e4:7d
2 00:19:99:ce:00:19
3 90:1b:0e:14:a1:e3
4 90:1b:0e:1a:4b:41
5 00:19:99:cc:aa:58
6 90:1b:0e:8d:7a:c9
7 00:19:99:cc:ab:00
8 90:1b:0e:8d:7a:e2
9 4c:52:62:a8:08:2c
10 90:1b:0e:1a:4b:50
In [233]: df["HW address"][5]
Out[233]: '00:19:99:cc:aa:58'
By default it tries to figure out the format automagically, but there are options you can give for more explicit instructions (see documentation). There are also other IO routines in pandas that are powerful for other file formats.
How to wait in bash for several subprocesses to finish and return exit code !=0 when any subprocess ends with code !=0?
I've had a go at this and combined all the best parts from the other examples here. This script will execute the checkpids
function when any background process exits, and output the exit status without resorting to polling.
#!/bin/bash
set -o monitor
sleep 2 &
sleep 4 && exit 1 &
sleep 6 &
pids=`jobs -p`
checkpids() {
for pid in $pids; do
if kill -0 $pid 2>/dev/null; then
echo $pid is still alive.
elif wait $pid; then
echo $pid exited with zero exit status.
else
echo $pid exited with non-zero exit status.
fi
done
echo
}
trap checkpids CHLD
wait
Handle file download from ajax post
Here is my solution, gathered from different sources:
Server side implementation :
String contentType = MediaType.APPLICATION_OCTET_STREAM_VALUE;
// Set headers
response.setHeader("content-disposition", "attachment; filename =" + fileName);
response.setContentType(contentType);
// Copy file to output stream
ServletOutputStream servletOutputStream = response.getOutputStream();
try (InputStream inputStream = new FileInputStream(file)) {
IOUtils.copy(inputStream, servletOutputStream);
} finally {
servletOutputStream.flush();
Utils.closeQuitely(servletOutputStream);
fileToDownload = null;
}
Client side implementation (using jquery):
$.ajax({
type: 'POST',
contentType: 'application/json',
url: <download file url>,
data: JSON.stringify(postObject),
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(errorThrown);
},
success: function(message, textStatus, response) {
var header = response.getResponseHeader('Content-Disposition');
var fileName = header.split("=")[1];
var blob = new Blob([message]);
var link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = fileName;
link.click();
}
});
Convert any object to a byte[]
Like others have said before, you could use binary serialization, but it may produce an extra bytes or be deserialized into an objects with not exactly same data. Using reflection on the other hand is quite complicated and very slow.
There is an another solution that can strictly convert your objects to bytes and vise-versa - marshalling:
var size = Marshal.SizeOf(your_object);
// Both managed and unmanaged buffers required.
var bytes = new byte[size];
var ptr = Marshal.AllocHGlobal(size);
// Copy object byte-to-byte to unmanaged memory.
Marshal.StructureToPtr(your_object, ptr, false);
// Copy data from unmanaged memory to managed buffer.
Marshal.Copy(ptr, bytes, 0, size);
// Release unmanaged memory.
Marshal.FreeHGlobal(ptr);
And to convert bytes to object:
var bytes = new byte[size];
var ptr = Marshal.AllocHGlobal(size);
Marshal.Copy(bytes, 0, ptr, size);
var your_object = (YourType)Marshal.PtrToStructure(ptr, typeof(YourType));
Marshal.FreeHGlobal(ptr);
It's noticeably slower and partly unsafe to use this approach for small objects and structs comparing to your own serialization field by field (because of double copying from/to unmanaged memory), but it's easiest way to strictly convert object to byte[] without implementing serialization and without [Serializable] attribute.
How can I check if a string contains a character in C#?
You can use the IndexOf
method, which has a suitable overload for string comparison types:
if (def.IndexOf("s", StringComparison.OrdinalIgnoreCase) >= 0) ...
Also, you would not need the == true
, since an if statement only expects an expression that evaluates to a bool
.
What does the shrink-to-fit viewport meta attribute do?
It is Safari specific, at least at time of writing, being introduced in Safari 9.0. From the "What's new in Safari?" documentation for Safari 9.0:
Viewport Changes
Viewport meta tags using "width=device-width"
cause the page to scale down to fit content that overflows the viewport bounds. You can override this behavior by adding "shrink-to-fit=no"
to your meta tag as shown below. The added value will prevent the page from scaling to fit the viewport.
<meta name="viewport" content="width=device-width, initial-scale=1.0, shrink-to-fit=no">
In short, adding this to the viewport meta tag restores pre-Safari 9.0 behaviour.
Example
Here's a worked visual example which shows the difference upon loading the page in the two configurations.
The red section is the width of the viewport and the blue section is positioned outside the initial viewport (eg left: 100vw
). Note how in the first example the page is zoomed to fit when shrink-to-fit=no
is omitted (thus showing the out-of-viewport content) and the blue content remains off screen in the latter example.
The code for this example can be found at https://codepen.io/davidjb/pen/ENGqpv.
Without shrink-to-fit specified
With shrink-to-fit=no
Android: How to bind spinner to custom object list?
Do:
spinner.adapter = object: ArrayAdapter<Project>(
container.context,
android.R.layout.simple_spinner_dropdown_item,
state.projects
) {
override fun getDropDownView(
position: Int,
convertView: View?,
parent: ViewGroup
): View {
val label = super.getView(position, convertView, parent) as TextView
label.text = getItem(position)?.title
return label
}
override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
val label = super.getView(position, convertView, parent) as TextView
label.text = getItem(position)?.title
return label
}
}
How to convert the system date format to dd/mm/yy in SQL Server 2008 R2?
SELECT CONVERT(varchar(11),getdate(),101) -- mm/dd/yyyy
SELECT CONVERT(varchar(11),getdate(),103) -- dd/mm/yyyy
Check this . I am assuming D30.SPGD30_TRACKED_ADJUSTMENT_X is of datetime datatype .
That is why i am using CAST()
function to make it as an character expression because CHARINDEX()
works on character expression.
Also I think there is no need of OR condition.
select case when CHARINDEX('-',cast(D30.SPGD30_TRACKED_ADJUSTMENT_X as varchar )) > 0
then 'Score Calculation - '+CONVERT(VARCHAR(11), D30.SPGD30_TRACKED_ADJUSTMENT_X, 103)
end
EDIT:
select case when CHARINDEX('-',D30.SPGD30_TRACKED_ADJUSTMENT_X) > 0
then 'Score Calculation - '+
CONVERT( VARCHAR(11), CAST(D30.SPGD30_TRACKED_ADJUSTMENT_X as DATETIME) , 103)
end
See this link for conversion to other date formats: https://www.w3schools.com/sql/func_sqlserver_convert.asp
POST Multipart Form Data using Retrofit 2.0 including image
Update Code for image file uploading in Retrofit2.0
public interface ApiInterface {
@Multipart
@POST("user/signup")
Call<UserModelResponse> updateProfilePhotoProcess(@Part("email") RequestBody email,
@Part("password") RequestBody password,
@Part("profile_pic\"; filename=\"pp.png")
RequestBody file);
}
Change MediaType.parse("image/*")
to MediaType.parse("image/jpeg")
RequestBody reqFile = RequestBody.create(MediaType.parse("image/jpeg"),
file);
RequestBody email = RequestBody.create(MediaType.parse("text/plain"),
"[email protected]");
RequestBody password = RequestBody.create(MediaType.parse("text/plain"),
"123456789");
Call<UserModelResponse> call = apiService.updateProfilePhotoProcess(email,
password,
reqFile);
call.enqueue(new Callback<UserModelResponse>() {
@Override
public void onResponse(Call<UserModelResponse> call,
Response<UserModelResponse> response) {
String
TAG =
response.body()
.toString();
UserModelResponse userModelResponse = response.body();
UserModel userModel = userModelResponse.getUserModel();
Log.d("MainActivity",
"user image = " + userModel.getProfilePic());
}
@Override
public void onFailure(Call<UserModelResponse> call,
Throwable t) {
Toast.makeText(MainActivity.this,
"" + TAG,
Toast.LENGTH_LONG)
.show();
}
});
Change windows hostname from command line
Here's another way of doing it with a WHS script:
Set objWMIService = GetObject("Winmgmts:root\cimv2")
For Each objComputer in _
objWMIService.InstancesOf("Win32_ComputerSystem")
objComputer.rename "NewComputerName", NULL, NULL
Next
Source
How do I revert back to an OpenWrt router configuration?
Those who are facing this problem: Don't panic.
Short answer:
Restart your router, and this problem will be fixed. (But if your restart button is not working, you need to do a nine-step process to do the restart. Hitting the restart button is just one of them.)
Long answer: Let's learn how to restart the router.
- Set your PC's IP address: 192.168.1.2 and subnetmask 255.255.255.0 and gateway 192.168.1.1
- Power off the router
- Disconnect the WAN cable
- Only connect your PC Ethernet cable to ETH0
- Power on the router
- Wait for the router to start the boot sequence (SYS LED starts blinking)
- When the SYS LED is blinking, hit the restart button (the SYS LED will be blinking at a faster rate means your router is in failsafe mode). (You have to hit the button before the router boots.)
telnet 192.168.1.1
Run these commands:
mount_root ## this remounts your partitions from read-only to read/write mode
firstboot ## This will reset your router after reboot
reboot -f ## And force reboot
Log in the web interface using web browser.
link to see the official failsafe mode.
How to get current relative directory of your Makefile?
The shell function.
You can use shell
function: current_dir = $(shell pwd)
.
Or shell
in combination with notdir
, if you need not absolute path:
current_dir = $(notdir $(shell pwd))
.
Update.
Given solution only works when you are running make
from the Makefile's current directory.
As @Flimm noted:
Note that this returns the current working directory, not the parent directory of the Makefile.
For example, if you run cd /; make -f /home/username/project/Makefile
, the current_dir
variable will be /
, not /home/username/project/
.
Code below will work for Makefiles invoked from any directory:
mkfile_path := $(abspath $(lastword $(MAKEFILE_LIST)))
current_dir := $(notdir $(patsubst %/,%,$(dir $(mkfile_path))))
SQL Server: Null VS Empty String
How are the "NULL" and "empty varchar" values stored in SQL Server.
Why would you want to know that? Or in other words, if you knew the answer, how would you use that information?
And in case I have no user entry for a string field on my UI, should I store a NULL or a ''?
It depends on the nature of your field. Ask yourself whether the empty string is a valid value for your field.
If it is (for example, house name in an address) then that might be what you want to store (depending on whether or not you know that the address has no house name).
If it's not (for example, a person's name), then you should store a null, because people don't have blank names (in any culture, so far as I know).
Node.js - Maximum call stack size exceeded
In some languages this can be solved with tail call optimization, where the recursion call is transformed under the hood into a loop so no maximum stack size reached error exists.
But in javascript the current engines don't support this, it's foreseen for new version of the language Ecmascript 6.
Node.js has some flags to enable ES6 features but tail call is not yet available.
So you can refactor your code to implement a technique called trampolining, or refactor in order to transform recursion into a loop.
How to position a CSS triangle using ::after?
You can set triangle with position see this code for reference
.top-left-corner {
width: 0px;
height: 0px;
border-top: 0px solid transparent;
border-bottom: 55px solid transparent;
border-left: 55px solid #289006;
position: absolute;
left: 0px;
top: 0px;
}
Construct a manual legend for a complicated plot
You need to map attributes to aesthetics (colours within the aes statement) to produce a legend.
cols <- c("LINE1"="#f04546","LINE2"="#3591d1","BAR"="#62c76b")
ggplot(data=data,aes(x=a)) +
geom_bar(stat="identity", aes(y=h, fill = "BAR"),colour="#333333")+ #green
geom_line(aes(y=b,group=1, colour="LINE1"),size=1.0) + #red
geom_point(aes(y=b, colour="LINE1"),size=3) + #red
geom_errorbar(aes(ymin=d, ymax=e, colour="LINE1"), width=0.1, size=.8) +
geom_line(aes(y=c,group=1,colour="LINE2"),size=1.0) + #blue
geom_point(aes(y=c,colour="LINE2"),size=3) + #blue
geom_errorbar(aes(ymin=f, ymax=g,colour="LINE2"), width=0.1, size=.8) +
scale_colour_manual(name="Error Bars",values=cols) + scale_fill_manual(name="Bar",values=cols) +
ylab("Symptom severity") + xlab("PHQ-9 symptoms") +
ylim(0,1.6) +
theme_bw() +
theme(axis.title.x = element_text(size = 15, vjust=-.2)) +
theme(axis.title.y = element_text(size = 15, vjust=0.3))
I understand where Roland is coming from, but since this is only 3 attributes, and complications arise from superimposing bars and error bars this may be reasonable to leave the data in wide format like it is. It could be slightly reduced in complexity by using geom_pointrange.
To change the background color for the error bars legend in the original, add + theme(legend.key = element_rect(fill = "white",colour = "white"))
to the plot specification. To merge different legends, you typically need to have a consistent mapping for all elements, but it is currently producing an artifact of a black background for me. I thought guide = guide_legend(fill = NULL,colour = NULL)
would set the background to null for the legend, but it did not. Perhaps worth another question.
ggplot(data=data,aes(x=a)) +
geom_bar(stat="identity", aes(y=h,fill = "BAR", colour="BAR"))+ #green
geom_line(aes(y=b,group=1, colour="LINE1"),size=1.0) + #red
geom_point(aes(y=b, colour="LINE1", fill="LINE1"),size=3) + #red
geom_errorbar(aes(ymin=d, ymax=e, colour="LINE1"), width=0.1, size=.8) +
geom_line(aes(y=c,group=1,colour="LINE2"),size=1.0) + #blue
geom_point(aes(y=c,colour="LINE2", fill="LINE2"),size=3) + #blue
geom_errorbar(aes(ymin=f, ymax=g,colour="LINE2"), width=0.1, size=.8) +
scale_colour_manual(name="Error Bars",values=cols, guide = guide_legend(fill = NULL,colour = NULL)) +
scale_fill_manual(name="Bar",values=cols, guide="none") +
ylab("Symptom severity") + xlab("PHQ-9 symptoms") +
ylim(0,1.6) +
theme_bw() +
theme(axis.title.x = element_text(size = 15, vjust=-.2)) +
theme(axis.title.y = element_text(size = 15, vjust=0.3))
To get rid of the black background in the legend, you need to use the override.aes
argument to the guide_legend
. The purpose of this is to let you specify a particular aspect of the legend which may not be being assigned correctly.
ggplot(data=data,aes(x=a)) +
geom_bar(stat="identity", aes(y=h,fill = "BAR", colour="BAR"))+ #green
geom_line(aes(y=b,group=1, colour="LINE1"),size=1.0) + #red
geom_point(aes(y=b, colour="LINE1", fill="LINE1"),size=3) + #red
geom_errorbar(aes(ymin=d, ymax=e, colour="LINE1"), width=0.1, size=.8) +
geom_line(aes(y=c,group=1,colour="LINE2"),size=1.0) + #blue
geom_point(aes(y=c,colour="LINE2", fill="LINE2"),size=3) + #blue
geom_errorbar(aes(ymin=f, ymax=g,colour="LINE2"), width=0.1, size=.8) +
scale_colour_manual(name="Error Bars",values=cols,
guide = guide_legend(override.aes=aes(fill=NA))) +
scale_fill_manual(name="Bar",values=cols, guide="none") +
ylab("Symptom severity") + xlab("PHQ-9 symptoms") +
ylim(0,1.6) +
theme_bw() +
theme(axis.title.x = element_text(size = 15, vjust=-.2)) +
theme(axis.title.y = element_text(size = 15, vjust=0.3))
Position Absolute + Scrolling
position: fixed;
will solve your issue. As an example, review my implementation of a fixed message area overlay (populated programmatically):
#mess {
position: fixed;
background-color: black;
top: 20px;
right: 50px;
height: 10px;
width: 600px;
z-index: 1000;
}
And in the HTML
<body>
<div id="mess"></div>
<div id="data">
Much content goes here.
</div>
</body>
When #data
becomes longer tha the sceen, #mess
keeps its position on the screen, while #data
scrolls under it.
What is a tracking branch?
The ProGit book has a very good explanation:
Tracking Branches
Checking out a local branch from a remote branch automatically creates what is called a tracking branch. Tracking branches are local branches that have a direct relationship to a remote branch. If you’re on a tracking branch and type git push
, Git automatically knows which server and branch to push to. Also, running git pull
while on one of these branches fetches all the remote references and then automatically merges in the corresponding remote branch.
When you clone a repository, it generally automatically creates a master branch that tracks origin/master. That’s why git push
and git pull
work out of the box with no other arguments. However, you can set up other tracking branches if you wish — ones that don’t track branches on origin and don’t track the master branch. The simple case is the example you just saw, running git checkout -b [branch] [remotename]/[branch]
. If you have Git version 1.6.2 or later, you can also use the --track
shorthand:
$ git checkout --track origin/serverfix
Branch serverfix set up to track remote branch refs/remotes/origin/serverfix.
Switched to a new branch "serverfix"
To set up a local branch with a different name than the remote branch, you can easily use the first version with a different local branch name:
$ git checkout -b sf origin/serverfix
Branch sf set up to track remote branch refs/remotes/origin/serverfix.
Switched to a new branch "sf"
Now, your local branch sf
will automatically push to and pull from origin/serverfix
.
BONUS: extra git status
info
With a tracking branch, git status
will tell you whether how far behind your tracking branch you are - useful to remind you that you haven't pushed your changes yet! It looks like this:
$ git status
On branch master
Your branch is ahead of 'origin/master' by 1 commit.
(use "git push" to publish your local commits)
or
$ git status
On branch dev
Your branch and 'origin/dev' have diverged,
and have 3 and 1 different commits each, respectively.
(use "git pull" to merge the remote branch into yours)
How do you redirect to a page using the POST verb?
HTTP doesn't support redirection to a page using POST. When you redirect somewhere, the HTTP "Location" header tells the browser where to go, and the browser makes a GET request for that page. You'll probably have to just write the code for your page to accept GET requests as well as POST requests.
How to execute a Python script from the Django shell?
Late to the party. But this might be helpful for someone.
All you need is your script and django-extensions
installed.
Just run the shell_plus
available in django_extensions
and import the script that you've written.
If your script is scpt.py
and it's inside a folder fol
you can run the script as follows.
python manage.py shell_plus
and just import your script inside the shell as follows.
>>> from fol import scpt
Where is `%p` useful with printf?
x
is used to print t pointer argument in hexadecimal.
A typical address when printed using %x
would look like bfffc6e4
and the sane address printed using %p
would be 0xbfffc6e4
How to make an ng-click event conditional?
I use the && expression which works perfectly for me.
For example,
<button ng-model="vm.slideOneValid" ng-disabled="!vm.slideOneValid" ng-click="vm.slideOneValid && vm.nextSlide()" class="btn btn-light-green btn-medium pull-right">Next</button>
If vm.slideOneValid
is false, the second part of the expression is not fired. I know this is putting logic into the DOM, but it's a quick a dirty way to get ng-disabled and ng-click to place nice.
Just remember to add ng-model to the element to make ng-disabled work.
Remove folder and its contents from git/GitHub's history
For Windows user, please note to use "
instead of '
Also added -f
to force the command if another backup is already there.
git filter-branch -f --tree-filter "rm -rf FOLDERNAME" --prune-empty HEAD
git for-each-ref --format="%(refname)" refs/original/ | xargs -n 1 git update-ref -d
echo FOLDERNAME/ >> .gitignore
git add .gitignore
git commit -m "Removing FOLDERNAME from git history"
git gc
git push origin master --force
I need a Nodejs scheduler that allows for tasks at different intervals
I would recommend node-cron
. It allows to run tasks using Cron patterns e.g.
'* * * * * *' - runs every second
'*/5 * * * * *' - runs every 5 seconds
'10,20,30 * * * * *' - run at 10th, 20th and 30th second of every minute
'0 * * * * *' - runs every minute
'0 0 * * * *' - runs every hour (at 0 minutes and 0 seconds)
But also more complex schedules e.g.
'00 30 11 * * 1-5' - Runs every weekday (Monday through Friday) at 11:30:00 AM. It does not run on Saturday or Sunday.
Sample code: running job every 10 minutes:
var cron = require('cron');
var cronJob = cron.job("0 */10 * * * *", function(){
// perform operation e.g. GET request http.get() etc.
console.info('cron job completed');
});
cronJob.start();
You can find more examples in node-cron wiki
More on cron configuration can be found on cron wiki
I've been using that library in many projects and it does the job. I hope that will help.
How to cin Space in c++?
#include <iostream>
#include <string>
int main()
{
std::string a;
std::getline(std::cin,a);
for(std::string::size_type i = 0; i < a.size(); ++i)
{
if(a[i] == ' ')
std::cout<<"It is a space!!!"<<std::endl;
}
return 0;
}
javascript scroll event for iPhone/iPad?
For iOS you need to use the touchmove event as well as the scroll event like this:
document.addEventListener("touchmove", ScrollStart, false);
document.addEventListener("scroll", Scroll, false);
function ScrollStart() {
//start of scroll event for iOS
}
function Scroll() {
//end of scroll event for iOS
//and
//start/end of scroll event for other browsers
}
Where to install Android SDK on Mac OS X?
In homebrew the android-sdk
has migrated from homebrew/core
to homebrew/cask
.
brew tap homebrew/cask
and install android-sdk
using
brew cask install android-sdk
You will have to add the ANDROID_HOME
to profile (.zshrc or .bashrc)
export ANDROID_HOME=/usr/local/share/android-sdk
If you prefer otherwise, copy the package to
~/opt/local/android-sdk-mac
Matplotlib/pyplot: How to enforce axis range?
Calling p.plot
after setting the limits is why it is rescaling. You are correct in that turning autoscaling off will get the right answer, but so will calling xlim()
or ylim()
after your plot
command.
I use this quite a lot to invert the x axis, I work in astronomy and we use a magnitude system which is backwards (ie. brighter stars have a smaller magnitude) so I usually swap the limits with
lims = xlim()
xlim([lims[1], lims[0]])
How do I remove a file from the FileList
This is extemporary, but I had the same problem which I solved this way. In my case I was uploading the files via XMLHttp request, so I was able to post the FileList cloned data through formdata appending. Functionality is that you can drag and drop or select multiple files as many times as you want (selecting files again won't reset the cloned FileList), remove any file you want from the (cloned) file list, and submit via xmlhttprequest whatever was left there. This is what I did. It is my first post here so code is a little messy. Sorry. Ah, and I had to use jQuery instead of $ as it was in Joomla script.
// some global variables
var clon = {}; // will be my FileList clone
var removedkeys = 0; // removed keys counter for later processing the request
var NextId = 0; // counter to add entries to the clone and not replace existing ones
jQuery(document).ready(function(){
jQuery("#form input").change(function () {
// making the clone
var curFiles = this.files;
// temporary object clone before copying info to the clone
var temparr = jQuery.extend(true, {}, curFiles);
// delete unnecessary FileList keys that were cloned
delete temparr["length"];
delete temparr["item"];
if (Object.keys(clon).length === 0){
jQuery.extend(true, clon, temparr);
}else{
var keysArr = Object.keys(clon);
NextId = Math.max.apply(null, keysArr)+1; // FileList keys are numbers
if (NextId < curFiles.length){ // a bug I found and had to solve for not replacing my temparr keys...
NextId = curFiles.length;
}
for (var key in temparr) { // I have to rename new entries for not overwriting existing keys in clon
if (temparr.hasOwnProperty(key)) {
temparr[NextId] = temparr[key];
delete temparr[key];
// meter aca los cambios de id en los html tags con el nuevo NextId
NextId++;
}
}
jQuery.extend(true, clon, temparr); // copy new entries to clon
}
// modifying the html file list display
if (NextId === 0){
jQuery("#filelist").html("");
for(var i=0; i<curFiles.length; i++) {
var f = curFiles[i];
jQuery("#filelist").append("<p id=\"file"+i+"\" style=\'margin-bottom: 3px!important;\'>" + f.name + "<a style=\"float:right;cursor:pointer;\" onclick=\"BorrarFile("+i+")\">x</a></p>"); // the function BorrarFile will handle file deletion from the clone by file id
}
}else{
for(var i=0; i<curFiles.length; i++) {
var f = curFiles[i];
jQuery("#filelist").append("<p id=\"file"+(i+NextId-curFiles.length)+"\" style=\'margin-bottom: 3px!important;\'>" + f.name + "<a style=\"float:right;cursor:pointer;\" onclick=\"BorrarFile("+(i+NextId-curFiles.length)+")\">x</a></p>"); // yeap, i+NextId-curFiles.length actually gets it right
}
}
// update the total files count wherever you want
jQuery("#form p").text(Object.keys(clon).length + " file(s) selected");
});
});
function BorrarFile(id){ // handling file deletion from clone
jQuery("#file"+id).remove(); // remove the html filelist element
delete clon[id]; // delete the entry
removedkeys++; // add to removed keys counter
if (Object.keys(clon).length === 0){
jQuery("#form p").text(Object.keys(clon).length + " file(s) selected");
jQuery("#fileToUpload").val(""); // I had to reset the form file input for my form check function before submission. Else it would send even though my clone was empty
}else{
jQuery("#form p").text(Object.keys(clon).length + " file(s) selected");
}
}
// now my form check function
function check(){
if( document.getElementById("fileToUpload").files.length == 0 ){
alert("No file selected");
return false;
}else{
var _validFileExtensions = [".pdf", ".PDF"]; // I wanted pdf files
// retrieve input files
var arrInputs = clon;
// validating files
for (var i = 0; i < Object.keys(arrInputs).length+removedkeys; i++) {
if (typeof arrInputs[i]!="undefined"){
var oInput = arrInputs[i];
if (oInput.type == "application/pdf") {
var sFileName = oInput.name;
if (sFileName.length > 0) {
var blnValid = false;
for (var j = 0; j < _validFileExtensions.length; j++) {
var sCurExtension = _validFileExtensions[j];
if (sFileName.substr(sFileName.length - sCurExtension.length, sCurExtension.length).toLowerCase() == sCurExtension.toLowerCase()) {
blnValid = true;
break;
}
}
if (!blnValid) {
alert("Sorry, " + sFileName + " is invalid, allowed extensions are: " + _validFileExtensions.join(", "));
return false;
}
}
}else{
alert("Sorry, " + arrInputs[0].name + " is invalid, allowed extensions are: " + _validFileExtensions.join(" or "));
return false;
}
}
}
// proceed with the data appending and submission
// here some hidden input values i had previously set. Now retrieving them for submission. My form wasn't actually even a form...
var fecha = jQuery("#fecha").val();
var vendor = jQuery("#vendor").val();
var sku = jQuery("#sku").val();
// create the formdata object
var formData = new FormData();
formData.append("fecha", fecha);
formData.append("vendor", encodeURI(vendor));
formData.append("sku", sku);
// now appending the clone file data (finally!)
var fila = clon; // i just did this because I had already written the following using the "fila" object, so I copy my clone again
// the interesting part. As entries in my clone object aren't consecutive numbers I cannot iterate normally, so I came up with the following idea
for (i = 0; i < Object.keys(fila).length+removedkeys; i++) {
if(typeof fila[i]!="undefined"){
formData.append("fileToUpload[]", fila[i]); // VERY IMPORTANT the formdata key for the files HAS to be an array. It will be later retrieved as $_FILES['fileToUpload']['temp_name'][i]
}
}
jQuery("#submitbtn").fadeOut("slow"); // remove the upload btn so it can't be used again
jQuery("#drag").html(""); // clearing the output message element
// start the request
var xhttp = new XMLHttpRequest();
xhttp.addEventListener("progress", function(e) {
var done = e.position || e.loaded, total = e.totalSize || e.total;
}, false);
if ( xhttp.upload ) {
xhttp.upload.onprogress = function(e) {
var done = e.position || e.loaded, total = e.totalSize || e.total;
var percent = done / total;
jQuery("#drag").html(Math.round(percent * 100) + "%");
};
}
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var respuesta = this.responseText;
jQuery("#drag").html(respuesta);
}
};
xhttp.open("POST", "your_upload_handler.php", true);
xhttp.send(formData);
return true;
}
};
Now the html and styles for this. I'm quite a newbie but all this actually worked for me and took me a while to figure it out.
<div id="form" class="formpos">
<!-- Select the pdf to upload:-->
<input type="file" name="fileToUpload[]" id="fileToUpload" accept="application/pdf" multiple>
<div><p id="drag">Drop your files here or click to select them</p>
</div>
<button id="submitbtn" onclick="return check()" >Upload</button>
// these inputs are passed with different names on the formdata. Be aware of that
// I was echoing this, so that's why I use the single quote for php variables
<input type="hidden" id="fecha" name="fecha_copy" value="'.$fecha.'" />
<input type="hidden" id="vendor" name="vendorname" value="'.$vendor.'" />
<input type="hidden" id="sku" name="sku" value="'.$sku.'"" />
</div>
<h1 style="width: 500px!important;margin:20px auto 0px!important;font-size:24px!important;">File list:</h1>
<div id="filelist" style="width: 500px!important;margin:10px auto 0px!important;">Nothing selected yet</div>
The styles for that. I had to mark some of them !important to override Joomla behavior.
.formpos{
width: 500px;
height: 200px;
border: 4px dashed #999;
margin: 30px auto 100px;
}
.formpos p{
text-align: center!important;
padding: 80px 30px 0px;
color: #000;
}
.formpos div{
width: 100%!important;
height: 100%!important;
text-align: center!important;
margin-bottom: 30px!important;
}
.formpos input{
position: absolute!important;
margin: 0!important;
padding: 0!important;
width: 500px!important;
height: 200px!important;
outline: none!important;
opacity: 0!important;
}
.formpos button{
margin: 0;
color: #fff;
background: #16a085;
border: none;
width: 508px;
height: 35px;
margin-left: -4px;
border-radius: 4px;
transition: all .2s ease;
outline: none;
}
.formpos button:hover{
background: #149174;
color: #0C5645;
}
.formpos button:active{
border:0;
}
I hope this helps.
Formatting doubles for output in C#
Another method, starting with the method:
double i = (10 * 0.69);
Console.Write(ToStringFull(i)); // Output 6.89999999999999946709294817
Console.Write(ToStringFull(-6.9) // Output -6.90000000000000035527136788
Console.Write(ToStringFull(i - 6.9)); // Output -0.00000000000000088817841970012523233890533
A Drop-In Function...
public static string ToStringFull(double value)
{
if (value == 0.0) return "0.0";
if (double.IsNaN(value)) return "NaN";
if (double.IsNegativeInfinity(value)) return "-Inf";
if (double.IsPositiveInfinity(value)) return "+Inf";
long bits = BitConverter.DoubleToInt64Bits(value);
BigInteger mantissa = (bits & 0xfffffffffffffL) | 0x10000000000000L;
int exp = (int)((bits >> 52) & 0x7ffL) - 1023;
string sign = (value < 0) ? "-" : "";
if (54 > exp)
{
double offset = (exp / 3.321928094887362358); //...or =Math.Log10(Math.Abs(value))
BigInteger temp = mantissa * BigInteger.Pow(10, 26 - (int)offset) >> (52 - exp);
string numberText = temp.ToString();
int digitsNeeded = (int)((numberText[0] - '5') / 10.0 - offset);
if (exp < 0)
return sign + "0." + new string('0', digitsNeeded) + numberText;
else
return sign + numberText.Insert(1 - digitsNeeded, ".");
}
return sign + (mantissa >> (52 - exp)).ToString();
}
How it works
To solve this problem I used the BigInteger tools. Large values are simple as they just require left shifting the mantissa by the exponent. For small values we cannot just directly right shift as that would lose the precision bits. We must first give it some extra size by multiplying it by a 10^n and then do the right shifts. After that, we move over the decimal n places to the left. More text/code here.
DataGrid get selected rows' column values
An easy way that works:
private void dataGrid_SelectedCellsChanged(object sender, SelectedCellsChangedEventArgs e)
{
foreach (var item in e.AddedCells)
{
var col = item.Column as DataGridColumn;
var fc = col.GetCellContent(item.Item);
if (fc is CheckBox)
{
Debug.WriteLine("Values" + (fc as CheckBox).IsChecked);
}
else if(fc is TextBlock)
{
Debug.WriteLine("Values" + (fc as TextBlock).Text);
}
//// Like this for all available types of cells
}
}
How do you connect to multiple MySQL databases on a single webpage?
Warning : mysql_xx
functions are deprecated since php 5.5 and removed since php 7.0 (see http://php.net/manual/intro.mysql.php), use mysqli_xx
functions or see the answer below from @Troelskn
You can make multiple calls to mysql_connect()
, but if the parameters are the same you need to pass true for the '$new_link
' (fourth) parameter, otherwise the same connection is reused. For example:
$dbh1 = mysql_connect($hostname, $username, $password);
$dbh2 = mysql_connect($hostname, $username, $password, true);
mysql_select_db('database1', $dbh1);
mysql_select_db('database2', $dbh2);
Then to query database 1 pass the first link identifier:
mysql_query('select * from tablename', $dbh1);
and for database 2 pass the second:
mysql_query('select * from tablename', $dbh2);
If you do not pass a link identifier then the last connection created is used (in this case the one represented by $dbh2
) e.g.:
mysql_query('select * from tablename');
Other options
If the MySQL user has access to both databases and they are on the same host (i.e. both DBs are accessible from the same connection) you could:
- Keep one connection open and call
mysql_select_db()
to swap between as necessary. I am not sure this is a clean solution and you could end up querying the wrong database.
- Specify the database name when you reference tables within your queries (e.g.
SELECT * FROM database2.tablename
). This is likely to be a pain to implement.
Also please read troelskn's answer because that is a better approach if you are able to use PDO rather than the older extensions.
OpenCV with Network Cameras
#include <stdio.h>
#include "opencv.hpp"
int main(){
CvCapture *camera=cvCaptureFromFile("http://username:pass@cam_address/axis-cgi/mjpg/video.cgi?resolution=640x480&req_fps=30&.mjpg");
if (camera==NULL)
printf("camera is null\n");
else
printf("camera is not null");
cvNamedWindow("img");
while (cvWaitKey(10)!=atoi("q")){
double t1=(double)cvGetTickCount();
IplImage *img=cvQueryFrame(camera);
double t2=(double)cvGetTickCount();
printf("time: %gms fps: %.2g\n",(t2-t1)/(cvGetTickFrequency()*1000.), 1000./((t2-t1)/(cvGetTickFrequency()*1000.)));
cvShowImage("img",img);
}
cvReleaseCapture(&camera);
}
Javascript replace with reference to matched group?
For the replacement string and the replacement pattern as specified by $
.
here a resume:
link to doc : here
"hello _there_".replace(/_(.*?)_/g, "<div>$1</div>")
Note:
If you want to have a $
in the replacement string use $$
. Same as with vscode snippet system.
How to send JSON instead of a query string with $.ajax?
If you are sending this back to asp.net and need the data in request.form[] then you'll need to set the content type to "application/x-www-form-urlencoded; charset=utf-8"
Original post here
Secondly get rid of the Datatype, if your not expecting a return the POST will wait for about 4 minutes before failing. See here
How can I get the Windows last reboot reason
Take a look at the Event Log API. Case a) (bluescreen, user cut the power cord or system hang) causes a note ('system did not shutdown correctly' or something like that) to be left in the 'System' event log the next time the system is rebooted properly. You should be able to access it programmatically using the above API (honestly, I've never used it but it should work).
Where's javax.servlet?
javax.servlet
is a package that's part of Java EE (Java Enterprise Edition). You've got the JDK for Java SE (Java Standard Edition).
You could use the Java EE SDK for example.
Alternatively simple servlet containers such as Apache Tomcat also come with this API (look for servlet-api.jar
).
How to set maximum fullscreen in vmware?
It sounds to me as if you actually mean "linux guests" and not "linux hosts".
But in any case, I suspect you did not install the VMWare Tools: doubleclick on that icon on the Desktop that can be seen on your screenshot. It will install some drivers that communicate with VMWare that, among other things, allow to adjust the screen resolution dynamically.
When the installation process is finished, you'll most likely have to reboot the VM.
How can I upgrade NumPy?
If you don't encounter any permission errors with
pip install -U numpy
try:
pip install --user -U numpy
How to create a circular ImageView in Android?
I too needed a rounded ImageView, I used the below code, you can modify it accordingly:
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.ImageView;
public class RoundedImageView extends ImageView {
public RoundedImageView(Context context) {
super(context);
}
public RoundedImageView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public RoundedImageView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
protected void onDraw(Canvas canvas) {
Drawable drawable = getDrawable();
if (drawable == null) {
return;
}
if (getWidth() == 0 || getHeight() == 0) {
return;
}
Bitmap b = ((BitmapDrawable) drawable).getBitmap();
Bitmap bitmap = b.copy(Bitmap.Config.ARGB_8888, true);
int w = getWidth();
@SuppressWarnings("unused")
int h = getHeight();
Bitmap roundBitmap = getCroppedBitmap(bitmap, w);
canvas.drawBitmap(roundBitmap, 0, 0, null);
}
public static Bitmap getCroppedBitmap(Bitmap bmp, int radius) {
Bitmap sbmp;
if (bmp.getWidth() != radius || bmp.getHeight() != radius) {
float smallest = Math.min(bmp.getWidth(), bmp.getHeight());
float factor = smallest / radius;
sbmp = Bitmap.createScaledBitmap(bmp,
(int) (bmp.getWidth() / factor),
(int) (bmp.getHeight() / factor), false);
} else {
sbmp = bmp;
}
Bitmap output = Bitmap.createBitmap(radius, radius, Config.ARGB_8888);
Canvas canvas = new Canvas(output);
final String color = "#BAB399";
final Paint paint = new Paint();
final Rect rect = new Rect(0, 0, radius, radius);
paint.setAntiAlias(true);
paint.setFilterBitmap(true);
paint.setDither(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(Color.parseColor(color));
canvas.drawCircle(radius / 2 + 0.7f, radius / 2 + 0.7f,
radius / 2 + 0.1f, paint);
paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
canvas.drawBitmap(sbmp, rect, rect, paint);
return output;
}
}
MVC If statement in View
Every time you use html syntax you have to start the next razor statement with a @. So it should be @if ....
String method cannot be found in a main class method
It seem like your Resort
method doesn't declare a compareTo
method. This method typically belongs to the Comparable
interface. Make sure your class implements it.
Additionally, the compareTo
method is typically implemented as accepting an argument of the same type as the object the method gets invoked on. As such, you shouldn't be passing a String
argument, but rather a Resort
.
Alternatively, you can compare the names of the resorts. For example
if (resortList[mid].getResortName().compareTo(resortName)>0)
How to present popover properly in iOS 8
The following has a pretty comprehensive guide on how to configure and present popovers. https://www.appcoda.com/presentation-controllers-tutorial/
In summary, a viable implementation (with some updates from the original article syntax for Swift 4.2), to then be called from elsewhere, would be something like the following:
func showPopover(ofViewController popoverViewController: UIViewController, originView: UIView) {
popoverViewController.modalPresentationStyle = UIModalPresentationStyle.popover
if let popoverController = popoverViewController.popoverPresentationController {
popoverController.delegate = self
popoverController.sourceView = originView
popoverController.sourceRect = originView.bounds
popoverController.permittedArrowDirections = UIPopoverArrowDirection.any
}
self.present(popoverViewController, animated: true)
}
A lot of this was already covered in the answer from @mmc, but the article helps to explain some of those code elements used, and also show how it could be expanded.
It also provides a lot of additional detail about using delegation to handle the presentation style for iPhone vs. iPad, and to allow dismissal of the popover if it's ever shown full-screen. Again, updated for Swift 4.2:
func adaptivePresentationStyle(for: UIPresentationController) -> UIModalPresentationStyle {
//return UIModalPresentationStyle.fullScreen
return UIModalPresentationStyle.none
}
func adaptivePresentationStyle(for controller: UIPresentationController, traitCollection: UITraitCollection) -> UIModalPresentationStyle {
if traitCollection.horizontalSizeClass == .compact {
return UIModalPresentationStyle.none
//return UIModalPresentationStyle.fullScreen
}
//return UIModalPresentationStyle.fullScreen
return UIModalPresentationStyle.none
}
func presentationController(_ controller: UIPresentationController, viewControllerForAdaptivePresentationStyle style: UIModalPresentationStyle) -> UIViewController? {
switch style {
case .fullScreen:
let navigationController = UINavigationController(rootViewController: controller.presentedViewController)
let doneButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.done, target: self, action: #selector(doneWithPopover))
navigationController.topViewController?.navigationItem.rightBarButtonItem = doneButton
return navigationController
default:
return controller.presentedViewController
}
}
// As of Swift 4, functions used in selectors must be declared as @objc
@objc private func doneWithPopover() {
self.dismiss(animated: true, completion: nil)
}
Hope this helps.
PHP: How to send HTTP response code?
I just found this question and thought it needs a more comprehensive answer:
As of PHP 5.4 there are three methods to accomplish this:
Assembling the response code on your own (PHP >= 4.0)
The header()
function has a special use-case that detects a HTTP response line and lets you replace that with a custom one
header("HTTP/1.1 200 OK");
However, this requires special treatment for (Fast)CGI PHP:
$sapi_type = php_sapi_name();
if (substr($sapi_type, 0, 3) == 'cgi')
header("Status: 404 Not Found");
else
header("HTTP/1.1 404 Not Found");
Note: According to the HTTP RFC, the reason phrase can be any custom string (that conforms to the standard), but for the sake of client compatibility I do not recommend putting a random string there.
Note: php_sapi_name()
requires PHP 4.0.1
3rd argument to header function (PHP >= 4.3)
There are obviously a few problems when using that first variant. The biggest of which I think is that it is partly parsed by PHP or the web server and poorly documented.
Since 4.3, the header
function has a 3rd argument that lets you set the response code somewhat comfortably, but using it requires the first argument to be a non-empty string. Here are two options:
header(':', true, 404);
header('X-PHP-Response-Code: 404', true, 404);
I recommend the 2nd one. The first does work on all browsers I have tested, but some minor browsers or web crawlers may have a problem with a header line that only contains a colon. The header field name in the 2nd. variant is of course not standardized in any way and could be modified, I just chose a hopefully descriptive name.
http_response_code function (PHP >= 5.4)
The http_response_code()
function was introduced in PHP 5.4, and it made things a lot easier.
http_response_code(404);
That's all.
Compatibility
Here is a function that I have cooked up when I needed compatibility below 5.4 but wanted the functionality of the "new" http_response_code
function. I believe PHP 4.3 is more than enough backwards compatibility, but you never know...
// For 4.3.0 <= PHP <= 5.4.0
if (!function_exists('http_response_code'))
{
function http_response_code($newcode = NULL)
{
static $code = 200;
if($newcode !== NULL)
{
header('X-PHP-Response-Code: '.$newcode, true, $newcode);
if(!headers_sent())
$code = $newcode;
}
return $code;
}
}
Why use armeabi-v7a code over armeabi code?
EABI = Embedded Application Binary Interface. It is such specifications to which an executable must conform in order to execute in a specific execution environment. It also specifies various aspects of compilation and linkage required for interoperation between toolchains used for the ARM Architecture. In this context when we speak about armeabi we speak about ARM architecture and GNU/Linux OS. Android follows the little-endian ARM GNU/Linux ABI.
armeabi application will run on ARMv5 (e.g. ARM9) and ARMv6 (e.g. ARM11). You may use Floating Point hardware if you build your application using proper GCC options like -mfpu=vfpv3 -mfloat-abi=softfp which tells compiler to generate floating point instructions for VFP hardware and enables the soft-float calling conventions. armeabi doesn't support hard-float calling conventions (it means FP registers are not used to contain arguments for a function), but FP operations in HW are still supported.
armeabi-v7a application will run on Cortex A# devices like Cortex A8, A9, and A15. It supports multi-core processors and it supports -mfloat-abi=hard. So, if you build your application using -mfloat-abi=hard, many of your function calls will be faster.
what does -zxvf mean in tar -zxvf <filename>?
Instead of wading through the description of all the options, you can jump to 3.4.3 Short Options Cross Reference
under the info tar
command.
x
means --extract
. v
means --verbose
. f
means --file
. z
means --gzip
. You can combine one-letter arguments together, and f
takes an argument, the filename. There is something you have to watch out for:
Short options' letters may be clumped together, but you are not
required to do this (as compared to old options; see below). When
short options are clumped as a set, use one (single) dash for them
all, e.g., ''tar' -cvf'. Only the last option in such a set is
allowed to have an argument(1).
This old way of writing 'tar' options can surprise even experienced
users. For example, the two commands:
tar cfz archive.tar.gz file
tar -cfz archive.tar.gz file
are quite different. The first example uses 'archive.tar.gz' as the
value for option 'f' and recognizes the option 'z'. The second
example, however, uses 'z' as the value for option 'f' -- probably not
what was intended.
How to get my project path?
You can use
string wanted_path = Path.GetDirectoryName(Path.GetDirectoryName(System.IO.Directory.GetCurrentDirectory()));
python: [Errno 10054] An existing connection was forcibly closed by the remote host
This can be caused by the two sides of the connection disagreeing over whether the connection timed out or not during a keepalive. (Your code tries to reused the connection just as the server is closing it because it has been idle for too long.) You should basically just retry the operation over a new connection. (I'm surprised your library doesn't do this automatically.)
Unpacking a list / tuple of pairs into two lists / tuples
>>> source_list = ('1','a'),('2','b'),('3','c'),('4','d')
>>> list1, list2 = zip(*source_list)
>>> list1
('1', '2', '3', '4')
>>> list2
('a', 'b', 'c', 'd')
Edit: Note that zip(*iterable)
is its own inverse:
>>> list(source_list) == zip(*zip(*source_list))
True
When unpacking into two lists, this becomes:
>>> list1, list2 = zip(*source_list)
>>> list(source_list) == zip(list1, list2)
True
Addition suggested by rocksportrocker.
What is the difference between a schema and a table and a database?
A relation schema is the logical definition of a table - it defines what the name of the table is, and what the name and type of each column is. It's like a plan or a blueprint. A database schema is the collection of relation schemas for a whole database.
A table is a structure with a bunch of rows (aka "tuples"), each of which has the attributes defined by the schema. Tables might also have indexes on them to aid in looking up values on certain columns.
A database is, formally, any collection of data. In this context, the database would be a collection of tables. A DBMS (Database Management System) is the software (like MySQL, SQL Server, Oracle, etc) that manages and runs a database.
What is the difference between C# and .NET?
In addition to what Andrew said, it is worth noting that:
- .NET isn't just a library, but also a runtime for executing applications.
- The knowledge of C# implies some knowledge of .NET (because the C# object model corresponds to the .NET object model and you can do something interesting in C# just by using .NET libraries). The opposite isn't necessarily true as you can use other languages to write .NET applications.
The distinction between a language, a runtime, and a library is more strict in .NET/C# than for example in C++, where the language specification also includes some basic library functions. The C# specification says only a very little about the environment (basically, that it should contain some types such as int
, but that's more or less all).
What's the difference setting Embed Interop Types true and false in Visual Studio?
This option was introduced in order to remove the need to deploy very large PIAs (Primary Interop Assemblies) for interop.
It simply embeds the managed bridging code used that allows you to talk to unmanaged assemblies, but instead of embedding it all it only creates the stuff you actually use in code.
Read more in Scott Hanselman's blog post about it and other VS improvements here.
As for whether it is advised or not, I'm not sure as I don't need to use this feature. A quick web search yields a few leads:
The only risk of turning them all to false is more deployment concerns with PIA files and a larger deployment if some of those files are large.
Adjust UILabel height depending on the text
My code:
UILabel *label = [[UILabel alloc] init];
label.numberOfLines = 0;
label.lineBreakMode = NSLineBreakByWordWrapping;
label.text = text;
label.textAlignment = NSTextAlignmentCenter;
label.font = [UIFont fontWithName:_bodyTextFontFamily size:_bodyFontSize];
CGSize size = [label sizeThatFits:CGSizeMake(width, MAXFLOAT)];
float height = size.height;
label.frame = CGRectMake(x, y, width, height);
Javascript querySelector vs. getElementById
The functions getElementById
and getElementsByClassName
are very specific, while querySelector
and querySelectorAll
are more elaborate. My guess is that they will actually have a worse performance.
Also, you need to check for the support of each function in the browsers you are targetting. The newer it is, the higher probability of lack of support or the function being "buggy".
How to format a duration in java? (e.g format H:MM:SS)
This answer only uses Duration
methods and works with Java 8 :
public static String format(Duration d) {
long days = d.toDays();
d = d.minusDays(days);
long hours = d.toHours();
d = d.minusHours(hours);
long minutes = d.toMinutes();
d = d.minusMinutes(minutes);
long seconds = d.getSeconds() ;
return
(days == 0?"":days+" jours,")+
(hours == 0?"":hours+" heures,")+
(minutes == 0?"":minutes+" minutes,")+
(seconds == 0?"":seconds+" secondes,");
}
Call one constructor from another
Error handling and making your code reusable is key. I added string to int validation and it is possible to add other types if needed. Solving this problem with a more reusable solution could be this:
public class Sample
{
public Sample(object inputToInt)
{
_intField = objectToInt(inputToInt);
}
public int IntProperty => _intField;
private readonly int _intField;
}
public static int objectToInt(object inputToInt)
{
switch (inputToInt)
{
case int inputInt:
return inputInt;
break;
case string inputString:
if (!int.TryParse(inputString, out int parsedInt))
{
throw new InvalidParameterException($"The input {inputString} could not be parsed to int");
}
return parsedInt;
default:
throw new InvalidParameterException($"Constructor do not support {inputToInt.GetType().Name}");
break;
}
}
Adding elements to a collection during iteration
Even though we cannot add items to the same list during iteration, we can use Java 8's flatMap, to add new elements to a stream. This can be done on a condition. After this the added item can be processed.
Here is a Java example which shows how to add to the ongoing stream an object depending on a condition which is then processed with a condition:
List<Integer> intList = new ArrayList<>();
intList.add(1);
intList.add(2);
intList.add(3);
intList = intList.stream().flatMap(i -> {
if (i == 2) return Stream.of(i, i * 10); // condition for adding the extra items
return Stream.of(i);
}).map(i -> i + 1)
.collect(Collectors.toList());
System.out.println(intList);
The output of the toy example is:
[2, 3, 21, 4]
Create a .tar.bz2 file Linux
You are not indicating what to include in the archive.
Go one level outside your folder and try:
sudo tar -cvjSf folder.tar.bz2 folder
Or from the same folder try
sudo tar -cvjSf folder.tar.bz2 *
Cheers!
Sending event when AngularJS finished loading
If you don't use ngRoute module, i.e. you don't have $viewContentLoaded event.
You can use another directive method:
angular.module('someModule')
.directive('someDirective', someDirective);
someDirective.$inject = ['$rootScope', '$timeout']; //Inject services
function someDirective($rootScope, $timeout){
return {
restrict: "A",
priority: Number.MIN_SAFE_INTEGER, //Lowest priority
link : function(scope, element, attr){
$timeout(
function(){
$rootScope.$emit("Some:event");
}
);
}
};
}
Accordingly to trusktr's answer it has lowest priority. Plus $timeout will cause Angular to run through an entire event loop before callback execution.
$rootScope used, because it allow to place directive in any scope of the application and notify only necessary listeners.
$rootScope.$emit will fire an event for all $rootScope.$on listeners only. The interesting part is that $rootScope.$broadcast will notify all $rootScope.$on as well as $scope.$on listeners
Source
How to open link in new tab on html?
If you would like to make the command once for your entire site, instead of having to do it after every link. Try this place
within the Head of your web site and bingo.
<head>
<title>your text</title>
<base target="_blank" rel="noopener noreferrer">
</head>
hope this helps
Difference between HttpModule and HttpClientModule
Don't want to be repetitive, but just to summarize in other way (features added in new HttpClient):
- Automatic conversion from JSON to an object
- Response type definition
- Event firing
- Simplified syntax for headers
- Interceptors
I wrote an article, where I covered the difference between old "http" and new "HttpClient". The goal was to explain it in the easiest way possible.
Simply about new HttpClient in Angular
How do I record audio on iPhone with AVAudioRecorder?
I've been trying to get this code to work for the last 2 hours and though it showed no error on the simulator, there was one on the device.
Turns out, at least in my case that the error came from directory used (bundle) :
NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/recordTest.caf", [[NSBundle mainBundle] resourcePath]]];
It was not writable or something like this... There was no error except the fact that prepareToRecord failed...
I therefore replaced it by :
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *recDir = [paths objectAtIndex:0];
NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/recordTest.caf", recDir]]
It now Works like a Charm.
Hope this helps others.
How to insert data using wpdb
Use $wpdb->insert()
.
$wpdb->insert('wp_submitted_form', array(
'name' => 'Kumkum',
'email' => '[email protected]',
'phone' => '3456734567', // ... and so on
));
Addition from @mastrianni:
$wpdb->insert
sanitizes your data for you, unlike $wpdb->query
which requires you to sanitize your query with $wpdb->prepare
. The difference between the two is $wpdb->query
allows you to write your own SQL statement, where $wpdb->insert
accepts an array and takes care of sanitizing/sql for you.
JOptionPane - input dialog box program
After that you have to parse the results.
Suppose results are in integers, then
int testint1 = Integer.parse(test1);
Similarly others should be parsed.
Now the results should be checked for two higher marks in them, by using if statement
After that take out the average.
how to run command "mysqladmin flush-hosts" on Amazon RDS database Server instance?
You can flush hosts local MySQL using following command:
mysqladmin -u [username] -p flush-hosts
**** [MySQL password]
or
mysqladmin flush-hosts -u [username] -p
**** [MySQL password]
Though Amazon RDS database server is on network then use the following command as like as flush network MySQL server:
mysqladmin -h <RDS ENDPOINT URL> -P <PORT> -u <USER> -p flush-hosts
mysqladmin -h [YOUR RDS END POINT URL] -P 3306 -u [DB USER] -p flush-hosts
In additional suggestion
you can permanently solve blocked of many connections error problem by editing
my.ini file[Mysql configuration file]
change variables max_connections = 10000;
or
login into MySQL using command line -
mysql -u [username] -p
**** [MySQL password]
put the below command into MySQL window
SET GLOBAL max_connect_errors=10000;
set global max_connections = 200;
check veritable using command-
show variables like "max_connections";
show variables like "max_connect_errors";
How can I print out just the index of a pandas dataframe?
You can access the index attribute of a df using df.index[i]
>> import pandas as pd
>> import numpy as np
>> df = pd.DataFrame({'a':np.arange(5), 'b':np.random.randn(5)})
a b
0 0 1.088998
1 1 -1.381735
2 2 0.035058
3 3 -2.273023
4 4 1.345342
>> df.index[1] ## Second index
>> df.index[-1] ## Last index
>> for i in xrange(len(df)):print df.index[i] ## Using loop
...
0
1
2
3
4
Java correct way convert/cast object to Double
new Double(object.toString());
But it seems weird to me that you're going from an Object to a Double. You should have a better idea what class of object you're starting with before attempting a conversion. You might have a bit of a code quality problem there.
Note that this is a conversion, not casting.
How to turn off word wrapping in HTML?
white-space: nowrap;
: Will never break text, will keep other defaults
white-space: pre;
: Will never break text, will keep multiple spaces after one another as multiple spaces, will break if explicitly written to break(pressing enter in html etc)
Truncate with condition
The short answer is no: MySQL does not allow you to add a WHERE
clause to the TRUNCATE
statement. Here's MySQL's documentation about the TRUNCATE
statement.
But the good news is that you can (somewhat) work around this limitation.
Simple, safe, clean but slow solution using DELETE
First of all, if the table is small enough, simply use the DELETE
statement (it had to be mentioned):
1. LOCK TABLE my_table WRITE;
2. DELETE FROM my_table WHERE my_date<DATE_SUB(NOW(), INTERVAL 1 MONTH);
3. UNLOCK TABLES;
The LOCK
and UNLOCK
statements are not compulsory, but they will speed things up and avoid potential deadlocks.
Unfortunately, this will be very slow if your table is large... and since you are considering using the TRUNCATE
statement, I suppose it's because your table is large.
So here's one way to solve your problem using the TRUNCATE
statement:
Simple, fast, but unsafe solution using TRUNCATE
1. CREATE TABLE my_table_backup AS
SELECT * FROM my_table WHERE my_date>=DATE_SUB(NOW(), INTERVAL 1 MONTH);
2. TRUNCATE my_table;
3. LOCK TABLE my_table WRITE, my_table_backup WRITE;
4. INSERT INTO my_table SELECT * FROM my_table_backup;
5. UNLOCK TABLES;
6. DROP TABLE my_table_backup;
Unfortunately, this solution is a bit unsafe if other processes are inserting records in the table at the same time:
- any record inserted between steps 1 and 2 will be lost
- the
TRUNCATE
statement resets the AUTO-INCREMENT
counter to zero. So any record inserted between steps 2 and 3 will have an ID that will be lower than older IDs and that might even conflict with IDs inserted at step 4 (note that the AUTO-INCREMENT
counter will be back to it's proper value after step 4).
Unfortunately, it is not possible to lock the table and truncate it. But we can (somehow) work around that limitation using RENAME
.
Half-simple, fast, safe but noisy solution using TRUNCATE
1. RENAME TABLE my_table TO my_table_work;
2. CREATE TABLE my_table_backup AS
SELECT * FROM my_table_work WHERE my_date>DATE_SUB(NOW(), INTERVAL 1 MONTH);
3. TRUNCATE my_table_work;
4. LOCK TABLE my_table_work WRITE, my_table_backup WRITE;
5. INSERT INTO my_table_work SELECT * FROM my_table_backup;
6. UNLOCK TABLES;
7. RENAME TABLE my_table_work TO my_table;
8. DROP TABLE my_table_backup;
This should be completely safe and quite fast. The only problem is that other processes will see table my_table
disappear for a few seconds. This might lead to errors being displayed in logs everywhere. So it's a safe solution, but it's "noisy".
Disclaimer: I am not a MySQL expert, so these solutions might actually be crappy. The only guarantee I can offer is that they work fine for me. If some expert can comment on these solutions, I would be grateful.
How to automatically update your docker containers, if base-images are updated
UPDATE: Use Dependabot - https://dependabot.com/docker/
BLUF: finding the right insertion point for monitoring changes to a container is the challenge. It would be great if DockerHub would solve this. (Repository Links have been mentioned but note when setting them up on DockerHub - "Trigger a build in this repository whenever the base image is updated on Docker Hub. Only works for non-official images.")
While trying to solve this myself I saw several recommendations for webhooks so I wanted to elaborate on a couple of solutions I have used.
Use microbadger.com to track changes in a container and use it's
notification webhook feature to trigger an action. I set this up
with zapier.com (but you can use any customizable webhook service)
to create a new issue in my github repository that uses Alpine as a
base image.
- Pros: You can review the changes reported by microbadger in github before taking action.
- Cons: Microbadger doesn't let you track a specific tag. Looks like it only tracks 'latest'.
Track the RSS feed for git commits to an upstream container. ex. https://github.com/gliderlabs/docker-alpine/commits/rootfs/library-3.8/x86_64. I used zapier.com to monitor this feed and to trigger an automatic build of my container in Travis-CI anytime something is committed. This is a little extreme but you can change the trigger to do other things like open an issue in your git repository for manual intervention.
- Pros: Closer to an automated pipline. The Travis-CI build just checks to see if your container has issues with whatever was committed to the base image repository. It's up to you if your CI service takes any further action.
- Cons: Tracking the commit feed isn't perfect. Lots of things get committed to the repository that don't affect the build of the base image. Doesn't take in to account any issues with frequency/number of commits and any API throttling.
Search a whole table in mySQL for a string
Try this code,
SELECT
*
FROM
`customers`
WHERE
(
CONVERT
(`customer_code` USING utf8mb4) LIKE '%Mary%'
OR
CONVERT(`customer_name` USING utf8mb4) LIKE '%Mary%'
OR
CONVERT(`email_id` USING utf8mb4) LIKE '%Mary%'
OR
CONVERT(`address1` USING utf8mb4) LIKE '%Mary%'
OR
CONVERT(`report_sorting` USING utf8mb4) LIKE '%Mary%'
)
This is help to solve your problem mysql version 5.7.21
How to read lines of a file in Ruby
I believe my answer covers your new concerns about handling any type of line endings since both "\r\n"
and "\r"
are converted to Linux standard "\n"
before parsing the lines.
To support the "\r"
EOL character along with the regular "\n"
, and "\r\n"
from Windows, here's what I would do:
line_num=0
text=File.open('xxx.txt').read
text.gsub!(/\r\n?/, "\n")
text.each_line do |line|
print "#{line_num += 1} #{line}"
end
Of course this could be a bad idea on very large files since it means loading the whole file into memory.
How to declare string constants in JavaScript?
Many browsers' implementations (and Node) have constants, used with const
.
const SOME_VALUE = "Your string";
This const
means that you can't reassign it to any other value.
Check the compatibility notes to see if your targeted browsers are supported.
Alternatively, you could also modify the first example, using defineProperty()
or its friends and make the writable
property false
. This will mean the variable's contents can not be changed, like a constant.
Difference between exit() and sys.exit() in Python
If I use exit()
in a code and run it in the shell, it shows a message asking whether I want to kill the program or not. It's really disturbing.
See here
But sys.exit()
is better in this case. It closes the program and doesn't create any dialogue box.
Prevent Default on Form Submit jQuery
This is an ancient question, but the accepted answer here doesn't really get to the root of the problem.
You can solve this two ways. First with jQuery:
$(document).ready( function() { // Wait until document is fully parsed
$("#cpa-form").on('submit', function(e){
e.preventDefault();
});
})
Or without jQuery:
// Gets a reference to the form element
var form = document.getElementById('cpa-form');
// Adds a listener for the "submit" event.
form.addEventListener('submit', function(e) {
e.preventDefault();
});
You don't need to use return false
to solve this problem.
Debugging Spring configuration
Yes, Spring framework logging is very detailed, You did not mention in your post, if you are already using a logging framework or not. If you are using log4j then just add spring appenders to the log4j config (i.e to log4j.xml or log4j.properties), If you are using log4j xml config you can do some thing like this
<category name="org.springframework.beans">
<priority value="debug" />
</category>
or
<category name="org.springframework">
<priority value="debug" />
</category>
I would advise you to test this problem in isolation using JUnit test, You can do this by using spring testing module in conjunction with Junit. If you use spring test module it will do the bulk of the work for you it loads context file based on your context config and starts container so you can just focus on testing your business logic. I have a small example here
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath:springContext.xml"})
@Transactional
public class SpringDAOTest
{
@Autowired
private SpringDAO dao;
@Autowired
private ApplicationContext appContext;
@Test
public void checkConfig()
{
AnySpringBean bean = appContext.getBean(AnySpringBean.class);
Assert.assertNotNull(bean);
}
}
UPDATE
I am not advising you to change the way you load logging but try this in your dev environment, Add this snippet to your web.xml file
<context-param>
<param-name>log4jConfigLocation</param-name>
<param-value>/WEB-INF/log4j.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
</listener>
UPDATE log4j config file
I tested this on my local tomcat and it generated a lot of logging on application start up. I also want to make a correction: use debug not info as @Rayan Stewart mentioned.
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/" debug="false">
<appender name="STDOUT" class="org.apache.log4j.ConsoleAppender">
<param name="Threshold" value="debug" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern"
value="%d{HH:mm:ss} %p [%t]:%c{3}.%M()%L - %m%n" />
</layout>
</appender>
<appender name="springAppender" class="org.apache.log4j.RollingFileAppender">
<param name="file" value="C:/tomcatLogs/webApp/spring-details.log" />
<param name="append" value="true" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern"
value="%d{MM/dd/yyyy HH:mm:ss} [%t]:%c{5}.%M()%L %m%n" />
</layout>
</appender>
<category name="org.springframework">
<priority value="debug" />
</category>
<category name="org.springframework.beans">
<priority value="debug" />
</category>
<category name="org.springframework.security">
<priority value="debug" />
</category>
<category
name="org.springframework.beans.CachedIntrospectionResults">
<priority value="debug" />
</category>
<category name="org.springframework.jdbc.core">
<priority value="debug" />
</category>
<category name="org.springframework.transaction.support.TransactionSynchronizationManager">
<priority value="debug" />
</category>
<root>
<priority value="debug" />
<appender-ref ref="springAppender" />
<!-- <appender-ref ref="STDOUT"/> -->
</root>
</log4j:configuration>
ReferenceError: describe is not defined NodeJs
OP asked about running from node
not from mocha
. This is a very common use case, see Using Mocha Programatically
This is what injected describe and it into my tests.
mocha.ui('bdd').run(function (failures) {
process.on('exit', function () {
process.exit(failures);
});
});
I tried tdd
like in the docs, but that didn't work, bdd worked though.
How to add comments into a Xaml file in WPF?
You cannot put comments inside UWP XAML tags. Your syntax is right.
TO DO:
<xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:System="clr-namespace:System;assembly=mscorlib"/>
<!-- Cool comment -->
NOT TO DO:
<xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
<!-- Cool comment -->
xmlns:System="clr-namespace:System;assembly=mscorlib"/>
Http post and get request in angular 6
You can do a post/get using a library which allows you to use HttpClient with strongly-typed callbacks.
The data and the error are available directly via these callbacks.
The library is called angular-extended-http-client.
angular-extended-http-client library on GitHub
angular-extended-http-client library on NPM
Very easy to use.
Traditional approach
In the traditional approach you return Observable<HttpResponse<
T>
> from Service API. This is tied to HttpResponse.
With this approach you have to use .subscribe(x => ...) in the rest of your code.
This creates a tight coupling between the http layer and the rest of your code.
Strongly-typed callback approach
You only deal with your Models in these strongly-typed callbacks.
Hence, The rest of your code only knows about your Models.
Sample usage
The strongly-typed callbacks are
Success:
- IObservable<
T
>
- IObservableHttpResponse
- IObservableHttpCustomResponse<
T
>
Failure:
- IObservableError<
TError
>
- IObservableHttpError
- IObservableHttpCustomError<
TError
>
Add package to your project and in your app module
import { HttpClientExtModule } from 'angular-extended-http-client';
and in the @NgModule imports
imports: [
.
.
.
HttpClientExtModule
],
Your Models
export class SearchModel {
code: string;
}
//Normal response returned by the API.
export class RacingResponse {
result: RacingItem[];
}
//Custom exception thrown by the API.
export class APIException {
className: string;
}
Your Service
In your Service, you just create params with these callback types.
Then, pass them on to the HttpClientExt's get method.
import { Injectable, Inject } from '@angular/core'
import { SearchModel, RacingResponse, APIException } from '../models/models'
import { HttpClientExt, IObservable, IObservableError, ResponseType, ErrorType } from 'angular-extended-http-client';
.
.
@Injectable()
export class RacingService {
//Inject HttpClientExt component.
constructor(private client: HttpClientExt, @Inject(APP_CONFIG) private config: AppConfig) {
}
//Declare params of type IObservable<T> and IObservableError<TError>.
//These are the success and failure callbacks.
//The success callback will return the response objects returned by the underlying HttpClient call.
//The failure callback will return the error objects returned by the underlying HttpClient call.
searchRaceInfo(model: SearchModel, success: IObservable<RacingResponse>, failure?: IObservableError<APIException>) {
let url = this.config.apiEndpoint;
this.client.post<SearchModel, RacingResponse>(url, model,
ResponseType.IObservable, success,
ErrorType.IObservableError, failure);
}
}
Your Component
In your Component, your Service is injected and the searchRaceInfo API called as shown below.
search() {
this.service.searchRaceInfo(this.searchModel, response => this.result = response.result,
error => this.errorMsg = error.className);
}
Both, response and error returned in the callbacks are strongly typed. Eg. response is type RacingResponse and error is APIException.
How to use ArrayList's get() method
ArrayList get(int index)
method is used for fetching an element from the list. We need to specify the index while calling get method and it returns the value present at the specified index.
public Element get(int index)
Example :
In below example we are getting few elements of an arraylist by using get method.
package beginnersbook.com;
import java.util.ArrayList;
public class GetMethodExample {
public static void main(String[] args) {
ArrayList<String> al = new ArrayList<String>();
al.add("pen");
al.add("pencil");
al.add("ink");
al.add("notebook");
al.add("book");
al.add("books");
al.add("paper");
al.add("white board");
System.out.println("First element of the ArrayList: "+al.get(0));
System.out.println("Third element of the ArrayList: "+al.get(2));
System.out.println("Sixth element of the ArrayList: "+al.get(5));
System.out.println("Fourth element of the ArrayList: "+al.get(3));
}
}
Output:
First element of the ArrayList: pen
Third element of the ArrayList: ink
Sixth element of the ArrayList: books
Fourth element of the ArrayList: notebook
assign headers based on existing row in dataframe in R
Try this:
colnames(DF) = DF[1, ] # the first row will be the header
DF = DF[-1, ] # removing the first row.
However, get a look if the data has been properly read. If you data.frame has numeric variables but the first row were characters, all the data has been read as character. To avoid this problem, it's better to save the data and read again with header=TRUE as you suggest. You can also get a look to this question: Reading a CSV file organized horizontally.
Why is jquery's .ajax() method not sending my session cookie?
Using
xhrFields: { withCredentials:true }
as part of my jQuery ajax call was only part of the solution. I also needed to have the headers returned in the OPTIONS response from my resource:
Access-Control-Allow-Origin : http://www.wombling.com
Access-Control-Allow-Credentials : true
It was important that only one allowed "origin" was in the response header of the OPTIONS call and not "*". I achieved this by reading the origin from the request and populating it back into the response - probably circumventing the original reason for the restriction, but in my use case the security is not paramount.
I thought it worth explicitly mentioning the requirement for only one origin, as the W3C standard does allow for a space separated list -but Chrome doesn't!
http://www.w3.org/TR/cors/#access-control-allow-origin-response-header
NB the "in practice" bit.
How to mark a build unstable in Jenkins when running shell scripts
You can just call "exit 1", and the build will fail at that point and not continue. I wound up making a passthrough make function to handle it for me, and call safemake instead of make for building:
function safemake {
make "$@"
if [ "$?" -ne 0 ]; then
echo "ERROR: BUILD FAILED"
exit 1
else
echo "BUILD SUCCEEDED"
fi
}
Splitting templated C++ classes into .hpp/.cpp files--is it possible?
It is not possible to write the implementation of a template class in a separate cpp file and compile. All the ways to do so, if anyone claims, are workarounds to mimic the usage of separate cpp file but practically if you intend to write a template class library and distribute it with header and lib files to hide the implementation, it is simply not possible.
To know why, let us look at the compilation process. The header files are never compiled. They are only preprocessed. The preprocessed code is then clubbed with the cpp file which is actually compiled. Now if the compiler has to generate the appropriate memory layout for the object it needs to know the data type of the template class.
Actually it must be understood that template class is not a class at all but a template for a class the declaration and definition of which is generated by the compiler at compile time after getting the information of the data type from the argument. As long as the memory layout cannot be created, the instructions for the method definition cannot be generated. Remember the first argument of the class method is the 'this' operator. All class methods are converted into individual methods with name mangling and the first parameter as the object which it operates on. The 'this' argument is which actually tells about size of the object which incase of template class is unavailable for the compiler unless the user instantiates the object with a valid type argument. In this case if you put the method definitions in a separate cpp file and try to compile it the object file itself will not be generated with the class information. The compilation will not fail, it would generate the object file but it won't generate any code for the template class in the object file. This is the reason why the linker is unable to find the symbols in the object files and the build fails.
Now what is the alternative to hide important implementation details? As we all know the main objective behind separating interface from implementation is hiding implementation details in binary form. This is where you must separate the data structures and algorithms. Your template classes must represent only data structures not the algorithms. This enables you to hide more valuable implementation details in separate non-templatized class libraries, the classes inside which would work on the template classes or just use them to hold data. The template class would actually contain less code to assign, get and set data. Rest of the work would be done by the algorithm classes.
I hope this discussion would be helpful.
.Contains() on a list of custom class objects
By default reference types have reference equality (i.e. two instances are only equal if they are the same object).
You need to override Object.Equals
(and Object.GetHashCode
to match) to implement your own equality. (And it is then good practice to implement an equality, ==
, operator.)
install cx_oracle for python
If you are trying to install in MAC , just unzip the Oracle client which you downloaded and place it into the folder where you written python scripts.
it will start working.
There is too much problem of setting up environmental variables.
It worked for me.
Hope this helps.
Thanks
make a header full screen (width) css
Remove the max-width
from the body
, and put it to the #container
.
So, instead of:
body {
max-width:1250px;
}
You should have:
#container {
max-width:1250px;
}
How do I delete an entity from symfony2
From what I understand, you struggle with what to put into your template.
I'll show an example:
<ul>
{% for guest in guests %}
<li>{{ guest.name }} <a href="{{ path('your_delete_route_name',{'id': guest.id}) }}">[[DELETE]]</a></li>
{% endfor %}
</ul>
Now what happens is it iterates over every object within guests (you'll have to rename this if your object collection is named otherwise!), shows the name and places the correct link. The route name might be different.
Write a file on iOS
Try making
NSString *appFile = [documentsDirectory stringByAppendingPathComponent:@"MyFile"];
as
NSString *appFile = [documentsDirectory stringByAppendingPathComponent:@"MyFile.txt"];
`React/RCTBridgeModule.h` file not found
After React Native 0.60 this issue is often caused by a linked library mixed with the new 'auto-linking' feature. This fixes it for me
Unlink old library using
$ react-native unlink react-native-fs
Refresh Pods integration entirely using
$ pod deintegrate && pod install
Now reload your workspace and do a clean build.
Adding Buttons To Google Sheets and Set value to Cells on clicking
It is possible to insert an image in a Google Spreadsheet using Google Apps Script. However, the image should have been hosted publicly over internet. At present, it is not possible to insert private images from Google Drive.
You can use following code to insert an image through script.
function insertImageOnSpreadsheet() {
var SPREADSHEET_URL = 'INSERT_SPREADSHEET_URL_HERE';
// Name of the specific sheet in the spreadsheet.
var SHEET_NAME = 'INSERT_SHEET_NAME_HERE';
var ss = SpreadsheetApp.openByUrl(SPREADSHEET_URL);
var sheet = ss.getSheetByName(SHEET_NAME);
var response = UrlFetchApp.fetch(
'https://developers.google.com/adwords/scripts/images/reports.png');
var binaryData = response.getContent();
// Insert the image in cell A1.
var blob = Utilities.newBlob(binaryData, 'image/png', 'MyImageName');
sheet.insertImage(blob, 1, 1);
}
Above example has been copied from this link. Check noogui's reply for details.
In case you need to insert image from Google Drive, please check this link for current updates.
Equivalent to AssemblyInfo in dotnet core/csproj
I do the following for my .NET Standard 2.0 projects.
Create a Directory.Build.props
file (e.g. in the root of your repo)
and move the properties to be shared from the .csproj
file to this file.
MSBuild will pick it up automatically and apply them to the autogenerated AssemblyInfo.cs
.
They also get applied to the nuget package when building one with dotnet pack
or via the UI in Visual Studio 2017.
See https://docs.microsoft.com/en-us/visualstudio/msbuild/customize-your-build
Example:
<Project>
<PropertyGroup>
<Company>Some company</Company>
<Copyright>Copyright © 2020</Copyright>
<AssemblyVersion>1.0.0.1</AssemblyVersion>
<FileVersion>1.0.0.1</FileVersion>
<Version>1.0.0.1</Version>
<!-- ... -->
</PropertyGroup>
</Project>
Circle-Rectangle collision detection (intersection)
worked for me (only work when angle of rectangle is 180)
function intersects(circle, rect) {
let left = rect.x + rect.width > circle.x - circle.radius;
let right = rect.x < circle.x + circle.radius;
let top = rect.y < circle.y + circle.radius;
let bottom = rect.y + rect.height > circle.y - circle.radius;
return left && right && bottom && top;
}
Reverse a string in Java
You can also try this:
public class StringReverse {
public static void main(String[] args) {
String str = "Dogs hates cats";
StringBuffer sb = new StringBuffer(str);
System.out.println(sb.reverse());
}
}
Multiline string literal in C#
The problem with using string literal I find is that it can make your code look a bit "weird" because in order to not get spaces in the string itself, it has to be completely left aligned:
var someString = @"The
quick
brown
fox...";
Yuck.
So the solution I like to use, which keeps everything nicely aligned with the rest of your code is:
var someString = String.Join(
Environment.NewLine,
"The",
"quick",
"brown",
"fox...");
And of course, if you just want to logically split up lines of an SQL statement like you are and don't actually need a new line, you can always just substitute Environment.NewLine
for " "
.
Default argument values in JavaScript functions
ES2015 onwards:
From ES6/ES2015, we have default parameters in the language specification. So we can just do something simple like,
function A(a, b = 4, c = 5) {
}
or combined with ES2015 destructuring,
function B({c} = {c: 2}, [d, e] = [3, 4]) {
}
For detailed explanation,
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/default_parameters
Default function parameters allow formal parameters to be initialized with default values if no value or undefined is passed.
Pre ES2015:
If you're going to handle values which are NOT Numbers, Strings, Boolean, NaN
, or null
you can simply use
(So, for Objects, Arrays and Functions that you plan never to send null
, you can use)
param || DEFAULT_VALUE
for example,
function X(a) {
a = a || function() {};
}
Though this looks simple and kinda works, this is restrictive and can be an anti-pattern because ||
operates on all falsy values (""
, null
, NaN
, false
, 0
) too - which makes this method impossible to assign a param the falsy value passed as the argument.
So, in order to handle only undefined
values explicitly, the preferred approach would be,
function C(a, b) {
a = typeof a === 'undefined' ? DEFAULT_VALUE_A : a;
b = typeof b === 'undefined' ? DEFAULT_VALUE_B : b;
}
Condition within JOIN or WHERE
Joins are quicker in my opinion when you have a larger table. It really isn't that much of a difference though especially if you are dealing with a rather smaller table. When I first learned about joins, i was told that conditions in joins are just like where clause conditions and that i could use them interchangeably if the where clause was specific about which table to do the condition on.
Get month name from Date
The easiest and simplest way I figured.
_x000D_
_x000D_
var now = new Date();_x000D_
//basically converting whole date to string = "Fri Apr 2020'_x000D_
//then splitting by ' ' a space = ['Fri' 'Apr' '2020']_x000D_
//then selecting second element of array = _x000D_
//['Fri' 'Apr' '2020'].[1]_x000D_
var currentMonth = now.toDateString().split(' ')[1];_x000D_
console.log(currentMonth);_x000D_
_x000D_
_x000D_
_x000D_
Wait for a process to finish
Use inotifywait to monitor some file that gets closed, when your process terminates. Example (on Linux):
yourproc >logfile.log & disown
inotifywait -q -e close logfile.log
-e specifies the event to wait for, -q means minimal output only on termination. In this case it will be:
logfile.log CLOSE_WRITE,CLOSE
A single wait command can be used to wait for multiple processes:
yourproc1 >logfile1.log & disown
yourproc2 >logfile2.log & disown
yourproc3 >logfile3.log & disown
inotifywait -q -e close logfile1.log logfile2.log logfile3.log
The output string of inotifywait will tell you, which process terminated. This only works with 'real' files, not with something in /proc/
How to fully clean bin and obj folders within Visual Studio?
This is how I do with a batch file to delete all BIN and OBJ folders recursively.
- Create an empty file and name it DeleteBinObjFolders.bat
- Copy-paste code the below code into the DeleteBinObjFolders.bat
- Move the DeleteBinObjFolders.bat file in the same folder with your solution (*.sln) file.
@echo off
@echo Deleting all BIN and OBJ folders...
for /d /r . %%d in (bin,obj) do @if exist "%%d" rd /s/q "%%d"
@echo BIN and OBJ folders successfully deleted :) Close the window.
pause > nul
Google Maps setCenter()
@phoenix24 answer actually helped me (whose own asnwer did not solve my problem btw). The correct arguments for setCenter is
map.setCenter({lat:LAT_VALUE, lng:LONG_VALUE});
Google Documentation
By the way if your variable are lat and lng the following code will work
map.setCenter({lat:lat, lng:lng});
This actually solved my very intricate problem so I thought I will post it here.
How to add a JAR in NetBeans
You want to add libraries to your project and in doing so you have two options as you yourself identified:
Compile-time libraries are libraries which is needed to compile your application. They are not included when your application is assembled (e.g., into a war-file). Libraries of this kind must be provided by the container running your project.
This is useful in situation when
you want to vary API and implementation, or when the library is supplied by the container (which is typically the case with javax.servlet which is required to compile but provided by the application server, e.g., Apache Tomcat).
Run-time libraries are libraries which is needed both for compilation and when running your project. This is probably what you want in most cases. If for instance your project is packaged into a war/ear, then these libraries will be included in the package.
As for the other alernatives you have either global libraries using Library Manager
or jdk libraries. The latter is simply your regular java libraries, while the former is just a way for your to store a set of libraries under a common name. For all your future projects, instead of manually assigning the libraries you can simply select to import them from your Library Manager
.
How to set custom header in Volley Request
The accepted answer with getParams() is for setting POST body data, but the question in the title asked how to set HTTP headers like User-Agent. As CommonsWare said, you override getHeaders(). Here's some sample code which sets the User-Agent to 'Nintendo Gameboy' and Accept-Language to 'fr':
public void requestWithSomeHttpHeaders() {
RequestQueue queue = Volley.newRequestQueue(this);
String url = "http://www.somewebsite.com";
StringRequest getRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>()
{
@Override
public void onResponse(String response) {
// response
Log.d("Response", response);
}
},
new Response.ErrorListener()
{
@Override
public void onErrorResponse(VolleyError error) {
// TODO Auto-generated method stub
Log.d("ERROR","error => "+error.toString());
}
}
) {
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("User-Agent", "Nintendo Gameboy");
params.put("Accept-Language", "fr");
return params;
}
};
queue.add(getRequest);
}
CodeIgniter htaccess and URL rewrite issues
This works for me
Move your .htaccess file to root folder (locate before application folder in my case)
RewriteEngine on
RewriteBase /yourProjectFolder
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule .* index.php/$0 [PT,L]
Mine config.php looks like this (application/config/config.php)
$config['base_url'] = "";
$config['index_page'] = "index.php";
$config['uri_protocol'] = "AUTO";
Let me know if its working for you guys too ! Cheers !
Spring Boot Configure and Use Two DataSources
My requirement was slightly different but used two data sources.
I have used two data sources for same JPA entities from same package. One for executing DDL at the server startup to create/update tables and another one is for DML at runtime.
The DDL connection should be closed after DDL statements are executed, to prevent further usage of super user previlleges anywhere in the code.
Properties
spring.datasource.url=jdbc:postgresql://Host:port
ddl.user=ddluser
ddl.password=ddlpassword
dml.user=dmluser
dml.password=dmlpassword
spring.datasource.driver-class-name=org.postgresql.Driver
Data source config classes
//1st Config class for DDL Data source
public class DatabaseDDLConfig {
@Bean
public LocalContainerEntityManagerFactoryBean ddlEntityManagerFactoryBean() {
LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
PersistenceProvider persistenceProvider = new
org.hibernate.jpa.HibernatePersistenceProvider();
entityManagerFactoryBean.setDataSource(ddlDataSource());
entityManagerFactoryBean.setPackagesToScan(new String[] {
"com.test.two.data.sources"});
HibernateJpaVendorAdapter vendorAdapter = new
HibernateJpaVendorAdapter();
entityManagerFactoryBean.setJpaVendorAdapter(vendorAdapter);
HashMap<String, Object> properties = new HashMap<>();
properties.put("hibernate.dialect",
"org.hibernate.dialect.PostgreSQLDialect");
properties.put("hibernate.physical_naming_strategy",
"org.springframework.boot.orm.jpa.hibernate.
SpringPhysicalNamingStrategy");
properties.put("hibernate.implicit_naming_strategy",
"org.springframework.boot.orm.jpa.hibernate.
SpringImplicitNamingStrategy");
properties.put("hibernate.hbm2ddl.auto", "update");
entityManagerFactoryBean.setJpaPropertyMap(properties);
entityManagerFactoryBean.setPersistenceUnitName("ddl.config");
entityManagerFactoryBean.setPersistenceProvider(persistenceProvider);
return entityManagerFactoryBean;
}
@Bean
public DataSource ddlDataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(env.getProperty("spring.datasource.driver-class-name"));
dataSource.setUrl(env.getProperty("spring.datasource.url"));
dataSource.setUsername(env.getProperty("ddl.user");
dataSource.setPassword(env.getProperty("ddl.password"));
return dataSource;
}
@Bean
public PlatformTransactionManager ddlTransactionManager() {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(ddlEntityManagerFactoryBean().getObject());
return transactionManager;
}
}
//2nd Config class for DML Data source
public class DatabaseDMLConfig {
@Bean
@Primary
public LocalContainerEntityManagerFactoryBean dmlEntityManagerFactoryBean() {
LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
PersistenceProvider persistenceProvider = new org.hibernate.jpa.HibernatePersistenceProvider();
entityManagerFactoryBean.setDataSource(dmlDataSource());
entityManagerFactoryBean.setPackagesToScan(new String[] { "com.test.two.data.sources" });
JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
entityManagerFactoryBean.setJpaVendorAdapter(vendorAdapter);
entityManagerFactoryBean.setJpaProperties(defineJpaProperties());
entityManagerFactoryBean.setPersistenceUnitName("dml.config");
entityManagerFactoryBean.setPersistenceProvider(persistenceProvider);
return entityManagerFactoryBean;
}
@Bean
@Primary
public DataSource dmlDataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(env.getProperty("spring.datasource.driver-class-name"));
dataSource.setUrl(envt.getProperty("spring.datasource.url"));
dataSource.setUsername("dml.user");
dataSource.setPassword("dml.password");
return dataSource;
}
@Bean
@Primary
public PlatformTransactionManager dmlTransactionManager() {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(dmlEntityManagerFactoryBean().getObject());
return transactionManager;
}
}
//Usage of DDL data sources in code.
public class DDLServiceAtStartup {
//Import persistence unit ddl.config for ddl purpose.
@PersistenceUnit(unitName = "ddl.config")
private EntityManagerFactory entityManagerFactory;
public void executeDDLQueries() throws ContentServiceSystemError {
try {
EntityManager entityManager = entityManagerFactory.createEntityManager();
entityManager.getTransaction().begin();
entityManager.createNativeQuery("query to create/update table").executeUpdate();
entityManager.flush();
entityManager.getTransaction().commit();
entityManager.close();
//Close the ddl data source to avoid from further use in code.
entityManagerFactory.close();
} catch(Exception ex) {}
}
//Usage of DML data source in code.
public class DDLServiceAtStartup {
@PersistenceUnit(unitName = "dml.config")
private EntityManagerFactory entityManagerFactory;
public void createRecord(User user) {
userDao.save(user);
}
}
How to $http Synchronous call with AngularJS
What about wrapping your call in a Promise.all()
method i.e.
Promise.all([$http.get(url).then(function(result){....}, function(error){....}])
According to MDN
Promise.all waits for all fulfillments (or the first rejection)
How to get parameter on Angular2 route in Angular way?
As of Angular 6+, this is handled slightly differently than in previous versions. As @BeetleJuice mentions in the answer above, paramMap
is new interface for getting route params, but the execution is a bit different in more recent versions of Angular. Assuming this is in a component:
private _entityId: number;
constructor(private _route: ActivatedRoute) {
// ...
}
ngOnInit() {
// For a static snapshot of the route...
this._entityId = this._route.snapshot.paramMap.get('id');
// For subscribing to the observable paramMap...
this._route.paramMap.pipe(
switchMap((params: ParamMap) => this._entityId = params.get('id'))
);
// Or as an alternative, with slightly different execution...
this._route.paramMap.subscribe((params: ParamMap) => {
this._entityId = params.get('id');
});
}
I prefer to use both because then on direct page load I can get the ID param, and also if navigating between related entities the subscription will update properly.
Source in Angular Docs
How to make google spreadsheet refresh itself every 1 minute?
If you're on the New Google Sheets, this is all you need to do, according to the docs:
change your recalculation setting to "On change and every minute" in your spreadsheet at File > Spreadsheet settings.
This will make the entire sheet update itself every minute, on the server side, regardless of whether you have the spreadsheet up in your browser or not.
If you're on the old Google Sheets, you'll want to add a cell with this formula to achieve the same functionality:
=GoogleClock()
EDIT to include old and new Google Sheets and change to =GoogleClock()
.
Python: instance has no attribute
Your class doesn't have a __init__()
, so by the time it's instantiated, the attribute atoms
is not present. You'd have to do C.setdata('something')
so C.atoms
becomes available.
>>> C = Residues()
>>> C.atoms.append('thing')
Traceback (most recent call last):
File "<pyshell#84>", line 1, in <module>
B.atoms.append('thing')
AttributeError: Residues instance has no attribute 'atoms'
>>> C.setdata('something')
>>> C.atoms.append('thing') # now it works
>>>
Unlike in languages like Java, where you know at compile time what attributes/member variables an object will have, in Python you can dynamically add attributes at runtime. This also implies instances of the same class can have different attributes.
To ensure you'll always have (unless you mess with it down the line, then it's your own fault) an atoms
list you could add a constructor:
def __init__(self):
self.atoms = []
Count specific character occurrences in a string
Here's a simple version.
text.count(function(x) x = "a")
The above would give you the number of a's in the string. If you wanted to ignore case:
text.count(function(x) Ucase(x) = "A")
Or if you just wanted to count letters:
text.count(function(x) Char.IsLetter(x) = True)
Give it a shot!
Batch program to to check if process exists
TASKLIST
doesn't set an exit code that you could check in a batch file. One workaround to checking the exit code could be parsing its standard output (which you are presently redirecting to NUL
). Apparently, if the process is found, TASKLIST
will display its details, which include the image name too. Therefore, you could just use FIND
or FINDSTR
to check if the TASKLIST
's output contains the name you have specified in the request. Both FIND
and FINDSTR
set a non-null exit code if the search was unsuccessful. So, this would work:
@echo off
tasklist /fi "imagename eq notepad.exe" | find /i "notepad.exe" > nul
if not errorlevel 1 (taskkill /f /im "notepad.exe") else (
specific commands to perform if the process was not found
)
exit
There's also an alternative that doesn't involve TASKLIST
at all. Unlike TASKLIST
, TASKKILL
does set an exit code. In particular, if it couldn't terminate a process because it simply didn't exist, it would set the exit code of 128. You could check for that code to perform your specific actions that you might need to perform in case the specified process didn't exist:
@echo off
taskkill /f /im "notepad.exe" > nul
if errorlevel 128 (
specific commands to perform if the process
was not terminated because it was not found
)
exit