TINYTEXT, TEXT, MEDIUMTEXT, and LONGTEXT maximum storage sizes
Rising to @Ankan-Zerob's challenge, this is my estimate of the maximum length which can be stored in each text type measured in words:
Type | Bytes | English words | Multi-byte words
-----------+---------------+---------------+-----------------
TINYTEXT | 255 | ±44 | ±23
TEXT | 65,535 | ±11,000 | ±5,900
MEDIUMTEXT | 16,777,215 | ±2,800,000 | ±1,500,000
LONGTEXT | 4,294,967,295 | ±740,000,000 | ±380,000,000
In English, 4.8 letters per word is probably a good average (eg norvig.com/mayzner.html), though word lengths will vary according to domain (e.g. spoken language vs. academic papers), so there's no point being too precise. English is mostly single-byte ASCII characters, with very occasional multi-byte characters, so close to one-byte-per-letter. An extra character has to be allowed for inter-word spaces, so I've rounded down from 5.8 bytes per word. Languages with lots of accents such as say Polish would store slightly fewer words, as would e.g. German with longer words.
Languages requiring multi-byte characters such as Greek, Arabic, Hebrew, Hindi, Thai, etc, etc typically require two bytes per character in UTF-8. Guessing wildly at 5 letters per word, I've rounded down from 11 bytes per word.
CJK scripts (Hanzi, Kanji, Hiragana, Katakana, etc) I know nothing of; I believe characters mostly require 3 bytes in UTF-8, and (with massive simplification) they might be considered to use around 2 characters per word, so they would be somewhere between the other two. (CJK scripts are likely to require less storage using UTF-16, depending).
This is of course ignoring storage overheads etc.
How do I add more members to my ENUM-type column in MySQL?
It's possible if you believe. Hehe. try this code.
public function add_new_enum($new_value)
{
$table="product";
$column="category";
$row = $this->db->query("SELECT COLUMN_TYPE FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = ? AND COLUMN_NAME = ?", array($table, $column))->row_array();
$old_category = array();
$new_category="";
foreach (explode(',', str_replace("'", '', substr($row['COLUMN_TYPE'], 5, (strlen($row['COLUMN_TYPE']) - 6)))) as $val)
{
//getting the old category first
$old_category[$val] = $val;
$new_category.="'".$old_category[$val]."'".",";
}
//after the end of foreach, add the $new_value to $new_category
$new_category.="'".$new_value."'";
//Then alter the table column with the new enum
$this->db->query("ALTER TABLE product CHANGE category category ENUM($new_category)");
}
Before adding new value
After adding new value
Is there a good reason I see VARCHAR(255) used so often (as opposed to another length)?
255 is used because it's the largest number of characters that can be counted with an 8-bit number. It maximizes the use of the 8-bit count, without frivolously requiring another whole byte to count the characters above 255.
When used this way, VarChar only uses the number of bytes + 1 to store your text, so you might as well set it to 255, unless you want a hard limit (like 50) on the number of characters in the field.
How to upload multiple files using PHP, jQuery and AJAX
Finally I have found the solution by using the following code:
$('body').on('click', '#upload', function(e){
e.preventDefault();
var formData = new FormData($(this).parents('form')[0]);
$.ajax({
url: 'upload.php',
type: 'POST',
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
return myXhr;
},
success: function (data) {
alert("Data Uploaded: "+data);
},
data: formData,
cache: false,
contentType: false,
processData: false
});
return false;
});
ModalPopupExtender OK Button click event not firing?
I was just searching for a solution for this :)
it appears that you can't have OkControlID assign to a control if you want to that control fires an event, just removing this property I got everything working again.
my code (working):
<asp:Panel ID="pnlResetPanelsView" CssClass="modalPopup" runat="server" Style="display:none;">
<h2>
Warning</h2>
<p>
Do you really want to reset the panels to the default view?</p>
<div style="text-align: center;">
<asp:Button ID="btnResetPanelsViewOK" Width="60" runat="server" Text="Yes"
CssClass="buttonSuperOfficeLayout" OnClick="btnResetPanelsViewOK_Click" />
<asp:Button ID="btnResetPanelsViewCancel" Width="60" runat="server" Text="No" CssClass="buttonSuperOfficeLayout" />
</div>
</asp:Panel>
<ajax:ModalPopupExtender ID="mpeResetPanelsView" runat="server" TargetControlID="btnResetView"
PopupControlID="pnlResetPanelsView" BackgroundCssClass="modalBackground" DropShadow="true"
CancelControlID="btnResetPanelsViewCancel" />
How do you run CMD.exe under the Local System Account?
Though I haven't personally tested, I have good reason to believe that the above stated AT COMMAND solution will work for XP, 2000 and Server 2003. Per my and Bryant's testing, we've identified that the same approach does not work with Vista or Windows Server 2008 -- most probably due to added security and the /interactive switch being deprecated.
However, I came across this article which demonstrates the use of PSTools from SysInternals (which was acquired by Microsoft in July, 2006.) I launched the command line via the following and suddenly I was running under the Local Admin Account like magic:
psexec -i -s cmd.exe
PSTools works well. It's a lightweight, well-documented set of tools which provides an appropriate solution to my problem.
Many thanks to those who offered help.
How to use WebRequest to POST some data and read response?
Here's what works for me. I'm sure it can be improved, so feel free to make suggestions or edit to make it better.
const string WEBSERVICE_URL = "http://localhost/projectname/ServiceName.svc/ServiceMethod";
//This string is untested, but I think it's ok.
string jsonData = "{ \"key1\" : \"value1\", \"key2\":\"value2\" }";
try
{
var webRequest = System.Net.WebRequest.Create(WEBSERVICE_URL);
if (webRequest != null)
{
webRequest.Method = "POST";
webRequest.Timeout = 20000;
webRequest.ContentType = "application/json";
using (System.IO.Stream s = webRequest.GetRequestStream())
{
using (System.IO.StreamWriter sw = new System.IO.StreamWriter(s))
sw.Write(jsonData);
}
using (System.IO.Stream s = webRequest.GetResponse().GetResponseStream())
{
using (System.IO.StreamReader sr = new System.IO.StreamReader(s))
{
var jsonResponse = sr.ReadToEnd();
System.Diagnostics.Debug.WriteLine(String.Format("Response: {0}", jsonResponse));
}
}
}
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.ToString());
}
Saving images in Python at a very high quality
If you are using Matplotlib and are trying to get good figures in a LaTeX document, save as an EPS. Specifically, try something like this after running the commands to plot the image:
plt.savefig('destination_path.eps', format='eps')
I have found that EPS files work best and the dpi
parameter is what really makes them look good in a document.
To specify the orientation of the figure before saving, simply call the following before the plt.savefig
call, but after creating the plot (assuming you have plotted using an axes with the name ax
):
ax.view_init(elev=elevation_angle, azim=azimuthal_angle)
Where elevation_angle
is a number (in degrees) specifying the polar angle (down from vertical z axis) and the azimuthal_angle
specifies the azimuthal angle (around the z axis).
I find that it is easiest to determine these values by first plotting the image and then rotating it and watching the current values of the angles appear towards the bottom of the window just below the actual plot. Keep in mind that the x, y, z, positions appear by default, but they are replaced with the two angles when you start to click+drag+rotate the image.
Exit codes in Python
From the documentation for sys.exit
:
The optional argument arg can be an
integer giving the exit status
(defaulting to zero), or another type
of object. If it is an integer, zero
is considered “successful termination”
and any nonzero value is considered
“abnormal termination” by shells and
the like. Most systems require it to
be in the range 0-127, and produce
undefined results otherwise. Some
systems have a convention for
assigning specific meanings to
specific exit codes, but these are
generally underdeveloped; Unix
programs generally use 2 for command
line syntax errors and 1 for all other
kind of errors.
One example where exit codes are used are in shell scripts. In Bash you can check the special variable $?
for the last exit status:
me@mini:~$ python -c ""; echo $?
0
me@mini:~$ python -c "import sys; sys.exit(0)"; echo $?
0
me@mini:~$ python -c "import sys; sys.exit(43)"; echo $?
43
Personally I try to use the exit codes I find in /usr/include/asm-generic/errno.h
(on a Linux system), but I don't know if this is the right thing to do.
ESRI : Failed to parse source map
The error in the Google DevTools are caused Google extensions.
- I clicked on my Google icon in the browser
- created a guest profile at the bottom of the popup window.
- I then pasted my localhost address and voila!!
No more errors in the console.
IE11 meta element Breaks SVG
I was having the same problem with 3 of 4 inline svgs I was using, and they only disappeared (in one case, partially) on IE11.
I had <meta http-equiv="x-ua-compatible" content="ie=edge">
on the page.
In the end, the problem was extra clipping paths on the svg file. I opened the files on Illustrator, removed the clipping path (normally at the bottom of the layers) and now they're all working.
Why are unnamed namespaces used and what are their benefits?
Having something in an anonymous namespace means it's local to this translation unit (.cpp file and all its includes) this means that if another symbol with the same name is defined elsewhere there will not be a violation of the One Definition Rule (ODR).
This is the same as the C way of having a static global variable or static function but it can be used for class definitions as well (and should be used rather than static
in C++).
All anonymous namespaces in the same file are treated as the same namespace and all anonymous namespaces in different files are distinct. An anonymous namespace is the equivalent of:
namespace __unique_compiler_generated_identifer0x42 {
...
}
using namespace __unique_compiler_generated_identifer0x42;
R - Concatenate two dataframes?
Here's a simple little function that will rbind two datasets together after auto-detecting what columns are missing from each and adding them with all NA
s.
For whatever reason this returns MUCH faster on larger datasets than using the merge
function.
fastmerge <- function(d1, d2) {
d1.names <- names(d1)
d2.names <- names(d2)
# columns in d1 but not in d2
d2.add <- setdiff(d1.names, d2.names)
# columns in d2 but not in d1
d1.add <- setdiff(d2.names, d1.names)
# add blank columns to d2
if(length(d2.add) > 0) {
for(i in 1:length(d2.add)) {
d2[d2.add[i]] <- NA
}
}
# add blank columns to d1
if(length(d1.add) > 0) {
for(i in 1:length(d1.add)) {
d1[d1.add[i]] <- NA
}
}
return(rbind(d1, d2))
}
Most recent previous business day in Python
This will give a generator of working days, of course without holidays, stop is datetime.datetime object. If you need holidays just make additional argument with list of holidays and check with 'IFology' ;-)
def workingdays(stop, start=datetime.date.today()):
while start != stop:
if start.weekday() < 5:
yield start
start += datetime.timedelta(1)
Later on you can count them like
workdays = workingdays(datetime.datetime(2015, 8, 8))
len(list(workdays))
How to split a data frame?
If you want to split a dataframe according to values of some variable, I'd suggest using daply()
from the plyr
package.
library(plyr)
x <- daply(df, .(splitting_variable), function(x)return(x))
Now, x
is an array of dataframes. To access one of the dataframes, you can index it with the name of the level of the splitting variable.
x$Level1
#or
x[["Level1"]]
I'd be sure that there aren't other more clever ways to deal with your data before splitting it up into many dataframes though.
Using switch statement with a range of value in each case?
I know this post is old but I believe this answer deserves some recognition. There is no need to avoid the switch statement. This can be done in java but through the switch statement, not the cases. It involves using ternary operators.
public class Solution {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int num = Integer.parseInt(sc.nextLine());
switch ((1 <= num && num <= 5 ) ? 0 :
(6 <= num && num <= 10) ? 1 : 2) {
case 0:
System.out.println("I'm between one and five inclusive.");
break;
case 1:
System.out.println("I'm between 6 and 10 inclusive.");
break;
case 2:
System.out.println("I'm not between one and five or 6 and 10 inclusive.");
break;
}
}
}
Pass a local file in to URL in Java
I tried it with Java on Linux. The following possibilities are OK:
file:///home/userId/aaaa.html
file:/home/userId/aaaa.html
file:aaaa.html (if current directory is /home/userId)
not working is:
file://aaaa.html
Using multiple .cpp files in c++ program?
You should have header files (.h) that contain the function's declaration, then a corresponding .cpp file that contains the definition. You then include the header file everywhere you need it. Note that the .cpp file that contains the definitions also needs to include (it's corresponding) header file.
// main.cpp
#include "second.h"
int main () {
secondFunction();
}
// second.h
void secondFunction();
// second.cpp
#include "second.h"
void secondFunction() {
// do stuff
}
overlay two images in android to set an imageview
Its a bit late answer, but it covers merging images from urls using Picasso
MergeImageView
import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Build;
import android.util.AttributeSet;
import android.util.SparseArray;
import android.widget.ImageView;
import com.squareup.picasso.Picasso;
import java.io.IOException;
import java.util.List;
public class MergeImageView extends ImageView {
private SparseArray<Bitmap> bitmaps = new SparseArray<>();
private Picasso picasso;
private final int DEFAULT_IMAGE_SIZE = 50;
private int MIN_IMAGE_SIZE = DEFAULT_IMAGE_SIZE;
private int MAX_WIDTH = DEFAULT_IMAGE_SIZE * 2, MAX_HEIGHT = DEFAULT_IMAGE_SIZE * 2;
private String picassoRequestTag = null;
public MergeImageView(Context context) {
super(context);
}
public MergeImageView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public MergeImageView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public MergeImageView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}
@Override
public boolean isInEditMode() {
return true;
}
public void clearResources() {
if (bitmaps != null) {
for (int i = 0; i < bitmaps.size(); i++)
bitmaps.get(i).recycle();
bitmaps.clear();
}
// cancel picasso requests
if (picasso != null && AppUtils.ifNotNullEmpty(picassoRequestTag))
picasso.cancelTag(picassoRequestTag);
picasso = null;
bitmaps = null;
}
public void createMergedBitmap(Context context, List<String> imageUrls, String picassoTag) {
picasso = Picasso.with(context);
int count = imageUrls.size();
picassoRequestTag = picassoTag;
boolean isEven = count % 2 == 0;
// if url size are not even make MIN_IMAGE_SIZE even
MIN_IMAGE_SIZE = DEFAULT_IMAGE_SIZE + (isEven ? count / 2 : (count / 2) + 1);
// set MAX_WIDTH and MAX_HEIGHT to twice of MIN_IMAGE_SIZE
MAX_WIDTH = MAX_HEIGHT = MIN_IMAGE_SIZE * 2;
// in case of odd urls increase MAX_HEIGHT
if (!isEven) MAX_HEIGHT = MAX_WIDTH + MIN_IMAGE_SIZE;
// create default bitmap
Bitmap bitmap = Bitmap.createScaledBitmap(BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_wallpaper),
MIN_IMAGE_SIZE, MIN_IMAGE_SIZE, false);
// change default height (wrap_content) to MAX_HEIGHT
int height = Math.round(AppUtils.convertDpToPixel(MAX_HEIGHT, context));
setMinimumHeight(height * 2);
// start AsyncTask
for (int index = 0; index < count; index++) {
// put default bitmap as a place holder
bitmaps.put(index, bitmap);
new PicassoLoadImage(index, imageUrls.get(index)).execute();
// if you want parallel execution use
// new PicassoLoadImage(index, imageUrls.get(index)).(AsyncTask.THREAD_POOL_EXECUTOR);
}
}
private class PicassoLoadImage extends AsyncTask<String, Void, Bitmap> {
private int index = 0;
private String url;
PicassoLoadImage(int index, String url) {
this.index = index;
this.url = url;
}
@Override
protected Bitmap doInBackground(String... params) {
try {
// synchronous picasso call
return picasso.load(url).resize(MIN_IMAGE_SIZE, MIN_IMAGE_SIZE).tag(picassoRequestTag).get();
} catch (IOException e) {
}
return null;
}
@Override
protected void onPostExecute(Bitmap output) {
super.onPostExecute(output);
if (output != null)
bitmaps.put(index, output);
// create canvas
Bitmap.Config conf = Bitmap.Config.RGB_565;
Bitmap canvasBitmap = Bitmap.createBitmap(MAX_WIDTH, MAX_HEIGHT, conf);
Canvas canvas = new Canvas(canvasBitmap);
canvas.drawColor(Color.WHITE);
// if height and width are equal we have even images
boolean isEven = MAX_HEIGHT == MAX_WIDTH;
int imageSize = bitmaps.size();
int count = imageSize;
// we have odd images
if (!isEven) count = imageSize - 1;
for (int i = 0; i < count; i++) {
Bitmap bitmap = bitmaps.get(i);
canvas.drawBitmap(bitmap, bitmap.getWidth() * (i % 2), bitmap.getHeight() * (i / 2), null);
}
// if images are not even set last image width to MAX_WIDTH
if (!isEven) {
Bitmap scaledBitmap = Bitmap.createScaledBitmap(bitmaps.get(count), MAX_WIDTH, MIN_IMAGE_SIZE, false);
canvas.drawBitmap(scaledBitmap, scaledBitmap.getWidth() * (count % 2), scaledBitmap.getHeight() * (count / 2), null);
}
// set bitmap
setImageBitmap(canvasBitmap);
}
}
}
xml
<com.example.MergeImageView
android:id="@+id/iv_thumb"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
Example
List<String> urls = new ArrayList<>();
String picassoTag = null;
// add your urls
((MergeImageView)findViewById(R.id.iv_thumb)).
createMergedBitmap(MainActivity.this, urls,picassoTag);
Concatenate text files with Windows command line, dropping leading lines
I would put this in a comment to ghostdog74, except my rep is too low, so here goes.
more +2 file2.txt > temp
This code will actually ignore rows 1 and 2 of the file. OP wants to keep all rows from the first file (to maintain the header row), and then exclude the first row (presumably the same header row) on the second file, so to exclude only the header row OP should use more +1
.
type temp file1.txt > out.txt
It is unclear what order results from this code. Is temp
appended to file1.txt
(as desired), or is file1.txt
appended to temp
(undesired as the header row would be buried in the middle of the resulting file).
In addition, these operations take a REALLY LONG TIME with large files (e.g. 300MB)
Close application and launch home screen on Android
You are wrong. There is one way to kill an application. In a class with super class Application, we use some field, for example, killApp
. When we start the splash screen (first activity) in onResume()
, we set a parameter for false for field killApp
. In every activity which we have when onResume()
is called in the end, we call something like that:
if(AppClass.killApp())
finish();
Every activity which is getting to the screen have to call onResume()
. When it is called, we have to check if our field killApp
is true. If it is true, current activities call finish()
. To invoke the full action, we use the next construction. For example, in the action for a button:
AppClass.setkillApplication(true);
finish();
return;
Changing width property of a :before css selector using JQuery
Pseudo elements are part of the shadow DOM and can not be modified (but can have their values queried).
However, sometimes you can get around that by using classes, for example.
jQuery
$('#element').addClass('some-class');
CSS
.some-class:before {
/* change your properties here */
}
This may not be suitable for your query, but it does demonstrate you can achieve this pattern sometimes.
To get a pseudo element's value, try some code like...
var pseudoElementContent = window.getComputedStyle($('#element')[0], ':before')
.getPropertyValue('content')
How do I convert a IPython Notebook into a Python file via commandline?
Jupytext is nice to have in your toolchain for such conversions. It allows not only conversion from a notebook to a script, but you can go back again from the script to notebook as well. And even have that notebook produced in executed form.
jupytext --to py notebook.ipynb # convert notebook.ipynb to a .py file
jupytext --to notebook notebook.py # convert notebook.py to an .ipynb file with no outputs
jupytext --to notebook --execute notebook.py # convert notebook.py to an .ipynb file and run it
A process crashed in windows .. Crash dump location
a core dump is usually only made when the Windows kernel crashes (aka blue screen). A servicecrash will most of the times only leave some logging behind (in the event viewer probably).
If it is the bluescreen crash dump you are looking for, look in C:\Windows\Minidump or C:\windows\MEMORY.DMP
PL/pgSQL checking if a row exists
Simpler, shorter, faster: EXISTS
.
IF EXISTS (SELECT 1 FROM people p WHERE p.person_id = my_person_id) THEN
-- do something
END IF;
The query planner can stop at the first row found - as opposed to count()
, which will scan all matching rows regardless. Makes a difference with big tables. Hardly matters with a condition on a unique column - only one row qualifies anyway (and there is an index to look it up quickly).
Improved with input from @a_horse_with_no_name in the comments below.
You could even use an empty SELECT
list:
IF EXISTS (SELECT FROM people p WHERE p.person_id = my_person_id) THEN ...
Since the SELECT
list is not relevant to the outcome of EXISTS
. Only the existence of at least one qualifying row matters.
AngularJS does not send hidden field value
I had facing the same problem,
I really need to send a key from my jsp to java script,
It spend around 4h or more of my day to solve it.
I include this tag on my JavaScript/JSP:
_x000D_
_x000D_
$scope.sucessMessage = function (){ _x000D_
var message = ($scope.messages.sucess).format($scope.portfolio.name,$scope.portfolio.id);_x000D_
$scope.inforMessage = message;_x000D_
alert(message); _x000D_
}_x000D_
_x000D_
_x000D_
String.prototype.format = function() {_x000D_
var formatted = this;_x000D_
for( var arg in arguments ) {_x000D_
formatted = formatted.replace("{" + arg + "}", arguments[arg]);_x000D_
}_x000D_
return formatted;_x000D_
};
_x000D_
<!-- Messages definition -->_x000D_
<input type="hidden" name="sucess" ng-init="messages.sucess='<fmt:message key='portfolio.create.sucessMessage' />'" >_x000D_
_x000D_
<!-- Message showed affter insert -->_x000D_
<div class="alert alert-info" ng-show="(inforMessage.length > 0)">_x000D_
{{inforMessage}}_x000D_
</div>_x000D_
_x000D_
<!-- properties_x000D_
portfolio.create.sucessMessage=Portf\u00f3lio {0} criado com sucesso! ID={1}. -->
_x000D_
_x000D_
_x000D_
The result was:
Portfólio 1 criado com sucesso! ID=3.
Best Regards
Open a new tab in the background?
THX for this question! Works good for me on all popular browsers:
function openNewBackgroundTab(){
var a = document.createElement("a");
a.href = window.location.pathname;
var evt = document.createEvent("MouseEvents");
//the tenth parameter of initMouseEvent sets ctrl key
evt.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0,
true, false, false, false, 0, null);
a.dispatchEvent(evt);
}
var is_chrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1;
if(!is_chrome)
{
var url = window.location.pathname;
var win = window.open(url, '_blank');
} else {
openNewBackgroundTab();
}
AngularJS ng-style with a conditional expression
simple example:
<div ng-style="isTrue && {'background-color':'green'} || {'background-color': 'blue'}" style="width:200px;height:100px;border:1px solid gray;"></div>
{'background-color':'green'} RETURN true
OR the same result:
<div ng-style="isTrue && {'background-color':'green'}" style="width:200px;height:100px;border:1px solid gray;background-color: blue"></div>
other conditional possibility:
<div ng-style="count === 0 && {'background-color':'green'} || count === 1 && {'background-color':'yellow'}" style="width:200px;height:100px;border:1px solid gray;background-color: blue"></div>
How to add Certificate Authority file in CentOS 7
Maybe late to the party but in my case it was RHEL 6.8:
Copy certificate.crt
issued by hosting to:
/etc/pki/ca-trust/source/anchors/
Then:
update-ca-trust force-enable (ignore not found warnings)
update-ca-trust extract
Hope it helps
console.log showing contents of array object
It's simple to print an object to console in Javascript. Just use the following syntax:
console.log( object );
or
console.log('object: %O', object );
A relatively unknown method is following which prints an object or array to the console as table:
console.table( object );
I think it is important to say that this kind of logging statement only works inside a browser environment. I used this with Google Chrome. You can watch the output of your console.log calls inside the Developer Console: Open it by right click on any element in the webpage and select 'Inspect'. Select tab 'Console'.
How to detect responsive breakpoints of Twitter Bootstrap 3 using JavaScript?
Bootstrap's CSS for the .container
class looks like that:
.container {
padding-right: 15px;
padding-left: 15px;
margin-right: auto;
margin-left: auto;
}
@media (min-width: 768px) {
.container {
width: 750px;
}
}
@media (min-width: 992px) {
.container {
width: 970px;
}
}
@media (min-width: 1200px) {
.container {
width: 1170px;
}
}
So this means we can safely rely on jQuery('.container').css('width')
to detect breakpoints without the drawbacks of relying on jQuery(window).width()
.
We can write a function like this:
function detectBreakpoint() {
// Let's ensure we have at least 1 container in our pages.
if (jQuery('.container').length == 0) {
jQuery('body').append('<div class="container"></div>');
}
var cssWidth = jQuery('.container').css('width');
if (cssWidth === '1170px') return 'lg';
else if (cssWidth === '970px') return 'md';
else if (cssWidth === '750px') return 'sm';
return 'xs';
}
And then test it like
jQuery(document).ready(function() {
jQuery(window).resize(function() {
jQuery('p').html('current breakpoint is: ' + detectBreakpoint());
});
detectBreakpoint();
});
Storing Form Data as a Session Variable
You can solve this problem using this code:
if(!empty($_GET['variable from which you get']))
{
$_SESSION['something']= $_GET['variable from which you get'];
}
So you get the variable from a GET form, you will store in the $_SESSION['whatever']
variable just once when $_GET['variable from which you get']
is set and if it is empty $_SESSION['something']
will store the old parameter
The object 'DF__*' is dependent on column '*' - Changing int to double
I'm adding this as a response to explain where the constraint comes from.
I tried to do it in the comments but it's hard to edit nicely there :-/
If you create (or alter) a table with a column that has default values it will create the constraint for you.
In your table for example it might be:
CREATE TABLE Movie (
...
rating INT NOT NULL default 100
)
It will create the constraint for default 100.
If you instead create it like so
CREATE TABLE Movie (
name VARCHAR(255) NOT NULL,
rating INT NOT NULL CONSTRAINT rating_default DEFAULT 100
);
Then you get a nicely named constraint that's easier to reference when you are altering said table.
ALTER TABLE Movie DROP CONSTRAINT rating_default;
ALTER TABLE Movie ALTER COLUMN rating DECIMAL(2) NOT NULL;
-- sets up a new default constraint with easy to remember name
ALTER TABLE Movie ADD CONSTRAINT rating_default DEFAULT ((1.0)) FOR rating;
You can combine those last 2 statements so you alter the column and name the constraint in one line (you have to if it's an existing table anyways)
How to get html to print return value of javascript function?
Most likely you're looking for something like
var targetElement = document.getElementById('idOfTargetElement');
targetElement.innerHTML = produceMessage();
provided that this is not something which happens on page load, in which case it should already be there from the start.
Change :hover CSS properties with JavaScript
I had this need once and created a small library for, which maintains the CSS documents
https://github.com/terotests/css
With that you can state
css().bind("TD:hover", {
"background" : "00ff00"
});
It uses the techniques mentioned above and also tries to take care of the cross-browser issues. If there for some reason exists an old browser like IE9 it will limit the number of STYLE tags, because the older IE browser had this strange limit for number of STYLE tags available on the page.
Also, it limits the traffic to the tags by updating tags only periodically. There is also a limited support for creating animation classes.
How do I enumerate through a JObject?
The answer did not work for me. I dont know how it got so many votes. Though it helped in pointing me in a direction.
This is the answer that worked for me:
foreach (var x in jobj)
{
var key = ((JProperty) (x)).Name;
var jvalue = ((JProperty)(x)).Value ;
}
How to insert a newline in front of a pattern?
You can also do this with awk, using -v
to provide the pattern:
awk -v patt="pattern" '$0 ~ patt {gsub(patt, "\n"patt)}1' file
This checks if a line contains a given pattern. If so, it appends a new line to the beginning of it.
See a basic example:
$ cat file
hello
this is some pattern and we are going ahead
bye!
$ awk -v patt="pattern" '$0 ~ patt {gsub(patt, "\n"patt)}1' file
hello
this is some
pattern and we are going ahead
bye!
Note it will affect to all patterns in a line:
$ cat file
this pattern is some pattern and we are going ahead
$ awk -v patt="pattern" '$0 ~ patt {gsub(patt, "\n"patt)}1' d
this
pattern is some
pattern and we are going ahead
Spring JDBC Template for calling Stored Procedures
There are a number of ways to call stored procedures in Spring.
If you use CallableStatementCreator
to declare parameters, you will be using Java's standard interface of CallableStatement
, i.e register out parameters and set them separately. Using SqlParameter
abstraction will make your code cleaner.
I recommend you looking at SimpleJdbcCall
. It may be used like this:
SimpleJdbcCall jdbcCall = new SimpleJdbcCall(jdbcTemplate)
.withSchemaName(schema)
.withCatalogName(package)
.withProcedureName(procedure)();
...
jdbcCall.addDeclaredParameter(new SqlParameter(paramName, OracleTypes.NUMBER));
...
jdbcCall.execute(callParams);
For simple procedures you may use jdbcTemplate
's update
method:
jdbcTemplate.update("call SOME_PROC (?, ?)", param1, param2);
How can I display a tooltip on an HTML "option" tag?
I just tried doing this on Chrome:
var $sel = $('#sel'); $sel.find('option').hover(function(){$sel.attr('title',$(this).attr('title'));console.log($(this).attr('title'))}, function(){$sel.attr('title','');});
However, the hover enter never fires... So you wouldn't be able to do this at all using the standard select. You could achieve this though through some non standard ways:
- You could fake a select box by using radio boxes that look like dropdowns. So for example, have a radio box absolute positioned and opacity set to 0 placed over the styled box that is pretending to be the option.
- Or you could use pure javascript and have a series of boxes and adding javascript onclick events to recreate the dropbox yourself - so you will update a hidden value with whichever box was clicked using javascript.
- Or use one of the non standard libraries already out there. (If there are any?)
How to concatenate two layers in keras?
Adding to the above-accepted answer so that it helps those who are using tensorflow 2.0
import tensorflow as tf
# some data
c1 = tf.constant([[1, 1, 1], [2, 2, 2]], dtype=tf.float32)
c2 = tf.constant([[2, 2, 2], [3, 3, 3]], dtype=tf.float32)
c3 = tf.constant([[3, 3, 3], [4, 4, 4]], dtype=tf.float32)
# bake layers x1, x2, x3
x1 = tf.keras.layers.Dense(10)(c1)
x2 = tf.keras.layers.Dense(10)(c2)
x3 = tf.keras.layers.Dense(10)(c3)
# merged layer y1
y1 = tf.keras.layers.Concatenate(axis=1)([x1, x2])
# merged layer y2
y2 = tf.keras.layers.Concatenate(axis=1)([y1, x3])
# print info
print("-"*30)
print("x1", x1.shape, "x2", x2.shape, "x3", x3.shape)
print("y1", y1.shape)
print("y2", y2.shape)
print("-"*30)
Result:
------------------------------
x1 (2, 10) x2 (2, 10) x3 (2, 10)
y1 (2, 20)
y2 (2, 30)
------------------------------
Fixing slow initial load for IIS
See this article for tips on how to help performance issues. This includes both performance issues related to starting up, under the "cold start" section. Most of this will matter no matter what type of server you are using, locally or in production.
https://blogs.msdn.microsoft.com/b/mcsuksoldev/2011/01/19/common-performance-issues-on-asp-net-web-sites/
If the application deserializes anything from XML (and that includes web services…) make sure SGEN is run against all binaries involved in deseriaization and place the resulting DLLs in the Global Assembly Cache (GAC). This precompiles all the serialization objects used by the assemblies SGEN was run against and caches them in the resulting DLL. This can give huge time savings on the first deserialization (loading) of config files from disk and initial calls to web services.
http://msdn.microsoft.com/en-us/library/bk3w6240(VS.80).aspx
If any IIS servers do not have outgoing access to the internet, turn off Certificate Revocation List (CRL) checking for Authenticode binaries by adding generatePublisherEvidence=”false” into machine.config. Otherwise every worker processes can hang for over 20 seconds during start-up while it times out trying to connect to the internet to obtain a CRL list.
http://blogs.msdn.com/amolravande/archive/2008/07/20/startup-performance-disable-the-generatepublisherevidence-property.aspx
http://msdn.microsoft.com/en-us/library/bb629393.aspx
Consider using NGEN on all assemblies. However without careful use this doesn’t give much of a performance gain. This is because the base load addresses of all the binaries that are loaded by each process must be carefully set at build time to not overlap. If the binaries have to be rebased when they are loaded because of address clashes, almost all the performance gains of using NGEN will be lost.
http://msdn.microsoft.com/en-us/magazine/cc163610.aspx
Get line number while using grep
Line numbers are printed with grep -n
:
grep -n pattern file.txt
To get only the line number (without the matching line), one may use cut
:
grep -n pattern file.txt | cut -d : -f 1
Lines not containing a pattern are printed with grep -v
:
grep -v pattern file.txt
Can I connect to SQL Server using Windows Authentication from Java EE webapp?
This actually works for me:
Per the README.SSO that comes with the jtdsd distribution:
In order for Single Sign On to work, jTDS must be able to load the native SPPI library ntlmauth.dll
. Place this DLL anywhere in the system path (defined by the PATH
system variable) and you're all set.
I placed it in my jre/bin folder
I configured a port dedicated the sql server instance (2302) to alleviate the need for an instance name - just something I do. lportal is my database name.
jdbc.default.url=jdbc:jtds:sqlserver://192.168.0.147:2302/lportal;useNTLMv2=true;domain=mydomain.local
Is there a way to pass jvm args via command line to maven?
I think MAVEN_OPTS
would be most appropriate for you. See here: http://maven.apache.org/configure.html
In Unix:
Add the MAVEN_OPTS
environment variable to specify JVM properties, e.g. export MAVEN_OPTS="-Xms256m -Xmx512m"
. This environment variable can be used to supply extra options to Maven.
In Win, you need to set environment variable via the dialogue box
Add ... environment variable by opening up the system properties (WinKey + Pause
),... In the same dialog, add the MAVEN_OPTS
environment variable in the user variables to specify JVM properties, e.g. the value -Xms256m -Xmx512m
. This environment variable can be used to supply extra options to Maven.
Plotting histograms from grouped data in a pandas DataFrame
Your function is failing because the groupby dataframe you end up with has a hierarchical index and two columns (Letter and N) so when you do .hist()
it's trying to make a histogram of both columns hence the str error.
This is the default behavior of pandas plotting functions (one plot per column) so if you reshape your data frame so that each letter is a column you will get exactly what you want.
df.reset_index().pivot('index','Letter','N').hist()
The reset_index()
is just to shove the current index into a column called index
. Then pivot
will take your data frame, collect all of the values N
for each Letter
and make them a column. The resulting data frame as 400 rows (fills missing values with NaN
) and three columns (A, B, C
). hist()
will then produce one histogram per column and you get format the plots as needed.
Converting from signed char to unsigned char and back again?
There are two ways to interpret the input data; either -128 is the lowest value, and 127 is the highest (i.e. true signed data), or 0 is the lowest value, 127 is somewhere in the middle, and the next "higher" number is -128, with -1 being the "highest" value (that is, the most significant bit already got misinterpreted as a sign bit in a two's complement notation.
Assuming you mean the latter, the formally correct way is
signed char in = ...
unsigned char out = (in < 0)?(in + 256):in;
which at least gcc properly recognizes as a no-op.
BATCH file asks for file or folder
Well, for the task as asked by just me the perhaps best solution would be the following command according to the incomplete advice of Andy Morris:
xcopy "J:\My Name\FILES IN TRANSIT\JOHN20101126\Missing file\Shapes.atc" "C:\Documents and Settings\His name\Application Data\Autodesk\AutoCAD 2010\R18.0\enu\Support\" /Q /R /S /Y
This works for this simple file copying task because of
- specifying just the destination directory instead of destination file and
- ending destination directory with a backslash which is very important as otherwise XCOPY would even with
/I
prompt for file or directory on copying just a single file.
The other parameters not related to the question are:
/Q
... quiet
/Y
... yes (OS language independent) on overwrite existing file
/R
... overwrite also read-only, hidden and system file
/S
... from specified directory and all subdirectories.
Well, I don't know if /S
is really needed here because it is unclear if just J:\My Name\FILES IN TRANSIT\JOHN20101126\Missing file\Shapes.atc
should be copied or all Shapes.atc
found anywhere in directory tree of J:\My Name\FILES IN TRANSIT\JOHN20101126\Missing file
.
The explanation for the parameters can be read by opening a command prompt window and running from within this window xcopy /?
to get output the help for XCOPY.
But none of the provided solutions worked for a file copying task on which a single file should be copied into same directory as source file, but with a different file name because of current date and time is inserted in file name before file extension.
The source file can have hidden or system attribute set which excludes the usage of COPY command.
The batch file for creating the time stamped file should work also on Windows XP which excludes ROBOCOPY because by default not available on Windows XP.
The batch file should work with any file including non typical files like .gitconfig
or .htaccess
which are files without a file extension starting with a point to hide them on *nix systems. Windows command processor interprets such files as files with no file name and having just a file extension because of the rule that everything after last point is the extension of the file and everything before last point is the file name.
For a complete task description and the final, fully commented solution see the post Create a backup copy of files in UltraEdit forum.
Patrick's, Tirtha R's, Interociter Operator's and CharlesB's solutions do not work because using /Y
does not avoid the file or directory prompt if the destination file does not already exist.
Andy Morris' and grenix's solutions can't be used for the single file copying task as destination must be the name of destination file and not the name of destination directory. The destination directory is the same as the source directory, but name of destination file is different to name of source file.
DosMan's and Govert's solutions simply don't work for files starting with a point and not having a file extension.
For example the command
xcopy C:\Temp\.gitconfig C:\Temp\.gitconfig_2016-03-07_15-30-00* /C /H /K /Q /R /V /Y
results in following error message on execution:
English: Could not expand second file name so as to match first.
German: Zweiter Dateiname konnte nicht so erweitert werden, dass er zum ersten passt.
And finally Denis Ivin's solution has the restriction that the operating system language dependent character for an automatic answering of the file OR directory prompt must be known.
So I thought about methods to get F
for File on English Windows or D
for Datei on German Windows or ?
for ... on ... Windows automatically.
And it is indeed possible to determine the language dependent character for an automatic answering of the prompt.
A hack is used to get the language dependent letter from prompt text without really copying any file.
Command XCOPY is used to start copying the batch file itself to folder for temporary files with file extension being TMP for destination file. This results in a prompt by XCOPY if there is not already a file with that name in temporary files folder which is very unlikely.
The handler of device NUL is used as an input handler for XCOPY resulting in breaking the copying process after the prompt was output by XCOPY two times.
This output is processed in a FOR loop which is exited on first line starting with an opening parenthesis. This is the line on which second character defines the letter to use for specifying that destination is a file.
Here is a batch file using XCOPY with the code to determine the required letter for an automatic answering of the file or directory prompt to create a time stamped copy of a single file in same directory as the source file even if source file is a hidden or system file and even if the source file starts with a point and does not have a file extension.
@echo off
rem Batch file must be started or called with name of a single file.
if "%~1" == "" exit /B
for /F "delims=*?" %%I in ("#%~1#") do if not "%%I" == "#%~1#" exit /B
if not exist "%~1" exit /B
if exist "%~1\" exit /B
setlocal EnableDelayedExpansion
rem Determine the character needed for answering prompt of
rem XCOPY for destination being a file and not a directory.
del /F "%TEMP%\%~n0.tmp" 2>nul
for /F %%I in ('%SystemRoot%\System32\xcopy.exe "%~f0" "%TEMP%\%~n0.tmp" ^<nul') do (
set "PromptAnswer=%%I"
if "!PromptAnswer:~0,1!" == "(" (
set "PromptAnswer=!PromptAnswer:~1,1!"
goto CopyFile
)
)
echo ERROR: Failed to determine letter for answering prompt of XCOPY.
exit /B
:CopyFile
rem This is a workaround for files starting with a point and having no
rem file extension like many hidden files on *nix copied to Windows.
if "%~n1" == "" (
set "FileNameWithPath=%~dpx1"
set "FileExtension="
) else (
set "FileNameWithPath=%~dpn1"
set "FileExtension=%~x1"
)
rem Get local date and time in region and language independent format YYYYMMDDHHmmss
rem and reformat the local date and time to format YYYY-MM-DD_HH-mm-ss.
for /F "tokens=2 delims==." %%I in ('%SystemRoot%\System32\wbem\wmic.exe OS get LocalDateTime /format:value') do set "LocalDateTime=%%I"
set "LocalDateTime=%LocalDateTime:~0,4%-%LocalDateTime:~4,2%-%LocalDateTime:~6,2%_%LocalDateTime:~8,2%-%LocalDateTime:~10,2%-%LocalDateTime:~12,2%"
rem Do the copy with showing what is copied and with printing success or
rem an error message if copying fails for example on sharing violation.
echo Copy "%~f1" to "%FileNameWithPath%_%LocalDateTime%%FileExtension%"
for /F %%I in ('echo %PromptAnswer% ^| %SystemRoot%\System32\xcopy.exe "%~f1" "%FileNameWithPath%_%LocalDateTime%%FileExtension%" /C /H /K /Q /R /V /Y') do set "FilesCopied=%%I"
if "%FilesCopied%" == "1" (
echo Success
) else (
echo ERROR: Copying failed, see error message above.
)
This batch code was tested on German Windows XP SP3 x86 and English Windows 7 SP1 x64.
See the post Create a backup copy of files in UltraEdit forum for a similar, fully commented batch file explaining all parts of the batch code.
For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.
del /?
echo /?
exit /?
for /?
goto /?
if /?
rem /?
set /?
setlocal /?
wmic OS get /?
xcopy /?
Further the Microsoft article about Using command redirection operators should be read, too.
No internet on Android emulator - why and how to fix?
The easiest way is to follow these steps:
- run android emulator 1.5
- open up the menu
- go to settings
- wireless settings(first block) and right at the bottom turn off airplane mode.
By now you would've seen on top 3g and your established connection.
What is the difference between a mutable and immutable string in C#?
To clarify there is no such thing as a mutable string in C# (or .NET in general). Other langues support mutable strings (string which can change) but the .NET framework does not.
So the correct answer to your question is ALL string are immutable in C#.
string has a specific meaning. "string" lowercase keyword is merely a shortcut for an object instantiated from System.String class. All objects created from string class are ALWAYS immutable.
If you want a mutable representation of text then you need to use another class like StringBuilder. StringBuilder allows you to iteratively build a collection of 'words' and then convert that to a string (once again immutable).
Is it possible to ping a server from Javascript?
const ping = (url, timeout = 6000) => {
return new Promise((reslove, reject) => {
const urlRule = new RegExp('(https?|ftp|file)://[-A-Za-z0-9+&@#/%?=~_|!:,.;]+[-A-Za-z0-9+&@#/%=~_|]');
if (!urlRule.test(url)) reject('invalid url');
try {
fetch(url)
.then(() => reslove(true))
.catch(() => reslove(false));
setTimeout(() => {
reslove(false);
}, timeout);
} catch (e) {
reject(e);
}
});
};
use like this:
ping('https://stackoverflow.com/')
.then(res=>console.log(res))
.catch(e=>console.log(e))
Test iOS app on device without apple developer program or jailbreak
Seven years after the inception of the App Store (July 10, 2008), Apple has finally introduced a new feature in Xcode 7 that allows you to deploy and run any number of apps on any of your devices, simply by logging in with your Apple ID. You will no longer need a paid Program membership to deploy apps on your own device (and you certainly no longer have to jailbreak your device if you're not comfortable doing so).
Well, not for the majority of use cases anyway. For obvious reasons, certain capabilities and entitlements that require Program membership such as Game Center and in-app purchases will not be available to apps deployed using this method. From Apple's developer documentation:
Launch Your App on Devices Using Free Provisioning (iOS, watchOS)
If you don’t join the Apple Developer Program, you can still build and run your app on your devices using free provisioning. However, the capabilities available to your app, described in Adding Capabilities, are restricted when you don’t belong to the Apple Developer Program.
The precise steps to getting your app onto your iOS device or Apple Watch follow immediately thus (screenshots omitted for ease of skimming):
In Xcode, add your Apple ID to Accounts preferences, described in Adding Your Apple ID Account in Xcode.
In the project navigator, select the project and your target to display the project editor.
Click General and choose your name from the Team pop-up menu.
Connect the device to your Mac and choose your device from the Scheme toolbar menu.
Below the Team pop-up menu, click Fix Issue.
Xcode creates a free provisioning profile for you and the warning text under the Team pop-up menu disappears.
Click the Run button.
Xcode installs the app on the device before launching the app.
Prior to Xcode 7, a Program membership was indeed required in order to sign the provisioning certificates required to deploy apps to devices. The only other alternative was jailbreaking. With Xcode 7, you no longer need to jailbreak your device just to run apps distributed outside the App Store, or to test apps if you cannot afford to join the Program, or to deploy and use apps that you have developed for your own personal use if you do not intend to distribute them through the App Store (in which case you probably don't need the entitlements offered by Program membership anyway).
Using onBlur with JSX and React
There are a few problems here.
1: onBlur expects a callback, and you are calling renderPasswordConfirmError
and using the return value, which is null.
2: you need a place to render the error.
3: you need a flag to track "and I validating", which you would set to true on blur. You can set this to false on focus if you want, depending on your desired behavior.
handleBlur: function () {
this.setState({validating: true});
},
render: function () {
return <div>
...
<input
type="password"
placeholder="Password (confirm)"
valueLink={this.linkState('password2')}
onBlur={this.handleBlur}
/>
...
{this.renderPasswordConfirmError()}
</div>
},
renderPasswordConfirmError: function() {
if (this.state.validating && this.state.password !== this.state.password2) {
return (
<div>
<label className="error">Please enter the same password again.</label>
</div>
);
}
return null;
},
SSH SCP Local file to Remote in Terminal Mac Os X
Just to clarify the answer given by JScoobyCed, the scp command cannot copy files to directories that require administrative permission. However, you can use the scp command to copy to directories that belong to the remote user.
So, to copy to a directory that requires root privileges, you must first copy that file to a directory belonging to the remote user using the scp command. Next, you must login to the remote account using ssh. Once logged in, you can then move the file to the directory of your choosing by using the sudo mv command. In short, the commands to use are as follows:
Using scp, copy file to a directory in the remote user's account, for example the Documents directory:
scp /path/to/your/local/file remoteUser@some_address:/home/remoteUser/Documents
Next, login to the remote user's account using ssh and then move the file to a restricted directory using sudo:
ssh remoteUser@some_address
sudo mv /home/remoteUser/Documents/file /var/www
Create PDF from a list of images
The best answer already exists !!! I am just improving the answer a little bit.
Here's the code :
from fpdf import FPDF
pdf = FPDF()
# imagelist is the list with all image filenames you can create using os module by iterating all the files in a folder or by specifying their name
for image in imagelist:
pdf.add_page()
pdf.image(image,x=0,y=0,w=210,h=297) # for A4 size because some people said that every other page is blank
pdf.output("yourfile.pdf", "F")
You'll need to install FPDF for this purpose.
pip install FPDF
Spring Boot access static resources missing scr/main/resources
While working with Spring Boot application, it is difficult to get the classpath resources using resource.getFile()
when it is deployed as JAR as I faced the same issue.
This scan be resolved using Stream which will find out all the resources which are placed anywhere in classpath.
Below is the code snippet for the same -
ClassPathResource classPathResource = new ClassPathResource("fileName");
InputStream inputStream = classPathResource.getInputStream();
content = IOUtils.toString(inputStream);
How to change text color of cmd with windows batch script every 1 second
Try this script. This can write any text on any position of screen and don't use temporary files or ".com, .exe" executables. Just make shure you have the "debug.exe" executable in windows\system or windows\system32 folders.
http://pastebin.com/bzYhfLGc
@echo off
setlocal enabledelayedexpansion
set /a _er=0
set /a _n=0
set _ln=%~4
goto init
:howuse ---------------------------------------------------------------
echo ------------------
echo ECOL.BAT - ver 1.0
echo ------------------
echo Print colored text in batch script
echo Written by BrendanLS - http://640kbworld.forum.st
echo.
echo Syntax:
echo ECOL.BAT [COLOR] [X] [Y] "Insert your text"
echo COLOR value must be a hexadecimal number
echo.
echo Example:
echo ECOL.BAT F0 20 30 "The 640KB World Forum"
echo.
echo Enjoy ;^)
goto quit
:error ----------------------------------------------------------------
set /a "_er=_er | (%~1)"
goto quit
:geth -----------------------------------------------------------------
set return=
set bts=%~1
:hshift ---------------------------------------------------------------
set /a "nn = bts & 0xff"
set return=!h%nn%!%return%
set /a "bts = bts >> 0x8"
if %bts% gtr 0 goto hshift
goto quit
:init -----------------------------------------------------------------
if "%~4"=="" call :error 0xff
(
set /a _cl=0x%1
call :error !errorlevel!
set _cl=%1
call :error "0x!_cl! ^>^> 8"
set /a _px=%2
call :error !errorlevel!
set /a _py=%3
call :error !errorlevel!
) 2>nul 1>&2
if !_er! neq 0 (
echo.
echo ERROR: value exception "!_er!" occurred.
echo.
goto howuse
)
set nsys=0123456789abcdef
set /a _val=-1
for /l %%a in (0,1,15) do (
for /l %%b in (0,1,15) do (
set /a "_val += 1"
set byte=!nsys:~%%a,1!!nsys:~%%b,1!
set h!_val!=!byte!
)
)
set /a cnb=0
set /a cnl=0
:parse ----------------------------------------------------------------
set _ch=!_ln:~%_n%,1!
if "%_ch%"=="" goto perform
set /a "cnb += 1"
if %cnb% gtr 7 (
set /a cnb=0
set /a "cnl += 1"
)
set bln%cnl%=!bln%cnl%! "!_ch!" %_cl%
set /a "_n += 1"
goto parse
:perform --------------------------------------------------------------
set /a "in = ((_py * 160) + (_px * 2)) & 0xffff"
call :geth %in%
set ntr=!return!
set /a jmp=0xe
@for /l %%x in (0,1,%cnl%) do (
set bl8086%%x=eb800:!ntr! !bln%%x!
set /a "in=!jmp! + 0x!ntr!"
call :geth !in!
set ntr=!return!
set /a jmp=0x10
)
(
echo.%bl80860%&echo.%bl80861%&echo.%bl80862%&echo.%bl80863%&echo.%bl80864%
echo.q
)|debug >nul 2>&1
:quit
Searching multiple files for multiple words
If you are using Notepad++ editor
Goto ctrl + F choose tab 3 find in files and enter:
- Find What = text1*.*text2
- Filters : .
- Search mode = Regular Expression
- Directory = enter the path of the directory you want to search in. You can check Follow current doc. to have the path of the current file to be filled.
Prevent jQuery UI dialog from setting focus to first textbox
Add a hidden span above it, use ui-helper-hidden-accessible to make it hidden by absolute positioning. I know you have that class because you are using dialog from jquery-ui and it's in jquery-ui.
<span class="ui-helper-hidden-accessible"><input type="text"/></span>
React-router urls don't work when refreshing or writing manually
As I am using .Net Core MVC something like this helped me:
public class HomeController : Controller
{
public IActionResult Index()
{
var url = Request.Path + Request.QueryString;
return App(url);
}
[Route("App")]
public IActionResult App(string url)
{
return View("/wwwroot/app/build/index.html");
}
}
Basically in MVC side, all the routes not matching will fall into to Home/Index
as it specified in startup.cs
. Inside Index
it is possible to get the original request url and pass it wherever needed.
startup.cs
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
routes.MapSpaFallbackRoute(
name: "spa-fallback",
defaults: new { controller = "Home", action = "Index" });
});
MVC3 EditorFor readOnly
i think this is simple than other by using [Editable(false)] attribute
for example:
public class MyModel
{
[Editable(false)]
public string userName { get; set; }
}
android ellipsize multiline textview
This is late, but I found an Apache licensed class from Android, that's used in the stock mail app: https://android.googlesource.com/platform/packages/apps/UnifiedEmail/+/184ec73/src/com/android/mail/ui/EllipsizedMultilineTextView.java
/*
* Copyright (C) 2013 Google Inc.
* Licensed to The Android Open Source Project.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.mail.ui;
import android.content.Context;
import android.text.Layout;
import android.text.Layout.Alignment;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.StaticLayout;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.widget.TextView;
/**
* A special MultiLine TextView that will apply ellipsize logic to only the last
* line of text, such that the last line may be shorter than any previous lines.
*/
public class EllipsizedMultilineTextView extends TextView {
public static final int ALL_AVAILABLE = -1;
private int mMaxLines;
public EllipsizedMultilineTextView(Context context) {
this(context, null);
}
public EllipsizedMultilineTextView(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
public void setMaxLines(int maxlines) {
super.setMaxLines(maxlines);
mMaxLines = maxlines;
}
/**
* Ellipsize just the last line of text in this view and set the text to the
* new ellipsized value.
* @param text Text to set and ellipsize
* @param avail available width in pixels for the last line
* @param paint Paint that has the proper properties set to measure the text
* for this view
* @return the {@link CharSequence} that was set on the {@link TextView}
*/
public CharSequence setText(final CharSequence text, int avail) {
if (text == null || text.length() == 0) {
return text;
}
setEllipsize(null);
setText(text);
if (avail == ALL_AVAILABLE) {
return text;
}
Layout layout = getLayout();
if (layout == null) {
final int w = getWidth() - getCompoundPaddingLeft() - getCompoundPaddingRight();
layout = new StaticLayout(text, 0, text.length(), getPaint(), w, Alignment.ALIGN_NORMAL,
1.0f, 0f, false);
}
// find the last line of text and chop it according to available space
final int lastLineStart = layout.getLineStart(mMaxLines - 1);
final CharSequence remainder = TextUtils.ellipsize(text.subSequence(lastLineStart,
text.length()), getPaint(), avail, TextUtils.TruncateAt.END);
// assemble just the text portion, without spans
final SpannableStringBuilder builder = new SpannableStringBuilder();
builder.append(text.toString(), 0, lastLineStart);
if (!TextUtils.isEmpty(remainder)) {
builder.append(remainder.toString());
}
// Now copy the original spans into the assembled string, modified for any ellipsizing.
//
// Merely assembling the Spanned pieces together would result in duplicate CharacterStyle
// spans in the assembled version if a CharacterStyle spanned across the lastLineStart
// offset.
if (text instanceof Spanned) {
final Spanned s = (Spanned) text;
final Object[] spans = s.getSpans(0, s.length(), Object.class);
final int destLen = builder.length();
for (int i = 0; i < spans.length; i++) {
final Object span = spans[i];
final int start = s.getSpanStart(span);
final int end = s.getSpanEnd(span);
final int flags = s.getSpanFlags(span);
if (start <= destLen) {
builder.setSpan(span, start, Math.min(end, destLen), flags);
}
}
}
setText(builder);
return builder;
}
}
symfony 2 twig limit the length of the text and put three dots
I wrote this simple marco for the same purpose, hope it helps:
{%- macro stringMaxLength(str, maxLength) -%}
{%- if str | length < maxLength -%}
{{ str }}
{%- else -%}
{{ str|slice(0, maxLength) }}...
{%- endif -%}
{%- endmacro -%}
Usage Example #1 (Output: "my long string here ..."):
{{ _self.stringMaxLength("my long string here bla bla bla la", 20) }}
Usage Example #2 (Output: "shorter string!"):
{{ _self.stringMaxLength("shorter string!", 20) }}
Waiting on a list of Future
maybe this would help (nothing would replaced with raw thread, yeah!)
I suggest run each Future
guy with a separated thread (they goes parallel), then when ever one of the got error, it just signal the manager(Handler
class).
class Handler{
//...
private Thread thisThread;
private boolean failed=false;
private Thread[] trds;
public void waitFor(){
thisThread=Thread.currentThread();
List<Future<Object>> futures = getFutures();
trds=new Thread[futures.size()];
for (int i = 0; i < trds.length; i++) {
RunTask rt=new RunTask(futures.get(i), this);
trds[i]=new Thread(rt);
}
synchronized (this) {
for(Thread tx:trds){
tx.start();
}
}
for(Thread tx:trds){
try {tx.join();
} catch (InterruptedException e) {
System.out.println("Job failed!");break;
}
}if(!failed){System.out.println("Job Done");}
}
private List<Future<Object>> getFutures() {
return null;
}
public synchronized void cancelOther(){if(failed){return;}
failed=true;
for(Thread tx:trds){
tx.stop();//Deprecated but works here like a boss
}thisThread.interrupt();
}
//...
}
class RunTask implements Runnable{
private Future f;private Handler h;
public RunTask(Future f,Handler h){this.f=f;this.h=h;}
public void run(){
try{
f.get();//beware about state of working, the stop() method throws ThreadDeath Error at any thread state (unless it blocked by some operation)
}catch(Exception e){System.out.println("Error, stopping other guys...");h.cancelOther();}
catch(Throwable t){System.out.println("Oops, some other guy has stopped working...");}
}
}
I have to say the above code would error(didn't check), but I hope I could explain the solution. please have a try.
I'm trying to use python in powershell
$env:path="$env:Path;C:\Python27"
will only set it for the current session. Next time you open Powershell, you will have to do the same thing again.
The [Environment]::SetEnvironmentVariable()
is the right way, and it would have set your PATH environment variable permanently. You just have to start Powershell again to see the effect in this case.
JQuery style display value
Well, for one thing your epression can be simplified:
$("#pDetails").attr("style")
since there should only be one element for any given ID and the ID selector will be much faster than the attribute id selector you're using.
If you just want to return the display value or something, use css():
$("#pDetails").css("display")
If you want to search for elements that have display none, that's a lot harder to do reliably. This is a rough example that won't be 100%:
$("[style*='display: none']")
but if you just want to find things that are hidden, use this:
$(":hidden")
How can I change the class of an element with jQuery>
To set a class completely, instead of adding one or removing one, use this:
$(this).attr("class","newclass");
Advantage of this is that you'll remove any class that might be set in there and reset it to how you like. At least this worked for me in one situation.
Run a string as a command within a Bash script
Here is my gradle build script that executes strings stored in heredocs:
current_directory=$( realpath "." )
GENERATED=${current_directory}/"GENERATED"
build_gradle=$( realpath build.gradle )
## touch because .gitignore ignores this folder:
touch $GENERATED
COPY_BUILD_FILE=$( cat <<COPY_BUILD_FILE_HEREDOC
cp
$build_gradle
$GENERATED/build.gradle
COPY_BUILD_FILE_HEREDOC
)
$COPY_BUILD_FILE
GRADLE_COMMAND=$( cat <<GRADLE_COMMAND_HEREDOC
gradle run
--build-file
$GENERATED/build.gradle
--gradle-user-home
$GENERATED
--no-daemon
GRADLE_COMMAND_HEREDOC
)
$GRADLE_COMMAND
The lone ")" are kind of ugly. But I have no clue how to fix that asthetic aspect.
How to stop Python closing immediately when executed in Microsoft Windows
I think I am too late to answer this question but anyways here goes nothing.
I have run in to the same problem before and I think there are two alternative solutions you can choose from.
- using sleep(_sometime)
from time import *
sleep(10)
- using a prompt message (note that I am using python 2.7)
exit_now = raw_input("Do you like to exit now (Y)es (N)o ? ")'
if exit_now.lower() = 'n'
//more processing here
Alternatively you can use a hybrid of those two methods as well where you can prompt for a message and use sleep(sometime) to delay the window closing as well. choice is yours.
please note the above are just ideas and if you want to use any of those in practice you might have to think about your application logic a bit.
Find location of a removable SD card
Like Richard I also use /proc/mounts file to get the list of available storage options
public class StorageUtils {
private static final String TAG = "StorageUtils";
public static class StorageInfo {
public final String path;
public final boolean internal;
public final boolean readonly;
public final int display_number;
StorageInfo(String path, boolean internal, boolean readonly, int display_number) {
this.path = path;
this.internal = internal;
this.readonly = readonly;
this.display_number = display_number;
}
public String getDisplayName() {
StringBuilder res = new StringBuilder();
if (internal) {
res.append("Internal SD card");
} else if (display_number > 1) {
res.append("SD card " + display_number);
} else {
res.append("SD card");
}
if (readonly) {
res.append(" (Read only)");
}
return res.toString();
}
}
public static List<StorageInfo> getStorageList() {
List<StorageInfo> list = new ArrayList<StorageInfo>();
String def_path = Environment.getExternalStorageDirectory().getPath();
boolean def_path_internal = !Environment.isExternalStorageRemovable();
String def_path_state = Environment.getExternalStorageState();
boolean def_path_available = def_path_state.equals(Environment.MEDIA_MOUNTED)
|| def_path_state.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
boolean def_path_readonly = Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED_READ_ONLY);
BufferedReader buf_reader = null;
try {
HashSet<String> paths = new HashSet<String>();
buf_reader = new BufferedReader(new FileReader("/proc/mounts"));
String line;
int cur_display_number = 1;
Log.d(TAG, "/proc/mounts");
while ((line = buf_reader.readLine()) != null) {
Log.d(TAG, line);
if (line.contains("vfat") || line.contains("/mnt")) {
StringTokenizer tokens = new StringTokenizer(line, " ");
String unused = tokens.nextToken(); //device
String mount_point = tokens.nextToken(); //mount point
if (paths.contains(mount_point)) {
continue;
}
unused = tokens.nextToken(); //file system
List<String> flags = Arrays.asList(tokens.nextToken().split(",")); //flags
boolean readonly = flags.contains("ro");
if (mount_point.equals(def_path)) {
paths.add(def_path);
list.add(0, new StorageInfo(def_path, def_path_internal, readonly, -1));
} else if (line.contains("/dev/block/vold")) {
if (!line.contains("/mnt/secure")
&& !line.contains("/mnt/asec")
&& !line.contains("/mnt/obb")
&& !line.contains("/dev/mapper")
&& !line.contains("tmpfs")) {
paths.add(mount_point);
list.add(new StorageInfo(mount_point, false, readonly, cur_display_number++));
}
}
}
}
if (!paths.contains(def_path) && def_path_available) {
list.add(0, new StorageInfo(def_path, def_path_internal, def_path_readonly, -1));
}
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (buf_reader != null) {
try {
buf_reader.close();
} catch (IOException ex) {}
}
}
return list;
}
}
What is the difference between localStorage, sessionStorage, session and cookies?
These are properties of 'window' object in JavaScript, just like document is one of a property of window object which holds DOM objects.
Session Storage property maintains a separate storage area for each given origin that's available for the duration of the page session i.e as long as the browser is open, including page reloads and restores.
Local Storage does the same thing, but persists even when the browser is closed and reopened.
You can set and retrieve stored data as follows:
sessionStorage.setItem('key', 'value');
var data = sessionStorage.getItem('key');
Similarly for localStorage.
Python if-else short-hand
The most readable way is
x = 10 if a > b else 11
but you can use and
and or
, too:
x = a > b and 10 or 11
The "Zen of Python" says that "readability counts", though, so go for the first way.
Also, the and-or trick will fail if you put a variable instead of 10
and it evaluates to False
.
However, if more than the assignment depends on this condition, it will be more readable to write it as you have:
if A[i] > B[j]:
x = A[i]
i += 1
else:
x = A[j]
j += 1
unless you put i
and j
in a container. But if you show us why you need it, it may well turn out that you don't.
When and why do I need to use cin.ignore() in C++?
Short answer
Why? Because there is still whitespace (carriage returns, tabs, spaces, newline) left in the input stream.
When? When you are using some function which does not on their own ignores the leading whitespaces. Cin by default ignores and removes the leading whitespace but getline does not ignore the leading whitespace on its own.
Now a detailed answer.
Everything you input in the console is read from the standard stream stdin. When you enter something, let's say 256 in your case and press enter, the contents of the stream become 256\n
. Now cin picks up 256 and removes it from the stream and \n
still remaining in the stream.
Now next when you enter your name, let's say Raddicus
, the new contents of the stream is \nRaddicus
.
Now here comes the catch.
When you try to read a line using getline, if not provided any delimiter as the third argument, getline by default reads till the newline character and removes the newline character from the stream.
So on calling new line, getline reads and discards \n
from the stream and resulting in an empty string read in mystr which appears like getline is skipped (but it's not) because there was already an newline in the stream, getline will not prompt for input as it has already read what it was supposed to read.
Now, how does cin.ignore help here?
According to the ignore documentation extract from cplusplus.com-
istream& ignore (streamsize n = 1, int delim = EOF);
Extracts characters from the input sequence and discards them, until
either n characters have been extracted, or one compares equal to
delim.
The function also stops extracting characters if the end-of-file is
reached. If this is reached prematurely (before either extracting n
characters or finding delim), the function sets the eofbit flag.
So, cin.ignore(256, '\n');
, ignores first 256 characters or all the character untill it encounters delimeter (here \n in your case), whichever comes first (here \n is the first character, so it ignores until \n is encountered).
Just for your reference, If you don't exactly know how many characters to skip and your sole purpose is to clear the stream to prepare for reading a string using getline or cin you should use cin.ignore(numeric_limits<streamsize>::max(),'\n')
.
Quick explanation: It ignores the characters equal to maximum size of stream or until a '\n' is encountered, whichever case happens first.
Loop through all elements in XML using NodeList
Here is another way to loop through XML elements using JDOM.
List<Element> nodeNodes = inputNode.getChildren();
if (nodeNodes != null) {
for (Element nodeNode : nodeNodes) {
List<Element> elements = nodeNode.getChildren(elementName);
if (elements != null) {
elements.size();
nodeNodes.removeAll(elements);
}
}
get DATEDIFF excluding weekends using sql server
BEGIN
DECLARE @totaldays INT;
DECLARE @weekenddays INT;
SET @totaldays = DATEDIFF(DAY, @startDate, @endDate)
SET @weekenddays = ((DATEDIFF(WEEK, @startDate, @endDate) * 2) + -- get the number of weekend days in between
CASE WHEN DATEPART(WEEKDAY, @startDate) = 1 THEN 1 ELSE 0 END + -- if selection was Sunday, won't add to weekends
CASE WHEN DATEPART(WEEKDAY, @endDate) = 6 THEN 1 ELSE 0 END) -- if selection was Saturday, won't add to weekends
Return (@totaldays - @weekenddays)
END
This is on SQL Server 2014
how do I initialize a float to its max/min value?
You can either use -FLT_MAX
(or -DBL_MAX
) for the maximum magnitude negative number and FLT_MAX
(or DBL_MAX
) for positive. This gives you the range of possible float (or double) values.
You probably don't want to use FLT_MIN
; it corresponds to the smallest magnitude positive number that can be represented with a float, not the most negative value representable with a float.
FLT_MIN
and FLT_MAX
correspond to std::numeric_limits<float>::min()
and std::numeric_limits<float>::max()
.
Chrome Uncaught Syntax Error: Unexpected Token ILLEGAL
I had the same error when multiline string included new line (\n
) characters. Merging all lines into one (thus removing all new line characters) and sending it to a browser used to solve. But was very inconvenient to code.
Often could not understand why this was an issue in Chrome until I came across to a statement which said that the current version of JavaScript engine in Chrome doesn't support multiline strings which are wrapped in single quotes and have new line (\n
) characters in them. To make it work, multiline string need to be wrapped in double quotes. Changing my code to this, resolved this issue.
I will try to find a reference to a standard or Chrome doc which proves this. Until then, try this solution and see if works for you as well.
Decimal precision and scale in EF Code First
In EF6
modelBuilder.Properties()
.Where(x => x.GetCustomAttributes(false).OfType<DecimalPrecisionAttribute>().Any())
.Configure(c => {
var attr = (DecimalPrecisionAttribute)c.ClrPropertyInfo.GetCustomAttributes(typeof (DecimalPrecisionAttribute), true).FirstOrDefault();
c.HasPrecision(attr.Precision, attr.Scale);
});
Measuring execution time of a function in C++
#include <iostream>
#include <chrono>
void function()
{
// code here;
}
int main()
{
auto t1 = std::chrono::high_resolution_clock::now();
function();
auto t2 = std::chrono::high_resolution_clock::now();
auto duration = std::chrono::duration_cast<std::chrono::microseconds>( t2 - t1 ).count();
std::cout << duration<<"/n";
return 0;
}
This Worked for me.
Note:
The high_resolution_clock
is not implemented consistently across different standard library implementations, and its use should be avoided. It is often just an alias for std::chrono::steady_clock
or std::chrono::system_clock
, but which one it is depends on the library or configuration. When it is a system_clock
, it is not monotonic (e.g., the time can go backwards).
For example, for gcc's libstdc++
it is system_clock
, for MSVC it is steady_clock
, and for clang's libc++
it depends on configuration.
Generally one should just use std::chrono::steady_clock
or std::chrono::system_clock
directly instead of std::chrono::high_resolution_clock
: use steady_clock
for duration measurements, and system_clock
for wall-clock time.
onclick open window and specific size
Anyone looking for a quick Vue file component, here you go:
// WindowUrl.vue
<template>
<a :href="url" :class="classes" @click="open">
<slot></slot>
</a>
</template>
<script>
export default {
props: {
url: String,
width: String,
height: String,
classes: String,
},
methods: {
open(e) {
// Prevent the link from opening on the parent page.
e.preventDefault();
window.open(
this.url,
'targetWindow',
`toolbar=no,location=no,status=no,menubar=no,scrollbars=no,resizable=yes,width=${this.width},height=${this.height}`
);
}
}
}
</script>
Usage:
<window-url url="/print/shipping" class="btn btn-primary" height="250" width="250">
Print Shipping Label
</window-url>
Grunt watch error - Waiting...Fatal error: watch ENOSPC
I ran into this error after my client PC crashed, the jest --watch
command I was running on the server persisted, and I tried to run jest --watch
again.
The addition to /etc/sysctl.conf
described in the answers above worked around this issue, but it was also important to find my old process via ps aux | grep node
and kill
it.
Do I need Content-Type: application/octet-stream for file download?
No.
The content-type should be whatever it is known to be, if you know it. application/octet-stream
is defined as "arbitrary binary data" in RFC 2046, and there's a definite overlap here of it being appropriate for entities whose sole intended purpose is to be saved to disk, and from that point on be outside of anything "webby". Or to look at it from another direction; the only thing one can safely do with application/octet-stream is to save it to file and hope someone else knows what it's for.
You can combine the use of Content-Disposition
with other content-types, such as image/png
or even text/html
to indicate you want saving rather than display. It used to be the case that some browsers would ignore it in the case of text/html
but I think this was some long time ago at this point (and I'm going to bed soon so I'm not going to start testing a whole bunch of browsers right now; maybe later).
RFC 2616 also mentions the possibility of extension tokens, and these days most browsers recognise inline
to mean you do want the entity displayed if possible (that is, if it's a type the browser knows how to display, otherwise it's got no choice in the matter). This is of course the default behaviour anyway, but it means that you can include the filename
part of the header, which browsers will use (perhaps with some adjustment so file-extensions match local system norms for the content-type in question, perhaps not) as the suggestion if the user tries to save.
Hence:
Content-Type: application/octet-stream
Content-Disposition: attachment; filename="picture.png"
Means "I don't know what the hell this is. Please save it as a file, preferably named picture.png".
Content-Type: image/png
Content-Disposition: attachment; filename="picture.png"
Means "This is a PNG image. Please save it as a file, preferably named picture.png".
Content-Type: image/png
Content-Disposition: inline; filename="picture.png"
Means "This is a PNG image. Please display it unless you don't know how to display PNG images. Otherwise, or if the user chooses to save it, we recommend the name picture.png for the file you save it as".
Of those browsers that recognise inline
some would always use it, while others would use it if the user had selected "save link as" but not if they'd selected "save" while viewing (or at least IE used to be like that, it may have changed some years ago).
Xcode stops working after set "xcode-select -switch"
You should be pointing it towards the Developer
directory, not the Xcode application bundle. Run this:
sudo xcode-select --switch /Applications/Xcode.app/Contents/Developer
With recent versions of Xcode, you can go to Xcode ? Preferences… ? Locations and pick one of the options for Command Line Tools to set the location.
SQL Server procedure declare a list
You can convert the list of passed values into a table valued parameter and then select against this list
DECLARE @list NVARCHAR(MAX)
SET @list = '1,2,5,7,10';
DECLARE @pos INT
DECLARE @nextpos INT
DECLARE @valuelen INT
DECLARE @tbl TABLE (number int NOT NULL)
SELECT @pos = 0, @nextpos = 1;
WHILE @nextpos > 0
BEGIN
SELECT @nextpos = charindex(',', @list, @pos + 1)
SELECT @valuelen = CASE WHEN @nextpos > 0
THEN @nextpos
ELSE len(@list) + 1
END - @pos - 1
INSERT @tbl (number)
VALUES (convert(int, substring(@list, @pos + 1, @valuelen)))
SELECT @pos = @nextpos;
END
SELECT * FROM DBTable WHERE id IN (SELECT number FROM @tbl);
In this example the string passed in '1,2,5,7,10' is split by the commas and each value is added as a new row within the @tbl
table variable. This can then be selected against using standard SQL.
If you intend to reuse this functionality you could go further and convert this into a function.
update package.json version automatically
Just in case if you want to do this using an npm package semver
link
let fs = require('fs');
let semver = require('semver');
if (fs.existsSync('./package.json')) {
var package = require('./package.json');
let currentVersion = package.version;
let type = process.argv[2];
if (!['major', 'minor', 'patch'].includes(type)) {
type = 'patch';
}
let newVersion = semver.inc(package.version, type);
package.version = newVersion;
fs.writeFileSync('./package.json', JSON.stringify(package, null, 2));
console.log('Version updated', currentVersion, '=>', newVersion);
}
package.json
should look like,
{
"name": "versioning",
"version": "0.0.0",
"description": "Update version in package.json using npm script",
"main": "version.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"version": "node version.js"
},
"author": "Bhadresh Arya",
"license": "ISC",
"dependencies": {
"semver": "^7.3.2"
}
}
just pass major
, minor
, patch
argument with npm run version
. Default will be patch
.
example:
npm run version
or npm run verison patch
or npm run verison minor
or npm run version major
Git Repo
Use table name in MySQL SELECT "AS"
To declare a string literal as an output column, leave the Table
off and just use Test
. It doesn't need to be associated with a table among your joins, since it will be accessed only by its column alias. When using a metadata function like getColumnMeta()
, the table name will be an empty string because it isn't associated with a table.
SELECT
`field1`,
`field2`,
'Test' AS `field3`
FROM `Test`;
Note: I'm using single quotes above. MySQL is usually configured to honor double quotes for strings, but single quotes are more widely portable among RDBMS.
If you must have a table alias name with the literal value, you need to wrap it in a subquery with the same name as the table you want to use:
SELECT
field1,
field2,
field3
FROM
/* subquery wraps all fields to put the literal inside a table */
(SELECT field1, field2, 'Test' AS field3 FROM Test) AS Test
Now field3
will come in the output as Test.field3
.
Style jQuery autocomplete in a Bootstrap input field
I don't know if you fixed it, but I did had the same issue, finally it was a dumb thing, I had:
<script src="jquery-ui/jquery-ui.min.css" rel="stylesheet">
but it should be:
<link href="jquery-ui/jquery-ui.min.css" rel="stylesheet">
Just change <scrip>
to <link>
and src
to href
How do I clear all variables in the middle of a Python script?
The following sequence of commands does remove every name from the current module:
>>> import sys
>>> sys.modules[__name__].__dict__.clear()
I doubt you actually DO want to do this, because "every name" includes all built-ins, so there's not much you can do after such a total wipe-out. Remember, in Python there is really no such thing as a "variable" -- there are objects, of many kinds (including modules, functions, class, numbers, strings, ...), and there are names, bound to objects; what the sequence does is remove every name from a module (the corresponding objects go away if and only if every reference to them has just been removed).
Maybe you want to be more selective, but it's hard to guess exactly what you mean unless you want to be more specific. But, just to give an example:
>>> import sys
>>> this = sys.modules[__name__]
>>> for n in dir():
... if n[0]!='_': delattr(this, n)
...
>>>
This sequence leaves alone names that are private or magical, including the __builtins__
special name which houses all built-in names. So, built-ins still work -- for example:
>>> dir()
['__builtins__', '__doc__', '__name__', '__package__', 'n']
>>>
As you see, name n
(the control variable in that for
) also happens to stick around (as it's re-bound in the for
clause every time through), so it might be better to name that control variable _
, for example, to clearly show "it's special" (plus, in the interactive interpreter, name _
is re-bound anyway after every complete expression entered at the prompt, to the value of that expression, so it won't stick around for long;-).
Anyway, once you have determined exactly what it is you want to do, it's not hard to define a function for the purpose and put it in your start-up file (if you want it only in interactive sessions) or site-customize file (if you want it in every script).
How to make an HTTP POST web request
There are several ways to perform HTTP GET
and POST
requests:
Method A: HttpClient (Preferred)
Available in: .NET Framework 4.5+
, .NET Standard 1.1+
, .NET Core 1.0+
.
It is currently the preferred approach, and is asynchronous and high performance. Use the built-in version in most cases, but for very old platforms there is a NuGet package.
using System.Net.Http;
Setup
It is recommended to instantiate one HttpClient
for your application's lifetime and share it unless you have a specific reason not to.
private static readonly HttpClient client = new HttpClient();
See HttpClientFactory
for a dependency injection solution.
POST
var values = new Dictionary<string, string>
{
{ "thing1", "hello" },
{ "thing2", "world" }
};
var content = new FormUrlEncodedContent(values);
var response = await client.PostAsync("http://www.example.com/recepticle.aspx", content);
var responseString = await response.Content.ReadAsStringAsync();
GET
var responseString = await client.GetStringAsync("http://www.example.com/recepticle.aspx");
Method B: Third-Party Libraries
RestSharp
POST
var client = new RestClient("http://example.com");
// client.Authenticator = new HttpBasicAuthenticator(username, password);
var request = new RestRequest("resource/{id}");
request.AddParameter("thing1", "Hello");
request.AddParameter("thing2", "world");
request.AddHeader("header", "value");
request.AddFile("file", path);
var response = client.Post(request);
var content = response.Content; // Raw content as string
var response2 = client.Post<Person>(request);
var name = response2.Data.Name;
Flurl.Http
It is a newer library sporting a fluent API, testing helpers, uses HttpClient under the hood, and is portable. It is available via NuGet.
using Flurl.Http;
POST
var responseString = await "http://www.example.com/recepticle.aspx"
.PostUrlEncodedAsync(new { thing1 = "hello", thing2 = "world" })
.ReceiveString();
GET
var responseString = await "http://www.example.com/recepticle.aspx"
.GetStringAsync();
Method C: HttpWebRequest (not recommended for new work)
Available in: .NET Framework 1.1+
, .NET Standard 2.0+
, .NET Core 1.0+
. In .NET Core, it is mostly for compatibility -- it wraps HttpClient
, is less performant, and won't get new features.
using System.Net;
using System.Text; // For class Encoding
using System.IO; // For StreamReader
POST
var request = (HttpWebRequest)WebRequest.Create("http://www.example.com/recepticle.aspx");
var postData = "thing1=" + Uri.EscapeDataString("hello");
postData += "&thing2=" + Uri.EscapeDataString("world");
var data = Encoding.ASCII.GetBytes(postData);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
using (var stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
var response = (HttpWebResponse)request.GetResponse();
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
GET
var request = (HttpWebRequest)WebRequest.Create("http://www.example.com/recepticle.aspx");
var response = (HttpWebResponse)request.GetResponse();
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
Method D: WebClient (Not recommended for new work)
This is a wrapper around HttpWebRequest
. Compare with HttpClient
.
Available in: .NET Framework 1.1+
, NET Standard 2.0+
, .NET Core 2.0+
using System.Net;
using System.Collections.Specialized;
POST
using (var client = new WebClient())
{
var values = new NameValueCollection();
values["thing1"] = "hello";
values["thing2"] = "world";
var response = client.UploadValues("http://www.example.com/recepticle.aspx", values);
var responseString = Encoding.Default.GetString(response);
}
GET
using (var client = new WebClient())
{
var responseString = client.DownloadString("http://www.example.com/recepticle.aspx");
}
Change fill color on vector asset in Android Studio
You can do it.
BUT you cannot use @color references for colors (..lame), otherwise it will work only for L+
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24.0"
android:viewportHeight="24.0">
<path
android:fillColor="#FFAABB"
android:pathData="M15.5,14h-0.79l-0.28,-0.27C15.41,12.59 16,11.11 16,9.5 16,5.91 13.09,3 9.5,3S3,5.91 3,9.5 5.91,16 9.5,16c1.61,0 3.09,-0.59 4.23,-1.57l0.27,0.28v0.79l5,4.99L20.49,19l-4.99,-5zm-6,0C7.01,14 5,11.99 5,9.5S7.01,5 9.5,5 14,7.01 14,9.5 11.99,14 9.5,14z"/>
How to change environment's font size?
There is a setting window.zoom that can enlarge the entire window content including the top menus and side nav tree. Setting this to 1 on a 4k monitor makes the content similar to a 1080p monitor of the same physical size.
Edit a text file on the console using Powershell
Not sure if this will benefit anybody, but if you are using Azure CloudShell PowerShell you can just type:
code file.txt
And Visual Studio code will popup with the file to be edit, pretty great.
What's the best way to dedupe a table?
Adding the actual code here for future reference
So, there are 3 steps, and therefore 3 SQL statements:
Step 1: Move the non duplicates (unique tuples) into a temporary table
CREATE TABLE new_table as
SELECT * FROM old_table WHERE 1 GROUP BY [column to remove duplicates by];
Step 2: delete the old table (or rename it)
We no longer need the table with all the duplicate entries, so drop it!
DROP TABLE old_table;
Step 3: rename the new_table to the name of the old_table
RENAME TABLE new_table TO old_table;
And of course, don't forget to fix your buggy code to stop inserting duplicates!
Sum values from multiple rows using vlookup or index/match functions
You should use Ctrl+shift+enter when using the =SUM(VLOOKUP(A9,A1:D5,{2,3,4,},FALSE))
that results in {=SUM(VLOOKUP(A9,A1:D5,{2,3,4,},FALSE))} en also works.
What is copy-on-write?
I was going to write up my own explanation but this Wikipedia article pretty much sums it up.
Here is the basic concept:
Copy-on-write (sometimes referred to as "COW") is an optimization strategy used in computer programming. The fundamental idea is that if multiple callers ask for resources which are initially indistinguishable, you can give them pointers to the same resource. This function can be maintained until a caller tries to modify its "copy" of the resource, at which point a true private copy is created to prevent the changes becoming visible to everyone else. All of this happens transparently to the callers. The primary advantage is that if a caller never makes any modifications, no private copy need ever be created.
Also here is an application of a common use of COW:
The COW concept is also used in maintenance of instant snapshot on database servers like Microsoft SQL Server 2005. Instant snapshots preserve a static view of a database by storing a pre-modification copy of data when underlaying data are updated. Instant snapshots are used for testing uses or moment-dependent reports and should not be used to replace backups.
Node: log in a file instead of the console
For future users. @keshavDulal answer doesn't work for latest version. And I couldn't find a proper fix for the issues that are reporting in the latest version 3.3.3
.
Anyway I finally fixed it after researching a bit. Here is the solution for winston version 3.3.3
Install winston and winston-daily-rotate-file
npm install winston
npm install winston-daily-rotate-file
Create a new file utils/logger.js
const winston = require('winston');
const winstonRotator = require('winston-daily-rotate-file');
var logger = new winston.createLogger({
transports: [
new (winston.transports.DailyRotateFile)({
name: 'access-file',
level: 'info',
filename: './logs/access.log',
json: false,
datePattern: 'yyyy-MM-DD',
prepend: true,
maxFiles: 10
}),
new (winston.transports.DailyRotateFile)({
name: 'error-file',
level: 'error',
filename: './logs/error.log',
json: false,
datePattern: 'yyyy-MM-DD',
prepend: true,
maxFiles: 10
})
]
});
module.exports = {
logger
};
Then in any file where you want to use logging import the module like
const logger = require('./utils/logger').logger;
Use logger like the following:
logger.info('Info service started');
logger.error('Service crashed');
How to implement the Java comparable interface?
You just have to define that Animal implements Comparable<Animal>
i.e. public class Animal implements Comparable<Animal>
. And then you have to implement the compareTo(Animal other)
method that way you like it.
@Override
public int compareTo(Animal other) {
return Integer.compare(this.year_discovered, other.year_discovered);
}
Using this implementation of compareTo
, animals with a higher year_discovered
will get ordered higher. I hope you get the idea of Comparable
and compareTo
with this example.
How do I make a stored procedure in MS Access?
Access 2010 has both stored procedures, and also has table triggers. And, both features are available even when you not using a server (so, in 100% file based mode).
If you using SQL Server with Access, then of course the stored procedures are built using SQL Server and not Access.
For Access 2010, you open up the table (non-design view), and then choose the table tab. You see options there to create store procedures and table triggers.
For example:
Note that the stored procedure language is its own flavor just like Oracle or SQL Server (T-SQL). Here is example code to update an inventory of fruits as a result of an update in the fruit order table
Keep in mind these are true engine-level table triggers. In fact if you open up that table with VB6, VB.NET, FoxPro or even modify the table on a computer WITHOUT Access having been installed, the procedural code and the trigger at the table level will execute. So, this is a new feature of the data engine jet (now called ACE) for Access 2010. As noted, this is procedural code that runs, not just a single statement.
How to call Stored Procedure in Entity Framework 6 (Code-First)?
I found that calling of stored procedures in code-first approach is not convenient.
I prefer to use Dapper
instead.
The following code was written with Entity Framework:
var clientIdParameter = new SqlParameter("@ClientId", 4);
var result = context.Database
.SqlQuery<ResultForCampaign>("GetResultsForCampaign @ClientId", clientIdParameter)
.ToList();
The following code was written with Dapper
:
return Database.Connection.Query<ResultForCampaign>(
"GetResultsForCampaign ",
new
{
ClientId = 4
},
commandType: CommandType.StoredProcedure);
I believe the second piece of code is simpler to understand.
How can I turn a DataTable to a CSV?
To mimic Excel CSV:
public static string Convert(DataTable dt)
{
StringBuilder sb = new StringBuilder();
IEnumerable<string> columnNames = dt.Columns.Cast<DataColumn>().
Select(column => column.ColumnName);
sb.AppendLine(string.Join(",", columnNames));
foreach (DataRow row in dt.Rows)
{
IEnumerable<string> fields = row.ItemArray.Select(field =>
{
string s = field.ToString().Replace("\"", "\"\"");
if(s.Contains(','))
s = string.Concat("\"", s, "\"");
return s;
});
sb.AppendLine(string.Join(",", fields));
}
return sb.ToString().Trim();
}
Subtracting two lists in Python
Python 2.7 and 3.2 added the collections.Counter
class, which is a dictionary subclass that maps elements to the number of occurrences of the element. This can be used as a multiset. You can do something like this:
from collections import Counter
a = Counter([0, 1, 2, 1, 0])
b = Counter([0, 1, 1])
c = a - b # ignores items in b missing in a
print(list(c.elements())) # -> [0, 2]
As well, if you want to check that every element in b
is in a
:
# a[key] returns 0 if key not in a, instead of raising an exception
assert all(a[key] >= b[key] for key in b)
But since you are stuck with 2.5, you could try importing it and define your own version if that fails. That way you will be sure to get the latest version if it is available, and fall back to a working version if not. You will also benefit from speed improvements if if gets converted to a C implementation in the future.
try:
from collections import Counter
except ImportError:
class Counter(dict):
...
You can find the current Python source here.
how can I set visible back to true in jquery
Using ASP.NET's visible="false"
property will set the visibility
attribute where as I think when you call show()
in jQuery it modifies the display
attribute of the CSS style.
So doing the latter won't rectify the former.
You need to do this:
$("#test1").attr("visibility", "visible");
How to downgrade php from 5.5 to 5.3
I did this in my local environment. Wasn't difficult but obviously it was done in "unsupported" way.
To do the downgrade you need just to download php 5.3 from http://php.net/releases/ (zip archive), than go to xampp folder and copy subfolder "php" to e.g. php5.5 (just for backup). Than remove content of the folder php and unzip content of zip archive downloaded from php.net. The next step is to adjust configuration (php.ini) - you can refer to your backed-up version from php 5.5. After that just run xampp control utility - everything should work (at least worked in my local environment). I didn't found any problem with such installation, although I didn't tested this too intensively.
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.
Two models in one view in ASP MVC 3
If you are a fan of having very flat models, just to support the view, you should create a model specific to this particular view...
public class EditViewModel
public int PersonID { get; set; }
public string PersonName { get; set; }
public int OrderID { get; set; }
public int TotalSum { get; set; }
}
Many people use AutoMapper to map from their domain objects to their flat views.
The idea of the view model is that it just supports the view - nothing else. You have one per view to ensure that it only contains what is required for that view - not loads of properties that you want for other views.
Handling the null value from a resultset in JAVA
output = rs.getString("column");// if data is null `output` would be null, so there is no chance of NPE unless `rs` is `null`
if(output == null){// if you fetched null value then initialize output with blank string
output= "";
}
DataGridView.Clear()
I don't like messing with the DataSource personally so after discussing the issue with an IT friend I was able to discover this way which is simple and doesn't effect the DataSource. Hope this helps!
foreach (DataGridViewRow row in dataGridView1.Rows)
{
foreach (DataGridViewCell cell in row.Cells)
{
cell.Value = "";
}
}
Extract time from date String
Use SimpleDateFormat
to convert between a date string and a real Date
object. with a Date
as starting point, you can easily apply formatting based on various patterns as definied in the javadoc of the SimpleDateFormat
(click the blue code link for the Javadoc).
Here's a kickoff example:
String originalString = "2010-07-14 09:00:02";
Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(originalString);
String newString = new SimpleDateFormat("H:mm").format(date); // 9:00
Find duplicate records in MySQL
This also will show you how many duplicates have and will order the results without joins
SELECT `Language` , id, COUNT( id ) AS how_many
FROM `languages`
GROUP BY `Language`
HAVING how_many >=2
ORDER BY how_many DESC
How using try catch for exception handling is best practice
I can tell you something:
Snippet #1 is not acceptable because it's ignoring exception. (it's swallowing it like nothing happened).
So do not add catch block that do nothing or just rethrows.
Catch block should add some value. For example output message to end user or log error.
Do not use exception for normal flow program logic. For example:
e.g input validation. <- This is not valid exceptional situation, rather you should write method IsValid(myInput);
to check whether input item is valid or not.
Design code to avoid exception. For example:
int Parse(string input);
If we pass value that cannot be parsed to int, this method would throw and exception, instead of that we might write something like this:
bool TryParse(string input,out int result);
<- this method would return boolean indicating if parse was successfull.
Maybe this is little bit out of scope of this question, but I hope this will help you to make right decisions when it's about try {} catch(){}
and exceptions.
SQL to find the number of distinct values in a column
Count(distinct({fieldname})) is redundant
Simply Count({fieldname}) gives you all the distinct values in that table. It will not (as many presume) just give you the Count of the table [i.e. NOT the same as Count(*) from table]
importing a CSV into phpmyadmin
In phpMyAdmin, click the table, and then click the Import tab at the top of the page.
Browse and open the csv file. Leave the charset as-is. Uncheck partial import unless you have a HUGE dataset (or slow server). The format should already have selected “CSV” after selecting your file, if not then select it (not using LOAD DATA). If you want to clear the whole table before importing, check “Replace table data with file”. Optionally check “Ignore duplicate rows” if you think you have duplicates in the CSV file. Now the important part, set the next four fields to these values:
Fields terminated by: ,
Fields enclosed by: “
Fields escaped by: \
Lines terminated by: auto
Currently these match the defaults except for “Fields terminated by”, which defaults to a semicolon.
Now click the Go button, and it should run successfully.
Format certain floating dataframe columns into percentage in pandas
Often times we are interested in calculating the full significant digits, but
for the visual aesthetics, we may want to see only few decimal point when we display the dataframe.
In jupyter-notebook, pandas can utilize the html formatting taking advantage of the method called style
.
For the case of just seeing two significant digits of some columns, we can use this code snippet:
Given dataframe
import numpy as np
import pandas as pd
df = pd.DataFrame({'var1': [1.458315, 1.576704, 1.629253, 1.6693310000000001, 1.705139, 1.740447, 1.77598, 1.812037, 1.85313, 1.9439849999999999],
'var2': [1.500092, 1.6084450000000001, 1.652577, 1.685456, 1.7120959999999998, 1.741961, 1.7708009999999998, 1.7993270000000001, 1.8229819999999999, 1.8684009999999998],
'var3': [-0.0057090000000000005, -0.005122, -0.0047539999999999995, -0.003525, -0.003134, -0.0012230000000000001, -0.0017230000000000001, -0.002013, -0.001396, 0.005732]})
print(df)
var1 var2 var3
0 1.458315 1.500092 -0.005709
1 1.576704 1.608445 -0.005122
2 1.629253 1.652577 -0.004754
3 1.669331 1.685456 -0.003525
4 1.705139 1.712096 -0.003134
5 1.740447 1.741961 -0.001223
6 1.775980 1.770801 -0.001723
7 1.812037 1.799327 -0.002013
8 1.853130 1.822982 -0.001396
9 1.943985 1.868401 0.005732
Style to get required format
df.style.format({'var1': "{:.2f}",'var2': "{:.2f}",'var3': "{:.2%}"})
Gives:
var1 var2 var3
id
0 1.46 1.50 -0.57%
1 1.58 1.61 -0.51%
2 1.63 1.65 -0.48%
3 1.67 1.69 -0.35%
4 1.71 1.71 -0.31%
5 1.74 1.74 -0.12%
6 1.78 1.77 -0.17%
7 1.81 1.80 -0.20%
8 1.85 1.82 -0.14%
9 1.94 1.87 0.57%
Update
If display command is not found try following:
from IPython.display import display
df_style = df.style.format({'var1': "{:.2f}",'var2': "{:.2f}",'var3': "{:.2%}"})
display(df_style)
Requirements
- To use
display
command, you need to have installed Ipython in your machine.
- The
display
command does not work in online python interpreter which do not have IPyton
installed such as https://repl.it/languages/python3
- The display command works in jupyter-notebook, jupyter-lab, Google-colab, kaggle-kernels, IBM-watson,Mode-Analytics and many other platforms out of the box, you do not even have to import display from IPython.display
How to test if parameters exist in rails
Simple as pie:
if !params[:one].nil? and !params[:two].nil?
#do something...
elsif !params[:one].nil?
#do something else...
elsif !params[:two].nil?
#do something extraordinary...
end
Switch on ranges of integers in JavaScript
Here is another way I figured it out:
const x = this.dealer;
switch (true) {
case (x < 5):
alert("less than five");
break;
case (x < 9):
alert("between 5 and 8");
break;
case (x < 12):
alert("between 9 and 11");
break;
default:
alert("none");
break;
}
Why should I use var instead of a type?
As the others have said, there is no difference in the compiled code (IL) when you use either of the following:
var x1 = new object();
object x2 = new object;
I suppose Resharper warns you because it is [in my opinion] easier to read the first example than the second. Besides, what's the need to repeat the name of the type twice?
Consider the following and you'll get what I mean:
KeyValuePair<string, KeyValuePair<string, int>> y1 = new KeyValuePair<string, KeyValuePair<string, int>>("key", new KeyValuePair<string, int>("subkey", 5));
It's way easier to read this instead:
var y2 = new KeyValuePair<string, KeyValuePair<string, int>>("key", new KeyValuePair<string, int>("subkey", 5));
Why write <script type="text/javascript"> when the mime type is set by the server?
Because, at least in HTML 4.01 and XHTML 1(.1), the type
attribute for <script>
elements is required.
In HTML 5, type
is no longer required.
In fact, while you should use text/javascript
in your HTML source, many servers will send the file with Content-type: application/javascript
. Read more about these MIME types in RFC 4329.
Notice the difference between RFC 4329, that marked text/javascript
as obsolete and recommending the use of application/javascript
, and the reality in which some browsers freak out on <script>
elements containing type="application/javascript"
(in HTML source, not the HTTP Content-type header of the file that gets send). Recently, there was a discussion on the WHATWG mailing list about this discrepancy (HTML 5's type
defaults to text/javascript
), read these messages with subject Will you consider about RFC 4329?
find_spec_for_exe': can't find gem bundler (>= 0.a) (Gem::GemNotFoundException)
The real answer is here if you try to install bundler 2.0.1 or 2.0.0 due to Bundler requiring RubyGems v3.0.0
Yesterday I released Bundler 2.0 that introduced a number of breaking changes. One of the those changes was setting Bundler to require RubyGems v3.0.0. After making the release, it has become clear that lots of our users are running into issues with Bundler 2 requiring a really new version of RubyGems.
We have been listening closely to feedback from users and have decided to relax the RubyGems requirement to v2.5.0 at minimum. We have released a new Bundler version, v2.0.1, that adjusts this requirement.
For more info, see: https://bundler.io/blog/2019/01/04/an-update-on-the-bundler-2-release.html
Set up a scheduled job?
Simple way is to write a custom shell command see Django Documentation and execute it using a cronjob on linux. However i would highly recommend using a message broker like RabbitMQ coupled with celery. Maybe you can have a look at
this Tutorial
In practice, what are the main uses for the new "yield from" syntax in Python 3.3?
Let's get one thing out of the way first. The explanation that yield from g
is equivalent to for v in g: yield v
does not even begin to do justice to what yield from
is all about. Because, let's face it, if all yield from
does is expand the for
loop, then it does not warrant adding yield from
to the language and preclude a whole bunch of new features from being implemented in Python 2.x.
What yield from
does is it establishes a transparent bidirectional connection between the caller and the sub-generator:
The connection is "transparent" in the sense that it will propagate everything correctly too, not just the elements being generated (e.g. exceptions are propagated).
The connection is "bidirectional" in the sense that data can be both sent from and to a generator.
(If we were talking about TCP, yield from g
might mean "now temporarily disconnect my client's socket and reconnect it to this other server socket".)
BTW, if you are not sure what sending data to a generator even means, you need to drop everything and read about coroutines first—they're very useful (contrast them with subroutines), but unfortunately lesser-known in Python. Dave Beazley's Curious Course on Coroutines is an excellent start. Read slides 24-33 for a quick primer.
Reading data from a generator using yield from
def reader():
"""A generator that fakes a read from a file, socket, etc."""
for i in range(4):
yield '<< %s' % i
def reader_wrapper(g):
# Manually iterate over data produced by reader
for v in g:
yield v
wrap = reader_wrapper(reader())
for i in wrap:
print(i)
# Result
<< 0
<< 1
<< 2
<< 3
Instead of manually iterating over reader()
, we can just yield from
it.
def reader_wrapper(g):
yield from g
That works, and we eliminated one line of code. And probably the intent is a little bit clearer (or not). But nothing life changing.
Sending data to a generator (coroutine) using yield from - Part 1
Now let's do something more interesting. Let's create a coroutine called writer
that accepts data sent to it and writes to a socket, fd, etc.
def writer():
"""A coroutine that writes data *sent* to it to fd, socket, etc."""
while True:
w = (yield)
print('>> ', w)
Now the question is, how should the wrapper function handle sending data to the writer, so that any data that is sent to the wrapper is transparently sent to the writer()
?
def writer_wrapper(coro):
# TBD
pass
w = writer()
wrap = writer_wrapper(w)
wrap.send(None) # "prime" the coroutine
for i in range(4):
wrap.send(i)
# Expected result
>> 0
>> 1
>> 2
>> 3
The wrapper needs to accept the data that is sent to it (obviously) and should also handle the StopIteration
when the for loop is exhausted. Evidently just doing for x in coro: yield x
won't do. Here is a version that works.
def writer_wrapper(coro):
coro.send(None) # prime the coro
while True:
try:
x = (yield) # Capture the value that's sent
coro.send(x) # and pass it to the writer
except StopIteration:
pass
Or, we could do this.
def writer_wrapper(coro):
yield from coro
That saves 6 lines of code, make it much much more readable and it just works. Magic!
Sending data to a generator yield from - Part 2 - Exception handling
Let's make it more complicated. What if our writer needs to handle exceptions? Let's say the writer
handles a SpamException
and it prints ***
if it encounters one.
class SpamException(Exception):
pass
def writer():
while True:
try:
w = (yield)
except SpamException:
print('***')
else:
print('>> ', w)
What if we don't change writer_wrapper
? Does it work? Let's try
# writer_wrapper same as above
w = writer()
wrap = writer_wrapper(w)
wrap.send(None) # "prime" the coroutine
for i in [0, 1, 2, 'spam', 4]:
if i == 'spam':
wrap.throw(SpamException)
else:
wrap.send(i)
# Expected Result
>> 0
>> 1
>> 2
***
>> 4
# Actual Result
>> 0
>> 1
>> 2
Traceback (most recent call last):
... redacted ...
File ... in writer_wrapper
x = (yield)
__main__.SpamException
Um, it's not working because x = (yield)
just raises the exception and everything comes to a crashing halt. Let's make it work, but manually handling exceptions and sending them or throwing them into the sub-generator (writer
)
def writer_wrapper(coro):
"""Works. Manually catches exceptions and throws them"""
coro.send(None) # prime the coro
while True:
try:
try:
x = (yield)
except Exception as e: # This catches the SpamException
coro.throw(e)
else:
coro.send(x)
except StopIteration:
pass
This works.
# Result
>> 0
>> 1
>> 2
***
>> 4
But so does this!
def writer_wrapper(coro):
yield from coro
The yield from
transparently handles sending the values or throwing values into the sub-generator.
This still does not cover all the corner cases though. What happens if the outer generator is closed? What about the case when the sub-generator returns a value (yes, in Python 3.3+, generators can return values), how should the return value be propagated? That yield from
transparently handles all the corner cases is really impressive. yield from
just magically works and handles all those cases.
I personally feel yield from
is a poor keyword choice because it does not make the two-way nature apparent. There were other keywords proposed (like delegate
but were rejected because adding a new keyword to the language is much more difficult than combining existing ones.
In summary, it's best to think of yield from
as a transparent two way channel
between the caller and the sub-generator.
References:
- PEP 380 - Syntax for delegating to a sub-generator (Ewing) [v3.3, 2009-02-13]
- PEP 342 -
Coroutines via Enhanced Generators (GvR, Eby) [v2.5, 2005-05-10]
When to use "ON UPDATE CASCADE"
It's an excellent question, I had the same question yesterday. I thought about this problem, specifically SEARCHED if existed something like "ON UPDATE CASCADE" and fortunately the designers of SQL had also thought about that. I agree with Ted.strauss, and I also commented Noran's case.
When did I use it? Like Ted pointed out, when you are treating several databases at one time, and the modification in one of them, in one table, has any kind of reproduction in what Ted calls "satellite database", can't be kept with the very original ID, and for any reason you have to create a new one, in case you can't update the data on the old one (for example due to permissions, or in case you are searching for fastness in a case that is so ephemeral that doesn't deserve the absolute and utter respect for the total rules of normalization, simply because will be a very short-lived utility)
So, I agree in two points:
(A.) Yes, in many times a better design can avoid it; BUT
(B.) In cases of migrations, replicating databases, or solving emergencies, it's a GREAT TOOL that fortunately was there when I went to search if it existed.
Windows 7 environment variable not working in path
I had exactly the same problem, to solve it, you can do one of two things:
- Put all variables in System Variables instead of User and add the ones you want to PATH
Or
- Put all variables in User Variables, and create or edit the PATH variables in User Variable, not In System. The Path variables in System don't expand the User Variables.
If the above are all correct, but the problem is still present, you need to check the system Registry, in HKEY_CURRENT_USER\Environment, to make sure the "PATH" key type is REG_EXPAND_SZ (not REG_SZ).
Error: [ng:areq] from angular controller
I got this same error when I included the entire controller file name in the Routes like this:
app.config(function($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'home.html',
controller: 'mainController.js'
})
.when('/portfolio', {
templateUrl: 'portfolio.html',
controller: 'mainController.js'
})
});
When it should be
app.config(function($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'home.html',
controller: 'mainController'
})
.when('/portfolio', {
templateUrl: 'portfolio.html',
controller: 'mainController'
})
});
Angular takes certain things you name like the app and controller and expounds on them in directives and across your app, take care to name everything consistently and check for this when debugging
Error: Uncaught (in promise): Error: Cannot match any routes Angular 2
If you are passing id through url please use below
imports: [
BrowserModule,
FormsModule,
HttpModule,
RouterModule.forRoot([
{ path: 'Employees', component: EmployeesComponent, pathMatch: 'full' },
{ path: 'Add', component: EmployeeAddComponent, pathMatch: 'full' },
**{ path: 'Edit/:id', component: EmployeeEditComponent },
{ path: 'Edit', component: EmployeeEditComponent },**
{ path: '', redirectTo: 'Employees', pathMatch: 'full' }
]),
],
i.e If you are passing any id we need to both url edit with id and edit url alone
Angular bootstrap datepicker date format does not format ng-model value
You may use formatters after picking value inside your datepicker directive.
For example
angular.module('foo').directive('bar', function() {
return {
require: '?ngModel',
link: function(scope, elem, attrs, ctrl) {
if (!ctrl) return;
ctrl.$formatters.push(function(value) {
if (value) {
// format and return date here
}
return undefined;
});
}
};
});
LINK.
Writing files in Node.js
Synchronous Write
fs.writeFileSync(file, data[, options])
fs = require('fs');
fs.writeFileSync("foo.txt", "bar");
Asynchronous Write
fs.writeFile(file, data[, options], callback)
fs = require('fs');
fs.writeFile('foo.txt', 'bar', (err) => { if (err) throw err; });
Where
file <string> | <Buffer> | <URL> | <integer> filename or file descriptor
data <string> | <Buffer> | <Uint8Array>
options <Object> | <string>
callback <Function>
Worth reading the offical File System (fs) docs.
Update: async/await
fs = require('fs');
util = require('util');
writeFile = util.promisify(fs.writeFile);
fn = async () => { await writeFile('foo.txt', 'bar'); }
fn()
clear table jquery
Having a table like this (with a header and a body)
<table id="myTableId">
<thead>
</thead>
<tbody>
</tbody>
</table>
remove every tr having a parent called tbody inside the #tableId
$('#tableId tbody > tr').remove();
and in reverse if you want to add to your table
$('#tableId tbody').append("<tr><td></td>....</tr>");
How to get the current working directory using python 3?
Using pathlib you can get the folder in which the current file is located. __file__
is the pathname of the file from which the module was loaded.
Ref: docs
import pathlib
current_dir = pathlib.Path(__file__).parent
current_file = pathlib.Path(__file__)
Doc ref: link
Changing three.js background to transparent or other color
I came across this when I started using three.js as well. It's actually a javascript issue. You currently have:
renderer.setClearColorHex( 0x000000, 1 );
in your threejs
init function. Change it to:
renderer.setClearColorHex( 0xffffff, 1 );
Update: Thanks to HdN8 for the updated solution:
renderer.setClearColor( 0xffffff, 0);
Update #2: As pointed out by WestLangley in another, similar question - you must now use the below code when creating a new WebGLRenderer instance in conjunction with the setClearColor()
function:
var renderer = new THREE.WebGLRenderer({ alpha: true });
Update #3: Mr.doob points out that since r78
you can alternatively use the code below to set your scene's background colour:
var scene = new THREE.Scene(); // initialising the scene
scene.background = new THREE.Color( 0xff0000 );
Logarithmic returns in pandas dataframe
@poulter7:
I cannot comment on the other answers, so I post it as new answer: be careful with
np.log(df.price).diff()
as this will fail for indices which can become negative as well as risk factors e.g. negative interest rates. In these cases
np.log(df.price/df.price.shift(1)).dropna()
is preferred and based on my experience generally the safer approach. It also evaluates the logarithm only once.
Whether you use +1 or -1 depends on the ordering of your time series. Use -1 for descending and +1 for ascending dates - in both cases the shift provides the preceding date's value.
read word by word from file in C++
First of all, don't loop while (!eof())
, it will not work as you expect it to because the eofbit
will not be set until after a failed read due to end of file.
Secondly, the normal input operator >>
separates on whitespace and so can be used to read "words":
std::string word;
while (file >> word)
{
...
}
Twitter Bootstrap Datepicker within modal window
// re initialze datepicker
$(".bootstrap-datepicker").bsdatepicker({
format: "yyyy-mm-dd",
autoclose: true,
}).on('changeDate', function (ev) {
$(this).bsdatepicker('hide');
});
//
$(".dropdown-menu").css({'z-index':'1100'});
What's causing my java.net.SocketException: Connection reset?
If you experience this trying to access Web services deployed on a Glassfish3 server, you might want to tune your http-thread-pool settings. That fixed SocketExceptions we had when many concurrent threads was calling the web service.
- Go to admin console
- Navigate to "Configurations"->"Server config"->"Thread pools"->"http-thread-pool".
- Change setting "Max Thread Pool Size" from 5 to 32
- Change setting "Min Thread Pool Size" from 2 to 16
- Restart Glassfish.
Device not detected in Eclipse when connected with USB cable
After a long and frustrating search, finally I made my Micromax Funbook p362 to connect with eclipse and made it to suit for development.
*Installed Moborobo (All in one Android smart phone management tool).
*Perform stop -server / start -server using ADB.
*Reboot the device.
*Restart the eclipse.
*Device got detected.(Eclipse - list of adb devices)
Work on a remote project with Eclipse via SSH
This answer currently only applies to using two Linux computers [or maybe works on Mac too?--untested on Mac] (syncing from one to the other) because I wrote this synchronization script in bash. It is simply a wrapper around git
, however, so feel free to take it and convert it into a cross-platform Python solution or something if you wish
This doesn't directly answer the OP's question, but it is so close I guarantee it will answer many other peoples' question who land on this page (mine included, actually, as I came here first before writing my own solution), so I'm posting it here anyway.
I want to:
- develop code using a powerful IDE like Eclipse on a light-weight Linux computer, then
- build that code via ssh on a different, more powerful Linux computer (from the command-line, NOT from inside Eclipse)
Let's call the first computer where I write the code "PC1" (Personal Computer 1), and the 2nd computer where I build the code "PC2". I need a tool to easily synchronize from PC1 to PC2. I tried rsync
, but it was insanely slow for large repos and took tons of bandwidth and data.
So, how do I do it? What workflow should I use? If you have this question too, here's the workflow that I decided upon. I wrote a bash script to automate the process by using git
to automatically push changes from PC1 to PC2 via a remote repository, such as github. So far it works very well and I'm very pleased with it. It is far far far faster than rsync
, more trustworthy in my opinion because each PC maintains a functional git repo, and uses far less bandwidth to do the whole sync, so it's easily doable over a cell phone hot spot without using tons of your data.
Setup:
Install the script on PC1 (this solution assumes ~/bin is in your $PATH):
git clone https://github.com/ElectricRCAircraftGuy/eRCaGuy_dotfiles.git
cd eRCaGuy_dotfiles/useful_scripts
mkdir -p ~/bin
ln -s "${PWD}/sync_git_repo_from_pc1_to_pc2.sh" ~/bin/sync_git_repo_from_pc1_to_pc2
cd ..
cp -i .sync_git_repo ~/.sync_git_repo
Now edit the "~/.sync_git_repo" file you just copied above, and update its parameters to fit your case. Here are the parameters it contains:
# The git repo root directory on PC2 where you are syncing your files TO; this dir must *already exist*
# and you must have *already `git clone`d* a copy of your git repo into it!
# - Do NOT use variables such as `$HOME`. Be explicit instead. This is because the variable expansion will
# happen on the local machine when what we need is the variable expansion from the remote machine. Being
# explicit instead just avoids this problem.
PC2_GIT_REPO_TARGET_DIR="/home/gabriel/dev/eRCaGuy_dotfiles" # explicitly type this out; don't use variables
PC2_SSH_USERNAME="my_username" # explicitly type this out; don't use variables
PC2_SSH_HOST="my_hostname" # explicitly type this out; don't use variables
Git clone your repo you want to sync on both PC1 and PC2.
- Ensure your ssh keys are all set up to be able to push and pull to the remote repo from both PC1 and PC2. Here's some helpful links:
- https://help.github.com/en/github/authenticating-to-github/connecting-to-github-with-ssh
- https://help.github.com/en/github/authenticating-to-github/generating-a-new-ssh-key-and-adding-it-to-the-ssh-agent
- Ensure your ssh keys are all set up to ssh from PC1 to PC2.
Now cd
into any directory within the git repo on PC1, and run:
sync_git_repo_from_pc1_to_pc2
That's it! About 30 seconds later everything will be magically synced from PC1 to PC2, and it will be printing output the whole time to tell you what it's doing and where it's doing it on your disk and on which computer. It's safe too, because it doesn't overwrite or delete anything that is uncommitted. It backs it up first instead! Read more below for how that works.
Here's the process this script uses (ie: what it's actually doing)
- From PC1: It checks to see if any uncommitted changes are on PC1. If so, it commits them to a temporary commit on the current branch. It then force pushes them to a remote SYNC branch. Then it uncommits its temporary commit it just did on the local branch, then it puts the local git repo back to exactly how it was by staging any files that were previously staged at the time you called the script. Next, it
rsync
s a copy of the script over to PC2, and does an ssh
call to tell PC2 to run the script with a special option to just do PC2 stuff.
- Here's what PC2 does: it
cd
s into the repo, and checks to see if any local uncommitted changes exist. If so, it creates a new backup branch forked off of the current branch (sample name: my_branch_SYNC_BAK_20200220-0028hrs-15sec
<-- notice that's YYYYMMDD-HHMMhrs--SSsec), and commits any uncommitted changes to that branch with a commit message such as DO BACKUP OF ALL UNCOMMITTED CHANGES ON PC2 (TARGET PC/BUILD MACHINE). Now, it checks out the SYNC branch, pulling it from the remote repository if it is not already on the local machine. Then, it fetches the latest changes on the remote repository, and does a hard reset to force the local SYNC repository to match the remote SYNC repository. You might call this a "hard pull". It is safe, however, because we already backed up any uncommitted changes we had locally on PC2, so nothing is lost!
- That's it! You now have produced a perfect copy from PC1 to PC2 without even having to ensure clean working directories, as the script handled all of the automatic committing and stuff for you! It is fast and works very well on huge repositories. Now you have an easy mechanism to use any IDE of your choice on one machine while building or testing on another machine, easily, over a wifi hot spot from your cell phone if needed, even if the repository is dozens of gigabytes and you are time and resource-constrained.
Resources:
- The whole project: https://github.com/ElectricRCAircraftGuy/eRCaGuy_dotfiles
- See tons more links and references in the source code itself within this project.
- How to do a "hard pull", as I call it: How do I force "git pull" to overwrite local files?
Related:
- git repository sync between computers, when moving around?
Git fetch remote branch
I have used fetch
followed by checkout
...
git fetch <remote> <rbranch>:<lbranch>
git checkout <lbranch>
...where <rbranch>
is the remote branch or source ref and <lbranch>
is the as yet non-existent local branch or destination ref you want to track and which you probably want to name the same as the remote branch or source ref. This is explained under options in the explanation of <refspec>
.
Git is so smart it auto completes the first command if I tab after the first few letters of the remote branch. That is, I don't even have to name the local branch, Git automatically copies the name of the remote branch for me. Thanks Git!
Also as the answer in this similar Stack Overflow post shows, if you don't name the local branch in fetch
, you can still create it when you check it out by using the -b
flag. That is, git fetch <remote> <branch>
followed by git checkout -b <branch> <remote>/<branch>
does exactly the same as my initial answer. And evidently, if your repository has only one remote, then you can just do git checkout <branch>
after fetch
and it will create a local branch for you. For example, you just cloned a repository and want to check out additional branches from the remote.
I believe that some of the documentation for fetch
may have been copied verbatim from pull
. In particular the section on <refspec>
in options is the same. However, I do not believe that fetch
will ever merge
, so that if you leave the destination side of the colon empty, fetch
should do nothing.
NOTE: git fetch <remote> <refspec>
is short for git fetch <remote> <refspec>:
which would therefore do nothing, but git fetch <remote> <tag>
is the same as git fetch <remote> <tag>:<tag>
which should copy the remote <tag>
locally.
I guess this is only helpful if you want to copy a remote branch locally, but not necessarily check it out right away. Otherwise, I now would use the accepted answer, which is explained in detail in the first section of the checkout description and later in the options section under the explanation of --track
, since it's a one-liner. Well... sort of a one-liner, because you would still have to run git fetch <remote>
first.
FYI: The order of the <refspecs>
(source:destination) explains the bizarre pre Git 1.7 method for deleting remote branches. That is, push nothing into the destination refspec.