How to use GROUP BY to concatenate strings in SQL Server?
An example would be
In Oracle you can use LISTAGG aggregate function.
Original records
name type
------------
name1 type1
name2 type2
name2 type3
Sql
SELECT name, LISTAGG(type, '; ') WITHIN GROUP(ORDER BY name)
FROM table
GROUP BY name
Result in
name type
------------
name1 type1
name2 type2; type3
Viewing all `git diffs` with vimdiff
Git accepts kdiff3, tkdiff, meld, xxdiff, emerge, vimdiff, gvimdiff, ecmerge,
and opendiff as valid diff tools. You can also set up a custom tool.
git config --global diff.tool vimdiff
git config --global diff.tool kdiff3
git config --global diff.tool meld
git config --global diff.tool xxdiff
git config --global diff.tool emerge
git config --global diff.tool gvimdiff
git config --global diff.tool ecmerge
Maximum and Minimum values for ints
If you want the max for array or list indices (equivalent to size_t
in C/C++), you can use numpy:
np.iinfo(np.intp).max
This is same as sys.maxsize
however advantage is that you don't need import sys just for this.
If you want max for native int on the machine:
np.iinfo(np.intc).max
You can look at other available types in doc.
For floats you can also use sys.float_info.max
.
How do change the color of the text of an <option> within a <select>?
You can't have HTML code inside the options, they can only contain text, but you can apply the class to the option instead:
<option selected="selected" class="grey_color">select one option</option>
Demo: http://jsfiddle.net/Guffa/hUpAB/9/
Note:
- The support for styling options varies between browsers. In modern brosers you generally can expect support for coloring but not for font size. A browser in a phone for example usually doesn't display the options in a dropdown, so the styling would not be relevant at all.
- You should not have
html
and head
tags in the HTML code in jsfiddle.
- You should name your classes for what the represent, not how they look.
Wrapping long text without white space inside of a div
You can use the following
p{word-break: break-all;}
<p>LoremipsumdolorLoremipsumdolorLoremipsumdolorLoremipsumdolorLoremipsumdolorLoremipsumdolorLoremipsumdolorLoremipsumdolorLoremipsumdolorLoremipsumdolorLoremipsumdolorLoremipsumdolorLoremipsumdolorLoremipsumdolorLoremipsumdolorLoremipsumdolorLoremipsumdolorLoremipsumdolorLoremipsumdolorLoremipsumdolorLoremipsumdolorLoremipsumdolorLoremipsumdolorLoremipsumdolorLoremipsumdolorLoremipsumdolorLoremipsumdolorLoremipsumdolorLoremipsumdolorLoremipsumdolorLoremipsumdolorLoremipsumdolorLoremipsumdolorLoremipsumdolorLoremipsumdolor</p>
Call parent method from child class c#
To follow up on the comment by suhendri to Rory McCrossan answer. Here is an Action delegate example:
In child add:
public Action UpdateProgress; // In place of event handler declaration
// declare an Action delegate
.
.
.
private LoadData() {
this.UpdateProgress(); // call to Action delegate - MyMethod in
// parent
}
In parent add:
// The 3 lines in the parent becomes:
ChildClass child = new ChildClass();
child.UpdateProgress = this.MyMethod; // assigns MyMethod to child delegate
Cannot get a text value from a numeric cell “Poi”
Formatter will work fine in this case.
import org.apache.poi.ss.usermodel.DataFormatter;
FileInputStream fis = new FileInputStream(workbookName);
Workbook workbook = WorkbookFactory.create(fis);
Sheet sheet = workbook.getSheet(sheetName);
DataFormatter formatter = new DataFormatter();
String val = formatter.formatCellValue(sheet.getRow(row).getCell(col));
list.add(val); //Adding value to list
PostgreSQL CASE ... END with multiple conditions
This kind of code perhaps should work for You
SELECT
*,
CASE
WHEN (pvc IS NULL OR pvc = '') AND (datepose < 1980) THEN '01'
WHEN (pvc IS NULL OR pvc = '') AND (datepose >= 1980) THEN '02'
WHEN (pvc IS NULL OR pvc = '') AND (datepose IS NULL OR datepose = 0) THEN '03'
ELSE '00'
END AS modifiedpvc
FROM my_table;
gid | datepose | pvc | modifiedpvc
-----+----------+-----+-------------
1 | 1961 | 01 | 00
2 | 1949 | | 01
3 | 1990 | 02 | 00
1 | 1981 | | 02
1 | | 03 | 00
1 | | | 03
(6 rows)
Why is Thread.Sleep so harmful
I have a use case that I don't quite see covered here, and will argue that this is a valid reason to use Thread.Sleep():
In a console application running cleanup jobs, I need to make a large amount of fairly expensive database calls, to a DB shared by thousands of concurrent users. In order to not hammer the DB and exclude others for hours, I'll need a pause between calls, in the order of 100 ms. This is not related to timing, just to yielding access to the DB for other threads.
Spending 2000-8000 cycles on context switching between calls that may take 500 ms to execute is benign, as does having 1 MB of stack for the thread, which runs as a single instance on a server.
Convert php array to Javascript
I had the same problem and this is how i done it.
/*PHP FILE*/
<?php
$data = file_get_contents('http://yourrssdomain.com/rss');
$data = simplexml_load_string($data);
$articles = array();
foreach($data->channel->item as $item){
$articles[] = array(
'title' => (string)$item->title,
'description' => (string)$item ->description,
'link' => (string)$item ->link,
'guid' => (string)$item ->guid,
'pubdate' => (string)$item ->pubDate,
'category' => (string)$item ->category,
);
}
// IF YOU PRINT_R THE ARTICLES ARRAY YOU WILL GET THE SAME KIND OF ARRAY THAT YOU ARE GETTING SO I CREATE AN OUTPUT STING AND WITH A FOR LOOP I ADD SOME CHARACTERS TO SPLIT LATER WITH JAVASCRIPT
$output="";
for($i = 0; $i < sizeof($articles); $i++){
//# Items
//| Attributes
if($i != 0) $output.="#"; /// IF NOT THE FIRST
// IF NOT THE FIRST ITEM ADD '#' TO SEPARATE EACH ITEM AND THEN '|' TO SEPARATE EACH ATTRIBUTE OF THE ITEM
$output.=$articles[$i]['title']."|";
$output.=$articles[$i]['description']."|";
$output.=$articles[$i]['link']."|";
$output.=$articles[$i]['guid']."|";
$output.=$articles[$i]['pubdate']."|";
$output.=$articles[$i]['category'];
}
echo $output;
?>
/* php file */
/*AJAX COMUNICATION*/
$(document).ready(function(e) {
/*AJAX COMUNICATION*/
var prodlist= [];
var attrlist= [];
$.ajax({
type: "get",
url: "php/fromupnorthrss.php",
data: {feeding: "feedstest"},
}).done(function(data) {
prodlist= data.split('#');
for(var i = 0; i < prodlist.length; i++){
attrlist= prodlist[i].split('|');
alert(attrlist[0]); /// NOW I CAN REACH EACH ELEMENT HOW I WANT TO.
}
});
});
I hope it helps.
How to replace NA values in a table for selected columns
For a specific column, there is an alternative with sapply
DF <- data.frame(A = letters[1:5],
B = letters[6:10],
C = c(2, 5, NA, 8, NA))
DF_NEW <- sapply(seq(1, nrow(DF)),
function(i) ifelse(is.na(DF[i,3]) ==
TRUE,
0,
DF[i,3]))
DF[,3] <- DF_NEW
DF
Oracle - What TNS Names file am I using?
For Windows: Filemon from SysInternals will show you what files are being accessed.
Remember to set your filters so you are not overwhelmed by the chatty file system traffic.
Added: Filemon does not work with newer Windows versions, so you might have to use Process Monitor.
How do you use bcrypt for hashing passwords in PHP?
Current thinking: hashes should be the slowest available, not the fastest possible. This suppresses rainbow table attacks.
Also related, but precautionary: An attacker should never have unlimited access to your login screen. To prevent that: Set up an IP address tracking table that records every hit along with the URI. If more than 5 attempts to login come from the same IP address in any five minute period, block with explanation. A secondary approach is to have a two-tiered password scheme, like banks do. Putting a lock-out for failures on the second pass boosts security.
Summary: slow down the attacker by using time-consuming hash functions. Also, block on too many accesses to your login, and add a second password tier.
Attach the Source in Eclipse of a jar
I Know it is pretty late but it will be helpful for the other user, as we can do Job using three ways... as below
1)1. Atttach your source code using
i.e, Right click on the project then properties --> Java build path--> attach your source in the source tab or you can remove jar file and attach the source in the libraries tab
2. Using eclipse source Analyzer
In the eclipse market you can download the plugin java source analyzer which is used to attach the open source jar file's source code. we can achieve it after installing the plugin, by right click on the open source jar and select the attach source option.
3. Using Jadclipse in eclipse you can do it
last not the least, you can achieve the decompile your code using this plugin. it is similar way you can download the plugin from the eclipse market place and install in your eclipse.
in jadclipse view you can see your .class file to decomplile source format note here you cannot see the comment and hidden things
I think in your scenario you can use the option one and option three, I prefer option three only if i want to the source code not for the debug the code. else i ll code the option 1, as i have the source already available with.
Is the order of elements in a JSON list preserved?
"Is the order of elements in a JSON list maintained?" is not a good question. You need to ask "Is the order of elements in a JSON list maintained when doing [...] ?"
As Felix King pointed out, JSON is a textual data format. It doesn't mutate without a reason. Do not confuse a JSON string with a (JavaScript) object.
You're probably talking about operations like JSON.stringify(JSON.parse(...))
. Now the answer is: It depends on the implementation. 99%* of JSON parsers do not maintain the order of objects, and do maintain the order of arrays, but you might as well use JSON to store something like
{
"son": "David",
"daughter": "Julia",
"son": "Tom",
"daughter": "Clara"
}
and use a parser that maintains order of objects.
*probably even more :)
HTML - Alert Box when loading page
you need a tiny bit of Javascript.
<script type="text/javascript">
window.onload = function(){
alert("Hi there");
}
</script>
This is only slightly different from Adam's answer. The effective difference is that this one alerts when the browser considers the page fully loaded, while Adam's alerts when the browser scans part the <script>
tag in the text. The difference is with, for example, images, which may continue loading in parallel for a while.
How to create many labels and textboxes dynamically depending on the value of an integer variable?
Suppose you have a button that when pressed sets n to 5, you could then generate labels and textboxes on your form like so.
var n = 5;
for (int i = 0; i < n; i++)
{
//Create label
Label label = new Label();
label.Text = String.Format("Label {0}", i);
//Position label on screen
label.Left = 10;
label.Top = (i + 1) * 20;
//Create textbox
TextBox textBox = new TextBox();
//Position textbox on screen
textBox.Left = 120;
textBox.Top = (i + 1) * 20;
//Add controls to form
this.Controls.Add(label);
this.Controls.Add(textBox);
}
This will not only add them to the form but position them decently as well.
How big can a MySQL database get before performance starts to degrade
It's kind of pointless to talk about "database performance", "query performance" is a better term here. And the answer is: it depends on the query, data that it operates on, indexes, hardware, etc. You can get an idea of how many rows are going to be scanned and what indexes are going to be used with EXPLAIN syntax.
2GB does not really count as a "large" database - it's more of a medium size.
Perform debounce in React.js
If you are using redux you can do this in a very elegant way with middleware. You can define a Debounce
middleware as:
var timeout;
export default store => next => action => {
const { meta = {} } = action;
if(meta.debounce){
clearTimeout(timeout);
timeout = setTimeout(() => {
next(action)
}, meta.debounce)
}else{
next(action)
}
}
You can then add debouncing to action creators, such as:
export default debouncedAction = (payload) => ({
type : 'DEBOUNCED_ACTION',
payload : payload,
meta : {debounce : 300}
}
There's actually already middleware you can get off npm to do this for you.
Remove Project from Android Studio
The location of SDK
is incorrect, the name of one filer is with place this is creating an issue. By removing that space issue will be resolved.
old SDK
location:
C:\Users\At Tech\AppData\Local\Android\Sdk
new SDK
location:
F:\AndroidSDK\Sdk
Xcode - Warning: Implicit declaration of function is invalid in C99
The compiler wants to know the function before it can use it
just declare the function before you call it
#include <stdio.h>
int Fibonacci(int number); //now the compiler knows, what the signature looks like. this is all it needs for now
int main(int argc, const char * argv[])
{
int input;
printf("Please give me a number : ");
scanf("%d", &input);
getchar();
printf("The fibonacci number of %d is : %d", input, Fibonacci(input)); //!!!
}/* main */
int Fibonacci(int number)
{
//…
Developing for Android in Eclipse: R.java not regenerating
If your OS is Ubuntu, I can provide some suggestion:
Install or upgrade ia32-lib:
sudo apt-get upgrade ia32-libs
Check if you have the right permission on the aapt folder:
cd ANDROID/adt-bundle-linux-x86_64-20130522/sdk/build-tools/android-4.2.2
chmod 777 aapt
Start Eclipse:
sudo eclipse
Run Project -> Clean in Eclipse
What are the differences between type() and isinstance()?
A practical usage difference is how they handle booleans
:
True
and False
are just keywords that mean 1
and 0
in python. Thus,
isinstance(True, int)
and
isinstance(False, int)
both return True
. Both booleans are an instance of an integer. type()
, however, is more clever:
type(True) == int
returns False
.
Use of String.Format in JavaScript?
Here is a useful string formatting function using regular expressions and captures:
function format (fmtstr) {
var args = Array.prototype.slice.call(arguments, 1);
return fmtstr.replace(/\{(\d+)\}/g, function (match, index) {
return args[index];
});
}
Strings can be formatted like C# String.Format:
var str = format('{0}, {1}!', 'Hello', 'world');
console.log(str); // prints "Hello, world!"
the format will place the correct variable in the correct spot, even if they appear out of order:
var str = format('{1}, {0}!', 'Hello', 'world');
console.log(str); // prints "world, Hello!"
Hope this helps!
How to activate "Share" button in android app?
Share Any File as below ( Kotlin ) :
first create a folder named xml
in the res
folder and create a new XML Resource File named provider_paths.xml
and put the below code inside it :
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<files-path
name="files"
path="."/>
<external-path
name="external_files"
path="."/>
</paths>
now go to the manifests
folder and open the AndroidManifest.xml
and then put the below code inside the <application>
tag :
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/provider_paths" /> // provider_paths.xml file path in this example
</provider>
now you put the below code in the setOnLongClickListener
:
share_btn.setOnClickListener {
try {
val file = File("pathOfFile")
if(file.exists()) {
val uri = FileProvider.getUriForFile(this, BuildConfig.APPLICATION_ID + ".provider", file)
val intent = Intent(Intent.ACTION_SEND)
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
intent.setType("*/*")
intent.putExtra(Intent.EXTRA_STREAM, uri)
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent)
}
} catch (e: java.lang.Exception) {
e.printStackTrace()
toast("Error")
}
}
How do I pass multiple parameters in Objective-C?
Yes; the Objective-C method syntax is like this for a couple of reasons; one of these is so that it is clear what the parameters you are specifying are. For example, if you are adding an object to an NSMutableArray
at a certain index, you would do it using the method:
- (void)insertObject:(id)anObject atIndex:(NSUInteger)index;
This method is called insertObject:atIndex:
and it is clear that an object is being inserted at a specified index.
In practice, adding a string "Hello, World!" at index 5 of an NSMutableArray
called array
would be called as follows:
NSString *obj = @"Hello, World!";
int index = 5;
[array insertObject:obj atIndex:index];
This also reduces ambiguity between the order of the method parameters, ensuring that you pass the object parameter first, then the index parameter. This becomes more useful when using functions that take a large number of arguments, and reduces error in passing the arguments.
Furthermore, the method naming convention is such because Objective-C doesn't support overloading; however, if you want to write a method that does the same job, but takes different data-types, this can be accomplished; take, for instance, the NSNumber
class; this has several object creation methods, including:
+ (id)numberWithBool:(BOOL)value;
+ (id)numberWithFloat:(float)value;
+ (id)numberWithDouble:(double)value;
In a language such as C++, you would simply overload the number method to allow different data types to be passed as the argument; however, in Objective-C, this syntax allows several different variants of the same function to be implemented, by changing the name of the method for each variant of the function.
validate a dropdownlist in asp.net mvc
Example from MVC 4 for dropdownlist validation on Submit using Dataannotation and ViewBag (less line of code)
Models:
namespace Project.Models
{
public class EmployeeReferral : Person
{
public int EmployeeReferralId { get; set; }
//Company District
//List
[Required(ErrorMessage = "Required.")]
[Display(Name = "Employee District:")]
public int? DistrictId { get; set; }
public virtual District District { get; set; }
}
namespace Project.Models
{
public class District
{
public int? DistrictId { get; set; }
[Display(Name = "Employee District:")]
public string DistrictName { get; set; }
}
}
EmployeeReferral Controller:
namespace Project.Controllers
{
public class EmployeeReferralController : Controller
{
private ProjDbContext db = new ProjDbContext();
//
// GET: /EmployeeReferral/
public ActionResult Index()
{
return View();
}
public ActionResult Create()
{
ViewBag.Districts = db.Districts;
return View();
}
View:
<td>
<div class="editor-label">
@Html.LabelFor(model => model.DistrictId, "District")
</div>
</td>
<td>
<div class="editor-field">
@*@Html.DropDownList("DistrictId", "----Select ---")*@
@Html.DropDownListFor(model => model.DistrictId, new SelectList(ViewBag.Districts, "DistrictId", "DistrictName"), "--- Select ---")
@Html.ValidationMessageFor(model => model.DistrictId)
</div>
</td>
Why can't we use ViewBag for populating dropdownlists that can be validated with Annotations. It is less lines of code.
C# Equivalent of SQL Server DataTypes
This is for SQL Server 2005. There are updated versions of the table for SQL Server 2008, SQL Server 2008 R2, SQL Server 2012 and SQL Server 2014.
SQL Server Data Types and Their .NET Framework Equivalents
The following table lists Microsoft SQL Server data types, their equivalents in the common language runtime (CLR) for SQL Server in the System.Data.SqlTypes namespace, and their native CLR equivalents in the Microsoft .NET Framework.
SQL Server data type CLR data type (SQL Server) CLR data type (.NET Framework)
varbinary SqlBytes, SqlBinary Byte[]
binary SqlBytes, SqlBinary Byte[]
varbinary(1), binary(1) SqlBytes, SqlBinary byte, Byte[]
image None None
varchar None None
char None None
nvarchar(1), nchar(1) SqlChars, SqlString Char, String, Char[]
nvarchar SqlChars, SqlString String, Char[]
nchar SqlChars, SqlString String, Char[]
text None None
ntext None None
uniqueidentifier SqlGuid Guid
rowversion None Byte[]
bit SqlBoolean Boolean
tinyint SqlByte Byte
smallint SqlInt16 Int16
int SqlInt32 Int32
bigint SqlInt64 Int64
smallmoney SqlMoney Decimal
money SqlMoney Decimal
numeric SqlDecimal Decimal
decimal SqlDecimal Decimal
real SqlSingle Single
float SqlDouble Double
smalldatetime SqlDateTime DateTime
datetime SqlDateTime DateTime
sql_variant None Object
User-defined type(UDT) None user-defined type
table None None
cursor None None
timestamp None None
xml SqlXml None
"Cannot start compilation: the output path is not specified for module..."
Open .iml file.
Look for keyword 'NewModuleRootManager'. Check if attribute 'inherit-compiler-output' is set to true or not. If not set to true.
Like this :
component name="NewModuleRootManager" inherit-compiler-output="true">
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/test" isTestSource="true" />
<sourceFolder url="file://$MODULE_DIR$/spec" isTestSource="true" />
<sourceFolder url="file://$MODULE_DIR$/app" isTestSource="false" />
ExpressJS How to structure an application?
Best Way To MVC Structure for ExpressJs Project with handlebar & Passportjs
- app
-config
-passport-setup.js
-controllers
-middleware
-models
-routes
-service
-bin
-www
-configuration.js
-passport.js
-node_modules
-views
-handlebars page
-env
-.gitignore
-package.json
-package-lock.json
Import python package from local directory into interpreter
You can use relative imports only from in a module that was in turn imported as part of a package -- your script or interactive interpreter wasn't, so of course from . import
(which means "import from the same package I got imported from") doesn't work. import mypackage
will be fine once you ensure the parent directory of mypackage
is in sys.path
(how you managed to get your current directory away from sys.path
I don't know -- do you have something strange in site.py, or...?)
To get your current directory back into sys.path
there is in fact no better way than putting it there.
Using getopts to process long and short command line options
Another way...
# translate long options to short
for arg
do
delim=""
case "$arg" in
--help) args="${args}-h ";;
--verbose) args="${args}-v ";;
--config) args="${args}-c ";;
# pass through anything else
*) [[ "${arg:0:1}" == "-" ]] || delim="\""
args="${args}${delim}${arg}${delim} ";;
esac
done
# reset the translated args
eval set -- $args
# now we can process with getopt
while getopts ":hvc:" opt; do
case $opt in
h) usage ;;
v) VERBOSE=true ;;
c) source $OPTARG ;;
\?) usage ;;
:)
echo "option -$OPTARG requires an argument"
usage
;;
esac
done
Display html text in uitextview
For Swift3
let theString = "<h1>H1 title</h1><b>Logo</b><img src='http://www.aver.com/Images/Shared/logo-color.png'><br>~end~"
let theAttributedString = try! NSAttributedString(data: theString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!,
options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
documentAttributes: nil)
UITextView_Message.attributedText = theAttributedString
Tensorflow import error: No module named 'tensorflow'
deleting tensorflow from cDrive/users/envs/tensorflow and after that
conda create -n tensorflow python=3.6
activate tensorflow
pip install --ignore-installed --upgrade tensorflow
now its working for newer versions of python thank you
Convert file: Uri to File in Android
public String getRealPathFromURI(Uri uri)
{
String result;
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
if (cursor == null) {
result = uri.getPath();
cursor.close();
return result;
}
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
result = cursor.getString(idx);
cursor.close();
return result;
}
Then using to get file from URI :
File finalFile = newFile(getRealPathFromURI(uri));
--HOPE CAN HELP YOU----
Checking if an Android application is running in the background
Another solution for this old post (for those that it might help) :
<application android:name=".BaseApplication" ... >
public class BaseApplication extends Application {
private class Status {
public boolean isVisible = true;
public boolean isFocused = true;
}
private Map<Activity, Status> activities;
@Override
public void onCreate() {
activities = new HashMap<Activity, Status>();
super.onCreate();
}
private boolean hasVisibleActivity() {
for (Status status : activities.values())
if (status.isVisible)
return true;
return false;
}
private boolean hasFocusedActivity() {
for (Status status : activities.values())
if (status.isFocused)
return true;
return false;
}
public void onActivityCreate(Activity activity, boolean isStarting) {
if (isStarting && activities.isEmpty())
onApplicationStart();
activities.put(activity, new Status());
}
public void onActivityStart(Activity activity) {
if (!hasVisibleActivity() && !hasFocusedActivity())
onApplicationForeground();
activities.get(activity).isVisible = true;
}
public void onActivityWindowFocusChanged(Activity activity, boolean hasFocus) {
activities.get(activity).isFocused = hasFocus;
}
public void onActivityStop(Activity activity, boolean isFinishing) {
activities.get(activity).isVisible = false;
if (!isFinishing && !hasVisibleActivity() && !hasFocusedActivity())
onApplicationBackground();
}
public void onActivityDestroy(Activity activity, boolean isFinishing) {
activities.remove(activity);
if(isFinishing && activities.isEmpty())
onApplicationStop();
}
private void onApplicationStart() {Log.i(null, "Start");}
private void onApplicationBackground() {Log.i(null, "Background");}
private void onApplicationForeground() {Log.i(null, "Foreground");}
private void onApplicationStop() {Log.i(null, "Stop");}
}
public class MyActivity extends BaseActivity {...}
public class BaseActivity extends Activity {
private BaseApplication application;
@Override
protected void onCreate(Bundle state) {
application = (BaseApplication) getApplication();
application.onActivityCreate(this, state == null);
super.onCreate(state);
}
@Override
protected void onStart() {
application.onActivityStart(this);
super.onStart();
}
@Override
public void onWindowFocusChanged(boolean hasFocus) {
application.onActivityWindowFocusChanged(this, hasFocus);
super.onWindowFocusChanged(hasFocus);
}
@Override
protected void onStop() {
application.onActivityStop(this, isFinishing());
super.onStop();
}
@Override
protected void onDestroy() {
application.onActivityDestroy(this, isFinishing());
super.onDestroy();
}
}
Visual Studio Copy Project
Following Shane's answer above (which works great BTW)…
You might encounter a slew of yellow triangles in the reference list.
Most of these can be eliminated by a Build->Clean Solution
and Build->Rebuild Solution
.
I did happen to have some Google API references that were a little more stubborn...as well as NewtonSoft JSon.
Trying to reinstall the NuGet package of the same version didn't work.
Visual Studio thinks you already have it installed.
To get around this:
1: Write down the original version.
2: Install the next higher/lower version...then uninstall it.
3: Install the original version from step #1.
How to use FormData in react-native?
Providing some other solution; we're also using react-native-image-picker
; and the server side is using koa-multer
; this set-up is working good:
ui
ImagePicker.showImagePicker(options, (response) => {
if (response.didCancel) {}
else if (response.error) {}
else if (response.customButton) {}
else {
this.props.addPhoto({ // leads to handleAddPhoto()
fileName: response.fileName,
path: response.path,
type: response.type,
uri: response.uri,
width: response.width,
height: response.height,
});
}
});
handleAddPhoto = (photo) => { // photo is the above object
uploadImage({ // these 3 properties are required
uri: photo.uri,
type: photo.type,
name: photo.fileName,
}).then((data) => {
// ...
});
}
client
export function uploadImage(file) { // so uri, type, name are required properties
const formData = new FormData();
formData.append('image', file);
return fetch(`${imagePathPrefix}/upload`, { // give something like https://xx.yy.zz/upload/whatever
method: 'POST',
body: formData,
}
).then(
response => response.json()
).then(data => ({
uri: data.uri,
filename: data.filename,
})
).catch(
error => console.log('uploadImage error:', error)
);
}
server
import multer from 'koa-multer';
import RouterBase from '../core/router-base';
const upload = multer({ dest: 'runtime/upload/' });
export default class FileUploadRouter extends RouterBase {
setupRoutes({ router }) {
router.post('/upload', upload.single('image'), async (ctx, next) => {
const file = ctx.req.file;
if (file != null) {
ctx.body = {
uri: file.filename,
filename: file.originalname,
};
} else {
ctx.body = {
uri: '',
filename: '',
};
}
});
}
}
How can I display a messagebox in ASP.NET?
This code will help you add a MsgBox in your asp.net file. You can change the function definition to your requirements. Hope this helps!
protected void Addstaff_Click(object sender, EventArgs e)
{
if (intClassCapcity < intCurrentstaffNumber)
{
MsgBox("Record cannot be added because max seats available for the " + (string)Session["course_name"] + " training has been reached");
}
else
{
sqlClassList.Insert();
}
}
private void MsgBox(string sMessage)
{
string msg = "<script language=\"javascript\">";
msg += "alert('" + sMessage + "');";
msg += "</script>";
Response.Write(msg);
}
How do I create variable variables?
I'm am answering the question: How to get the value of a variable given its name in a string?
which is closed as a duplicate with a link to this question.
If the variables in question are part of an object (part of a class for example) then some useful functions to achieve exactly that are hasattr
, getattr
, and setattr
.
So for example you can have:
class Variables(object):
def __init__(self):
self.foo = "initial_variable"
def create_new_var(self,name,value):
setattr(self,name,value)
def get_var(self,name):
if hasattr(self,name):
return getattr(self,name)
else:
raise("Class does not have a variable named: "+name)
Then you can do:
v = Variables()
v.get_var("foo")
"initial_variable"
v.create_new_var(v.foo,"is actually not initial")
v.initial_variable
"is actually not initial"
How to use XPath contains() here?
You are only looking at the first li
child in the query you have instead of looking for any li
child element that may contain the text, 'Model'
. What you need is a query like the following:
//ul[@class='featureList' and ./li[contains(.,'Model')]]
This query will give you the elements that have a class
of featureList
with one or more li
children that contain the text, 'Model'
.
Why is my Spring @Autowired field null?
I think you have missed to instruct spring to scan classes with annotation.
You can use @ComponentScan("packageToScan")
on the configuration class of your spring application to instruct spring to scan.
@Service, @Component
etc annotations add meta description.
Spring only injects instances of those classes which are either created as bean or marked with annotation.
Classes marked with annotation need to be identified by spring before injecting, @ComponentScan
instruct spring look for the classes marked with annotation. When Spring finds @Autowired
it searches for the related bean, and injects the required instance.
Adding annotation only, does not fix or facilitate the dependency injection, Spring needs to know where to look for.
jQuery: get parent tr for selected radio button
Try this.
You don't need to prefix attribute name by @
in jQuery selector. Use closest()
method to get the closest parent element matching the selector.
$("#MwDataList input[name=selectRadioGroup]:checked").closest('tr');
You can simplify your method like this
function getSelectedRowGuid() {
return GetRowGuid(
$("#MwDataList > input:radio[@name=selectRadioGroup]:checked :parent tr"));
}
closest()
- Gets the first element that matches the selector, beginning at the current element and progressing up through the DOM tree.
As a side note, the ids of the elements should be unique on the page so try to avoid having same ids for radio buttons which I can see in your markup. If you are not going to use the ids then just remove it from the markup.
How to get the selected value from RadioButtonList?
The ASPX code will look something like this:
<asp:RadioButtonList ID="rblist1" runat="server">
<asp:ListItem Text ="Item1" Value="1" />
<asp:ListItem Text ="Item2" Value="2" />
<asp:ListItem Text ="Item3" Value="3" />
<asp:ListItem Text ="Item4" Value="4" />
</asp:RadioButtonList>
<asp:Button ID="btn1" runat="server" OnClick="Button1_Click" Text="select value" />
And the code behind:
protected void Button1_Click(object sender, EventArgs e)
{
string selectedValue = rblist1.SelectedValue;
Response.Write(selectedValue);
}
How to create JSON post to api using C#
Try using Web API HttpClient
static async Task RunAsync()
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://domain.com/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// HTTP POST
var obj = new MyObject() { Str = "MyString"};
response = await client.PostAsJsonAsync("POST URL GOES HERE?", obj );
if (response.IsSuccessStatusCode)
{
response.//.. Contains the returned content.
}
}
}
You can find more details here Web API Clients
How do I create a list of random numbers without duplicates?
You can use Numpy library for quick answer as shown below -
Given code snippet lists down 6 unique numbers between the range of 0 to 5. You can adjust the parameters for your comfort.
import numpy as np
import random
a = np.linspace( 0, 5, 6 )
random.shuffle(a)
print(a)
Output
[ 2. 1. 5. 3. 4. 0.]
It doesn't put any constraints as we see in random.sample as referred here.
Hope this helps a bit.
How to make a new line or tab in <string> XML (eclipse/android)?
You can use \n
for new line and \t
for tabs. Also, extra spaces/tabs are just copied the way you write them in Strings.xml
so just give a couple of spaces where ever you want them.
A better way to reach this would probably be using padding/margin in your view xml and splitting up your long text in different strings in your string.xml
jQuery Determine if a matched class has a given id
update: sorry misunderstood the question, removed .has()
answer.
another alternative way, create .hasId()
plugin
_x000D_
_x000D_
// the plugin_x000D_
$.fn.hasId = function(id) {_x000D_
return this.attr('id') == id;_x000D_
};_x000D_
_x000D_
// select first class_x000D_
$('.mydiv').hasId('foo') ?_x000D_
console.log('yes') : console.log('no');_x000D_
_x000D_
// select second class_x000D_
// $('.mydiv').eq(1).hasId('foo')_x000D_
// or_x000D_
$('.mydiv:eq(1)').hasId('foo') ?_x000D_
console.log('yes') : console.log('no');
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<div class="mydiv" id="foo"></div>_x000D_
<div class="mydiv"></div>
_x000D_
_x000D_
_x000D_
How to select all the columns of a table except one column?
Without creating new table you can do simply (e.g with mysqli):
- get all columns
- loop through all columns and remove wich you want
- make your query
$r = mysqli_query('SELECT column_name FROM information_schema.columns WHERE table_name = table_to_query');
$c = count($r); while($c--) if($r[$c]['column_name'] != 'column_to_remove_from_query') $a[] = $r[$c]['column_name']; else unset($r[$c]);
$r = mysqli_query('SELECT ' . implode(',', $a) . ' FROM table_to_query');
Direct casting vs 'as' operator?
The as keyword is good in asp.net when you use the FindControl method.
Hyperlink link = this.FindControl("linkid") as Hyperlink;
if (link != null)
{
...
}
This means you can operate on the typed variable rather then having to then cast it from object
like you would with a direct cast:
object linkObj = this.FindControl("linkid");
if (link != null)
{
Hyperlink link = (Hyperlink)linkObj;
}
It's not a huge thing, but it saves lines of code and variable assignment, plus it's more readable
Mixed mode assembly is built against version ‘v2.0.50727' of the runtime
Please add attribute useLegacyV2RuntimeActivationPolicy="true" in your applications app.config file.
Old Value
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.1"/>
</startup>
New Value
<startup useLegacyV2RuntimeActivationPolicy="true">
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.1"/>
</startup>
It will solve your problem.
Raw SQL Query without DbSet - Entity Framework Core
I used Dapper to bypass this constraint of Entity framework Core.
IDbConnection.Query
is working with either sql query or stored procedure with multiple parameters.
By the way it's a bit faster (see benchmark tests )
Dapper is easy to learn. It took 15 minutes to write and run stored procedure with parameters. Anyway you may use both EF and Dapper. Below is an example:
public class PodborsByParametersService
{
string _connectionString = null;
public PodborsByParametersService(string connStr)
{
this._connectionString = connStr;
}
public IList<TyreSearchResult> GetTyres(TyresPodborView pb,bool isPartner,string partnerId ,int pointId)
{
string sqltext "spGetTyresPartnerToClient";
var p = new DynamicParameters();
p.Add("@PartnerID", partnerId);
p.Add("@PartnerPointID", pointId);
using (IDbConnection db = new SqlConnection(_connectionString))
{
return db.Query<TyreSearchResult>(sqltext, p,null,true,null,CommandType.StoredProcedure).ToList();
}
}
}
How do I get the current username in Windows PowerShell?
I have used $env:username
in the past, but a colleague pointed out it's an environment variable and can be changed by the user and therefore, if you really want to get the current user's username, you shouldn't trust it.
I'd upvote Mark Seemann's answer:
[System.Security.Principal.WindowsIdentity]::GetCurrent().Name
But I'm not allowed to. With Mark's answer, if you need just the username, you may have to parse it out since on my system, it returns hostname\username
and on domain joined machines with domain accounts it will return domain\username
.
I would not use whoami.exe
since it's not present on all versions of Windows, and it's a call out to another binary and may give some security teams fits.
How do I delay a function call for 5 seconds?
You can use plain javascript, this will call your_func once, after 5 seconds:
setTimeout(function() { your_func(); }, 5000);
If your function has no parameters and no explicit receiver you can call directly setTimeout(func, 5000)
There is also a plugin I've used once. It has oneTime
and everyTime
methods.
RegEx: How can I match all numbers greater than 49?
I know there is already a good answer posted, but it won't allow leading zeros. And I don't have enough reputation to leave a comment, so...
Here's my solution allowing leading zeros:
First I match the numbers 50 through 99 (with possible leading zeros):
0*[5-9]\d
Then match numbers of 100 and above (also with leading zeros):
0*[1-9]\d{2,}
Add them together with an "or" and wrap it up to match the whole sentence:
^0*([1-9]\d{2,}|[5-9]\d)$
That's it!
Static class initializer in PHP
I am posting this as an answer because this is very important as of PHP 7.4.
The opcache.preload
mechanism of PHP 7.4 makes it possible to preload opcodes for classes. If you use it to preload a file that contains a class definition and some side effects, then classes defined in that file will "exist" for all subsequent scripts executed by this FPM server and its workers, but the side effects will not be in effect, and the autoloader will not require the file containing them because the class already "exists". This completely defeats any and all static initialization techniques that rely on executing top-level code in the file that contains the class definition.
GIT clone repo across local file system in windows
You can specify the remote’s URL by applying the UNC path to the file protocol. This requires you to use four slashes:
git clone file:////<host>/<share>/<path>
For example, if your main machine has the IP 192.168.10.51 and the computer name main
, and it has a share named code
which itself is a git repository, then both of the following commands should work equally:
git clone file:////main/code
git clone file:////192.168.10.51/code
If the Git repository is in a subdirectory, simply append the path:
git clone file:////main/code/project-repository
git clone file:////192.168.10.51/code/project-repository
How to implement Enums in Ruby?
I have implemented enums like that
module EnumType
def self.find_by_id id
if id.instance_of? String
id = id.to_i
end
values.each do |type|
if id == type.id
return type
end
end
nil
end
def self.values
[@ENUM_1, @ENUM_2]
end
class Enum
attr_reader :id, :label
def initialize id, label
@id = id
@label = label
end
end
@ENUM_1 = Enum.new(1, "first")
@ENUM_2 = Enum.new(2, "second")
end
then its easy to do operations
EnumType.ENUM_1.label
...
enum = EnumType.find_by_id 1
...
valueArray = EnumType.values
Android Studio - Device is connected but 'offline'
This problem is because you have used an old adb version and not support on your device. or you have more than one adb
The key is:
- make sure you have a latest adb executable on your SDK
- Make sure to run adb command from "SDK_DIR/platform-tools/" because this should be the latest version (type command "which adb" to check) if u have more than one adb file, you can rename another one.
in my case, on my Windows 7 i have one more adb on "C:\Windows\adb.exe" and its an old version, so my adb command always run from that file. I fixed the problem by running adb form my sdk directory "SDK_DIR/platform-tools/adb.exe"
What is a word boundary in regex, does \b match hyphen '-'?
A word boundary, in most regex dialects, is a position between \w
and \W
(non-word char), or at the beginning or end of a string if it begins or ends (respectively) with a word character ([0-9A-Za-z_]
).
So, in the string "-12"
, it would match before the 1 or after the 2. The dash is not a word character.
Understanding the ngRepeat 'track by' expression
If you are working with objects track by the identifier(e.g. $index) instead of the whole object and you reload your data later, ngRepeat will not rebuild the DOM elements for items it has already rendered, even if the JavaScript objects in the collection have been substituted for new ones.
Selenium WebDriver and DropDown Boxes
Try the Select helper class and see if that makes any difference?
String valueToSelect= "Germany";
WebElement select = driver.findElement(By.id("selection"));
Select dropDown = new Select(select);
String selected = dropDown.getFirstSelectedOption().getText();
if(selected.equals(valueToSelect)) {//do stuff already selected}
List<WebElement> Options = dropDown.getOptions();
for(WebElement option:Options){
if(option.getText().equals(valueToSelect)){
option.click();
}
}
Stored Procedure error ORA-06550
Could you try this one:
create or replace
procedure point_triangle
IS
BEGIN
FOR thisteam in (select P.FIRSTNAME,P.LASTNAME, SUM(P.PTS) S from PLAYERREGULARSEASON P where P.TEAM = 'IND' group by P.FIRSTNAME, P.LASTNAME order by SUM(P.PTS) DESC)
LOOP
dbms_output.put_line(thisteam.FIRSTNAME|| ' ' || thisteam.LASTNAME || ':' || thisteam.S);
END LOOP;
END;
What's the difference between a 302 and a 307 redirect?
The difference concerns redirecting POST
, PUT
and DELETE
requests and what the expectations of the server are for the user agent behavior (RFC 2616
):
Note: RFC 1945 and RFC 2068 specify that the client is not allowed to
change the method on the redirected
request. However, most existing user
agent implementations treat 302 as if
it were a 303 response, performing a
GET on the Location field-value
regardless of the original request
method. The status codes 303 and 307
have been added for servers that wish
to make unambiguously clear which kind
of reaction is expected of the
client.
Also, read Wikipedia article on the 30x redirection codes.
How to pass objects to functions in C++?
Since no one mentioned I am adding on it, When you pass a object to a function in c++ the default copy constructor of the object is called if you dont have one which creates a clone of the object and then pass it to the method, so when you change the object values that will reflect on the copy of the object instead of the original object, that is the problem in c++, So if you make all the class attributes to be pointers, then the copy constructors will copy the addresses of the pointer attributes , so when the method invocations on the object which manipulates the values stored in pointer attributes addresses, the changes also reflect in the original object which is passed as a parameter, so this can behave same a Java but dont forget that all your class attributes must be pointers, also you should change the values of pointers, will be much clear with code explanation.
Class CPlusPlusJavaFunctionality {
public:
CPlusPlusJavaFunctionality(){
attribute = new int;
*attribute = value;
}
void setValue(int value){
*attribute = value;
}
void getValue(){
return *attribute;
}
~ CPlusPlusJavaFuncitonality(){
delete(attribute);
}
private:
int *attribute;
}
void changeObjectAttribute(CPlusPlusJavaFunctionality obj, int value){
int* prt = obj.attribute;
*ptr = value;
}
int main(){
CPlusPlusJavaFunctionality obj;
obj.setValue(10);
cout<< obj.getValue(); //output: 10
changeObjectAttribute(obj, 15);
cout<< obj.getValue(); //output: 15
}
But this is not good idea as you will be ending up writing lot of code involving with pointers, which are prone for memory leaks and do not forget to call destructors. And to avoid this c++ have copy constructors where you will create new memory when the objects containing pointers are passed to function arguments which will stop manipulating other objects data, Java does pass by value and value is reference, so it do not require copy constructors.
AngularJS $http, CORS and http authentication
No you don't have to put credentials, You have to put headers on client side eg:
$http({
url: 'url of service',
method: "POST",
data: {test : name },
withCredentials: true,
headers: {
'Content-Type': 'application/json; charset=utf-8'
}
});
And and on server side you have to put headers to this is example for nodejs:
/**
* On all requests add headers
*/
app.all('*', function(req, res,next) {
/**
* Response settings
* @type {Object}
*/
var responseSettings = {
"AccessControlAllowOrigin": req.headers.origin,
"AccessControlAllowHeaders": "Content-Type,X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Date, X-Api-Version, X-File-Name",
"AccessControlAllowMethods": "POST, GET, PUT, DELETE, OPTIONS",
"AccessControlAllowCredentials": true
};
/**
* Headers
*/
res.header("Access-Control-Allow-Credentials", responseSettings.AccessControlAllowCredentials);
res.header("Access-Control-Allow-Origin", responseSettings.AccessControlAllowOrigin);
res.header("Access-Control-Allow-Headers", (req.headers['access-control-request-headers']) ? req.headers['access-control-request-headers'] : "x-requested-with");
res.header("Access-Control-Allow-Methods", (req.headers['access-control-request-method']) ? req.headers['access-control-request-method'] : responseSettings.AccessControlAllowMethods);
if ('OPTIONS' == req.method) {
res.send(200);
}
else {
next();
}
});
How to change DatePicker dialog color for Android 5.0
I had the problem that time picker buttons have not been seen in the screen for API 24 in android. (API 21+)
it is solved by
<style name="MyDatePickerDialogTheme" parent="android:Theme.Material.Light.Dialog">
<item name="android:colorAccent">@color/colorPrimary2</item></style>
<style name="Theme" parent="BBaseTheme">
<item name="android:datePickerDialogTheme">@style/MyDatePickerDialogTheme</item>
</style>
Changing background colour of tr element on mouseover
Try it
<!- HTML -->
<tr onmouseover="mOvr(this,'#ffa');" onmouseout="mOut(this,'#FFF');">
<script>
function mOvr(src,clrOver) {
if (!src.contains(event.fromElement)) {
src.bgColor = clrOver;
}
}
function mOut(src,clrIn) {
if (!src.contains(event.toElement)) {
src.bgColor = clrIn;
}
}
</script>
Is it possible to set async:false to $.getJSON call
Roll your own e.g.
function syncJSON(i_url, callback) {
$.ajax({
type: "POST",
async: false,
url: i_url,
contentType: "application/json",
dataType: "json",
success: function (msg) { callback(msg) },
error: function (msg) { alert('error : ' + msg.d); }
});
}
syncJSON("/pathToYourResouce", function (msg) {
console.log(msg);
})
How do I set a ViewModel on a window in XAML using DataContext property?
You need to instantiate the MainViewModel and set it as datacontext. In your statement it just consider it as string value.
<Window x:Class="BuildAssistantUI.BuildAssistantWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:BuildAssistantUI.ViewModels">
<Window.DataContext>
<local:MainViewModel/>
</Window.DataContext>
How to store command results in a shell variable?
The syntax to store the command output into a variable is var=$(command)
.
So you can directly do:
result=$(ls -l | grep -c "rahul.*patle")
And the variable $result
will contain the number of matches.
What is JavaScript garbage collection?
Beware of circular references when DOM objects are involved:
Memory leak patterns in JavaScript
Keep in mind that memory can only be reclaimed when there are no active references to the object. This is a common pitfall with closures and event handlers, as some JS engines will not check which variables actually are referenced in inner functions and just keep all local variables of the enclosing functions.
Here's a simple example:
function init() {
var bigString = new Array(1000).join('xxx');
var foo = document.getElementById('foo');
foo.onclick = function() {
// this might create a closure over `bigString`,
// even if `bigString` isn't referenced anywhere!
};
}
A naive JS implementation can't collect bigString
as long as the event handler is around. There are several ways to solve this problem, eg setting bigString = null
at the end of init()
(delete
won't work for local variables and function arguments: delete
removes properties from objects, and the variable object is inaccessible - ES5 in strict mode will even throw a ReferenceError
if you try to delete a local variable!).
I recommend to avoid unnecessary closures as much as possible if you care for memory consumption.
WebView link click open default browser
You can use an Intent for this:
Uri uriUrl = Uri.parse("http://www.google.com/");
Intent launchBrowser = new Intent(Intent.ACTION_VIEW, uriUrl);
startActivity(launchBrowser);
How to find an object in an ArrayList by property
In Java8 you can use streams:
public static Carnet findByCodeIsIn(Collection<Carnet> listCarnet, String codeIsIn) {
return listCarnet.stream().filter(carnet -> codeIsIn.equals(carnet.getCodeIsin())).findFirst().orElse(null);
}
Additionally, in case you have many different objects (not only Carnet
) or you want to find it by different properties (not only by cideIsin
), you could build an utility class, to ecapsulate this logic in it:
public final class FindUtils {
public static <T> T findByProperty(Collection<T> col, Predicate<T> filter) {
return col.stream().filter(filter).findFirst().orElse(null);
}
}
public final class CarnetUtils {
public static Carnet findByCodeTitre(Collection<Carnet> listCarnet, String codeTitre) {
return FindUtils.findByProperty(listCarnet, carnet -> codeTitre.equals(carnet.getCodeTitre()));
}
public static Carnet findByNomTitre(Collection<Carnet> listCarnet, String nomTitre) {
return FindUtils.findByProperty(listCarnet, carnet -> nomTitre.equals(carnet.getNomTitre()));
}
public static Carnet findByCodeIsIn(Collection<Carnet> listCarnet, String codeIsin) {
return FindUtils.findByProperty(listCarnet, carnet -> codeIsin.equals(carnet.getCodeIsin()));
}
}
ASP.NET Web Api: The requested resource does not support http method 'GET'
If you have not configured any HttpMethod on your action in controller, it is assumed to be only HttpPost in RC. In Beta, it is assumed to support all methods - GET, PUT, POST and Delete. This is a small change from beta to RC. You could easily decore more than one httpmethod on your action with [AcceptVerbs("GET", "POST")].
Failed to connect to camera service
The problem is related to permission. Copy following code into onCreate() method. The issue will get solved.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[] {Manifest.permission.CAMERA}, 1);
}
}
After that wait for the user action and handle his decision.
@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case CAMERA_PERMISSION_REQUEST_CODE:
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//Start your camera handling here
} else {
AppUtils.showUserMessage("You declined to allow the app to access your camera", this);
}
}
}
What to use now Google News API is deprecated?
I'm running into the same issue with one of my own apps. So far I've found the only non-deprecated way to access Google News data is through their RSS feeds. They have a feed for each section and also a useful search function. However, these are only for noncommercial use.
As for viable alternatives I'll be trying out these two services: Feedzilla, Daylife
How to set a header for a HTTP GET request, and trigger file download?
Try
html
<!-- placeholder ,
`click` download , `.remove()` options ,
at js callback , following js
-->
<a>download</a>
js
$(document).ready(function () {
$.ajax({
// `url`
url: '/echo/json/',
type: "POST",
dataType: 'json',
// `file`, data-uri, base64
data: {
json: JSON.stringify({
"file": "data:text/plain;base64,YWJj"
})
},
// `custom header`
headers: {
"x-custom-header": 123
},
beforeSend: function (jqxhr) {
console.log(this.headers);
alert("custom headers" + JSON.stringify(this.headers));
},
success: function (data) {
// `file download`
$("a")
.attr({
"href": data.file,
"download": "file.txt"
})
.html($("a").attr("download"))
.get(0).click();
console.log(JSON.parse(JSON.stringify(data)));
},
error: function (jqxhr, textStatus, errorThrown) {
console.log(textStatus, errorThrown)
}
});
});
jsfiddle http://jsfiddle.net/guest271314/SJYy3/
Storing and Retrieving ArrayList values from hashmap
You can use like this(Though the random number generator logic is not upto the mark)
public class WorkSheet {
HashMap<String,ArrayList<Integer>> map = new HashMap<String,ArrayList<Integer>>();
public static void main(String args[]) {
WorkSheet test = new WorkSheet();
test.inputData("mango", 5);
test.inputData("apple", 2);
test.inputData("grapes", 2);
test.inputData("peach", 3);
test.displayData();
}
public void displayData(){
for (Entry<String, ArrayList<Integer>> entry : map.entrySet()) {
System.out.print(entry.getKey()+" | ");
for(int fruitNo : entry.getValue()){
System.out.print(fruitNo+" ");
}
System.out.println();
}
}
public void inputData(String name ,int number) {
Random rndData = new Random();
ArrayList<Integer> fruit = new ArrayList<Integer>();
for(int i=0 ; i<number ; i++){
fruit.add(rndData.nextInt(10));
}
map.put(name, fruit);
}
}
OUTPUT
grapes | 7 5
apple | 9 5
peach | 5 5 8
mango | 4 7 1 5 5
INSERT with SELECT
The right Syntax for your query is:
INSERT INTO courses (name, location, gid)
SELECT (name, location, gid)
FROM courses
WHERE cid = $cid
Want to show/hide div based on dropdown box selection
https://www.tutorialrepublic.com/codelab.php?topic=faq&file=jquery-show-hide-div-using-select-box
It's working well in my case
_x000D_
_x000D_
$(document).ready(function(){_x000D_
$("select").change(function(){_x000D_
$(this).find("option:selected").each(function(){_x000D_
var optionValue = $(this).attr("value");_x000D_
if(optionValue){_x000D_
$(".box").not("." + optionValue).hide();_x000D_
$("." + optionValue).show();_x000D_
} else{_x000D_
$(".box").hide();_x000D_
}_x000D_
});_x000D_
}).change();_x000D_
});
_x000D_
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
<head>_x000D_
<meta charset="utf-8">_x000D_
<title>jQuery Show Hide Elements Using Select Box</title>_x000D_
<style>_x000D_
.box{_x000D_
color: #fff;_x000D_
padding: 50px;_x000D_
display: none;_x000D_
margin-top: 10px;_x000D_
}_x000D_
.red{ background: #ff0000; }_x000D_
.green{ background: #228B22; }_x000D_
.blue{ background: #0000ff; }_x000D_
</style>_x000D_
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>_x000D_
_x000D_
</head>_x000D_
<body>_x000D_
<div>_x000D_
<select>_x000D_
<option>Choose Color</option>_x000D_
<option value="red">Red</option>_x000D_
<option value="green">Green</option>_x000D_
<option value="blue">Blue</option>_x000D_
</select>_x000D_
</div>_x000D_
<div class="red box">You have selected <strong>red option</strong> so i am here</div>_x000D_
<div class="green box">You have selected <strong>green option</strong> so i am here</div>_x000D_
<div class="blue box">You have selected <strong>blue option</strong> so i am here</div>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_
File path for project files?
You would do something like this to get the path "Data\ich_will.mp3" inside your application environments folder.
string fileName = "ich_will.mp3";
string path = Path.Combine(Environment.CurrentDirectory, @"Data\", fileName);
In my case it would return the following:
C:\MyProjects\Music\MusicApp\bin\Debug\Data\ich_will.mp3
I use Path.Combine
and Environment.CurrentDirectory
in my example. These are very useful and allows you to build a path based on the current location of your application. Path.Combine
combines two or more strings to create a location, and Environment.CurrentDirectory
provides you with the working directory of your application.
The working directory is not necessarily the same path as where your executable
is located, but in most cases it should be, unless specified otherwise.
Android: How to use webcam in emulator?
UPDATE
In Android Studio AVD:
- Open AVD Manager:
- Add/Edit AVD:
- Click Advanced Settings in the bottom of the screen:
- Set your camera of choice as the front/back cameras:
Cut Java String at a number of character
Use substring
String strOut = "abcdefghijklmnopqrtuvwxyz"
String result = strOut.substring(0, 8) + "...";// count start in 0 and 8 is excluded
System.out.pritnln(result);
Note: substring(int first, int second) takes two parameters. The first is inclusive and the second is exclusive.
Python function as a function argument?
Decorators are very powerful in Python since it allows programmers to pass function as argument and can also define function inside another function.
def decorator(func):
def insideFunction():
print("This is inside function before execution")
func()
return insideFunction
def func():
print("I am argument function")
func_obj = decorator(func)
func_obj()
Output
- This is inside function before execution
- I am argument function
How should I declare default values for instance variables in Python?
The two snippets do different things, so it's not a matter of taste but a matter of what's the right behaviour in your context. Python documentation explains the difference, but here are some examples:
Exhibit A
class Foo:
def __init__(self):
self.num = 1
This binds num
to the Foo instances. Change to this field is not propagated to other instances.
Thus:
>>> foo1 = Foo()
>>> foo2 = Foo()
>>> foo1.num = 2
>>> foo2.num
1
Exhibit B
class Bar:
num = 1
This binds num
to the Bar class. Changes are propagated!
>>> bar1 = Bar()
>>> bar2 = Bar()
>>> bar1.num = 2 #this creates an INSTANCE variable that HIDES the propagation
>>> bar2.num
1
>>> Bar.num = 3
>>> bar2.num
3
>>> bar1.num
2
>>> bar1.__class__.num
3
Actual answer
If I do not require a class variable, but only need to set a default value for my instance variables, are both methods equally good? Or one of them more 'pythonic' than the other?
The code in exhibit B is plain wrong for this: why would you want to bind a class attribute (default value on instance creation) to the single instance?
The code in exhibit A is okay.
If you want to give defaults for instance variables in your constructor I would however do this:
class Foo:
def __init__(self, num = None):
self.num = num if num is not None else 1
...or even:
class Foo:
DEFAULT_NUM = 1
def __init__(self, num = None):
self.num = num if num is not None else DEFAULT_NUM
...or even: (preferrable, but if and only if you are dealing with immutable types!)
class Foo:
def __init__(self, num = 1):
self.num = num
This way you can do:
foo1 = Foo(4)
foo2 = Foo() #use default
Error: package or namespace load failed for ggplot2 and for data.table
I had this same problem, but when running in a jupyter R notebook in an Anaconda environment.
The problem presented in such a way that any R notebook opened would instantly die and would not allow cell execution. The error would show up with each failed automated attempt to start the kernel:
Error in loadNamespace(j <- i[[1L]], c(lib.loc, .libPaths()), versionCheck = vI[[j]]) :
there is no package called ‘Rcpp’
To solve this, I ran as admin/sudo: conda install -c r r-rcpp
, restarted the kernel, and everything was back to normal.
How to pass 2D array (matrix) in a function in C?
I don't know what you mean by "data dont get lost". Here's how you pass a normal 2D array to a function:
void myfunc(int arr[M][N]) { // M is optional, but N is required
..
}
int main() {
int somearr[M][N];
...
myfunc(somearr);
...
}
How to use subList()
I've implemented and tested this one; it should cover most bases:
public static <T> List<T> safeSubList(List<T> list, int fromIndex, int toIndex) {
int size = list.size();
if (fromIndex >= size || toIndex <= 0 || fromIndex >= toIndex) {
return Collections.emptyList();
}
fromIndex = Math.max(0, fromIndex);
toIndex = Math.min(size, toIndex);
return list.subList(fromIndex, toIndex);
}
How to display an error message in an ASP.NET Web Application
All you need is a control that you can set the text of, and an UpdatePanel if the exception occurs during a postback.
If occurs during a postback:
markup:
<ajax:UpdatePanel id="ErrorUpdatePanel" runat="server" UpdateMode="Coditional">
<ContentTemplate>
<asp:TextBox id="ErrorTextBox" runat="server" />
</ContentTemplate>
</ajax:UpdatePanel>
code:
try
{
do something
}
catch(YourException ex)
{
this.ErrorTextBox.Text = ex.Message;
this.ErrorUpdatePanel.Update();
}
Validate phone number using javascript
Add a word boundary \b
at the end of the regex:
/^(\([0-9]{3}\) |[0-9]{3}-)[0-9]{3}-[0-9]{4}\b/
if the space after )
is optional:
/^(\([0-9]{3}\)\s*|[0-9]{3}-)[0-9]{3}-[0-9]{4}\b/
What is JSON and why would I use it?
I like JSON mainly because it's so terse. For web content that can be gzipped, this isn't necessarily a big deal (hence why xhtml is so popular). But there are occasions where this can be beneficial.
For example, for one project I was transmitting information that needed to be serialized and transmitted via XMPP. Since most servers will limit the amount of data you can transmit in a single message, I found it helpful to use JSON over the obvious alternative, XML.
As an added bonus, if you're familiar with Python or Javascript, you already pretty much know JSON and can interpret it without much training at all.
TypeError: $(...).DataTable is not a function
There can be two reasons for that error:
First
You are loding jQuery.DataTables.js
before jquery.js
so for that :-
You need to load jQuery.js
before you load jQuery.DataTables.js
Second
You are using two versions of jQuery.js
on the same page so for that :-
Try to use the higher version and make sure both links have same version of jQuery
Lotus Notes email as an attachment to another email
Tested vith Notes versions 6.5.x and 7.0.x
From your Lotus Notes inbox
- Open the message
- Click View > Show > Page Source
- Copy all the data into a text file and save the file with .eml extension.
- Create a new message
- Attach the .eml file(s) and send the new message
Hop this helps. I have no client on my current machine but will test from home on 8.5.1
How to cast a double to an int in Java by rounding it down?
try with this, This is simple
double x= 20.22889909008;
int a = (int) x;
this will return a=20
or try with this:-
Double x = 20.22889909008;
Integer a = x.intValue();
this will return a=20
or try with this:-
double x= 20.22889909008;
System.out.println("===="+(int)x);
this will return ===20
may be these code will help you.
docker-compose up for only certain containers
Update
Starting with docker-compose
1.28.0 the new service profiles are just made for that! With profiles
you can mark services to be only started in specific profiles:
services:
client:
# ...
db:
# ...
npm:
profiles: ["cli-only"]
# ...
docker-compose up # start main services, no npm
docker-compose run --rm npm # run npm service
docker-compose --profile cli-only # start main and all "cli-only" services
original answer
Since docker-compose
v1.5 it is possible to pass multiple docker-compose.yml
files with the -f
flag. This allows you to split your dev tools into a separate docker-compose.yml
which you then only include on-demand:
# start and attach to all your essential services
docker-compose up
# execute a defined command in docker-compose.dev.yml
docker-compose -f docker-compose.dev.yml run npm update
# if your command depends_on a service you need to include both configs
docker-compose -f docker-compose.yml -f docker-compose.dev.yml run npm update
For an in-depth discussion on this see docker/compose#1896.
No module named 'openpyxl' - Python 3.4 - Ubuntu
@zetysz and @Manish already fixed the problem. I am just putting this in an answer for future reference:
pip
refers to Python 2 as a default in Ubuntu, this means that pip install x
will install the module for Python 2 and not for 3
pip3
refers to Python 3, it will install the module for Python 3
bypass invalid SSL certificate in .net core
In .NetCore, you can add the following code snippet at services configure method , I added a check to make sure only that we by pass the SSL certificate in development environment only
services.AddHttpClient("HttpClientName", client => {
// code to configure headers etc..
}).ConfigurePrimaryHttpMessageHandler(() => {
var handler = new HttpClientHandler();
if (hostingEnvironment.IsDevelopment())
{
handler.ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => { return true; };
}
return handler;
});
How can I concatenate strings in VBA?
The main (very interesting) difference for me is that:
"string" & Null
-> "string"
while
"string" + Null
-> Null
But that's probably more useful in database apps like Access.
How do I use properly CASE..WHEN in MySQL
SELECT
CASE
WHEN course_enrollment_settings.base_price = 0 THEN 1
WHEN course_enrollment_settings.base_price>0 AND
course_enrollment_settings.base_price<=100 THEN 2
WHEN course_enrollment_settings.base_price>100 AND
course_enrollment_settings.base_price<201 THEN 3
ELSE 6
END AS 'calc_base_price',
course_enrollment_settings.base_price
FROM
course_enrollment_settings
WHERE course_enrollment_settings.base_price = 0
How to correctly assign a new string value?
Think of strings as abstract objects, and char arrays as containers. The string can be any size but the container must be at least 1 more than the string length (to hold the null terminator).
C has very little syntactical support for strings. There are no string operators (only char-array and char-pointer operators). You can't assign strings.
But you can call functions to help achieve what you want.
The strncpy()
function could be used here. For maximum safety I suggest following this pattern:
strncpy(p.name, "Jane", 19);
p.name[19] = '\0'; //add null terminator just in case
Also have a look at the strncat()
and memcpy()
functions.
javascript clear field value input
HTML:
<input name="name" id="name" type="text" value="Name" onfocus="clearField(this);" onblur="fillField(this);"/>
JS:
function clearField(input) {
if(input.value=="Name") { //Only clear if value is "Name"
input.value = "";
}
}
function fillField(input) {
if(input.value=="") {
input.value = "Name";
}
}
What is a typedef enum in Objective-C?
Update for 64-bit Change:
According to apple docs about 64-bit changes,
Enumerations Are Also Typed : In the LLVM compiler, enumerated types can
define the size of the enumeration. This means that some enumerated
types may also have a size that is larger than you expect. The
solution, as in all the other cases, is to make no assumptions about a
data type’s size. Instead, assign any enumerated values to a variable
with the proper data type
So you have to create enum with type as below syntax if you support for 64-bit.
typedef NS_ENUM(NSUInteger, ShapeType) {
kCircle,
kRectangle,
kOblateSpheroid
};
or
typedef enum ShapeType : NSUInteger {
kCircle,
kRectangle,
kOblateSpheroid
} ShapeType;
Otherwise, it will lead to warning as Implicit conversion loses integer precision: NSUInteger (aka 'unsigned long') to ShapeType
Update for swift-programming:
In swift, there's an syntax change.
enum ControlButtonID: NSUInteger {
case kCircle , kRectangle, kOblateSpheroid
}
Deny all, allow only one IP through htaccess
You can have more than one IP or even some other kind of allow like user, hostname, ... more info here https://www.askapache.com/htaccess/setenvif/
SetEnvIf remote_addr ^123.123.123.1$ allowedip=1
SetEnvIf remote_addr ^123.123.123.2$ allowedip=1
SetEnvIf remote_addr ^123.123.123.3$ allowedip=1
SetEnvIf remote_addr ^123.123.123.4$ allowedip=1
Order deny,allow
deny from all
allow from env=allowedip
Calling pylab.savefig without display in ipython
This is a matplotlib question, and you can get around this by using a backend that doesn't display to the user, e.g. 'Agg':
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
plt.plot([1,2,3])
plt.savefig('/tmp/test.png')
EDIT: If you don't want to lose the ability to display plots, turn off Interactive Mode, and only call plt.show()
when you are ready to display the plots:
import matplotlib.pyplot as plt
# Turn interactive plotting off
plt.ioff()
# Create a new figure, plot into it, then close it so it never gets displayed
fig = plt.figure()
plt.plot([1,2,3])
plt.savefig('/tmp/test0.png')
plt.close(fig)
# Create a new figure, plot into it, then don't close it so it does get displayed
plt.figure()
plt.plot([1,3,2])
plt.savefig('/tmp/test1.png')
# Display all "open" (non-closed) figures
plt.show()
ASP.net using a form to insert data into an sql server table
There are tons of sample code online as to how to do this.
Here is just one example of how to do this:
http://geekswithblogs.net/dotNETvinz/archive/2009/04/30/creating-a-simple-registration-form-in-asp.net.aspx
you define the text boxes between the following tag:
<form id="form1" runat="server">
you create your textboxes and define them to runat="server" like so:
<asp:TextBox ID="TxtName" runat="server"></asp:TextBox>
define a button to process your logic like so (notice the onclick):
<asp:Button ID="Button1" runat="server" Text="Save" onclick="Button1_Click" />
in the code behind, you define what you want the server to do if the user clicks on the button by defining a method named
protected void Button1_Click(object sender, EventArgs e)
or you could just double click the button in the design view.
Here is a very quick sample of code to insert into a table in the button click event (codebehind)
protected void Button1_Click(object sender, EventArgs e)
{
string name = TxtName.Text; // Scrub user data
string connString = ConfigurationManager.ConnectionStrings["yourconnstringInWebConfig"].ConnectionString;
SqlConnection conn = null;
try
{
conn = new SqlConnection(connString);
conn.Open();
using(SqlCommand cmd = new SqlCommand())
{
cmd.Conn = conn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "INSERT INTO dummyTable(name) Values (@var)";
cmd.Parameters.AddWithValue("@var", name);
int rowsAffected = cmd.ExecuteNonQuery();
if(rowsAffected ==1)
{
//Success notification
}
else
{
//Error notification
}
}
}
catch(Exception ex)
{
//log error
//display friendly error to user
}
finally
{
if(conn!=null)
{
//cleanup connection i.e close
}
}
}
How to add a char/int to an char array in C?
strcat
has the declaration:
char *strcat(char *dest, const char *src)
It expects 2 strings. While this compiles:
char str[1024] = "Hello World";
char tmp = '.';
strcat(str, tmp);
It will cause bad memory issues because strcat
is looking for a null terminated cstring. You can do this:
char str[1024] = "Hello World";
char tmp[2] = ".";
strcat(str, tmp);
Live example.
If you really want to append a char you will need to make your own function. Something like this:
void append(char* s, char c) {
int len = strlen(s);
s[len] = c;
s[len+1] = '\0';
}
append(str, tmp)
Of course you may also want to check your string size etc to make it memory safe.
How to bind DataTable to Datagrid
You could use DataGrid in WPF
SqlDataAdapter da = new SqlDataAdapter("Select * from Table",con);
DataTable dt = new DataTable("Call Reciept");
da.Fill(dt);
DataGrid dg = new DataGrid();
dg.ItemsSource = dt.DefaultView;
How can I make a float top with CSS?
There is no float:top
, only float:left
and float:right
If you wish to display div underneath each other you would have to do:
<div style="float:left;clear:both"></div>
<div style="float:left;clear:both"></div>
How to remove numbers from string using Regex.Replace?
You can do it with a LINQ like solution instead of a regular expression:
string input = "123- abcd33";
string chars = new String(input.Where(c => c != '-' && (c < '0' || c > '9')).ToArray());
A quick performance test shows that this is about five times faster than using a regular expression.
How can I hide/show a div when a button is clicked?
The following solution is:
- briefest. Somewhat similar to here. It's also minimal: The table in the DIV is orthogonal to your question.
- fastest:
getElementById
is called once at the outset. This may or may not suit your purposes.
- It uses pure JavaScript (i.e. without JQuery).
- It uses a button. Your taste may vary.
- extensible: it's ready to add more DIVs, sharing the code.
_x000D_
_x000D_
mydiv = document.getElementById("showmehideme");_x000D_
_x000D_
function showhide(d) {_x000D_
d.style.display = (d.style.display !== "none") ? "none" : "block";_x000D_
}
_x000D_
#mydiv { background-color: #ddd; }
_x000D_
<button id="button" onclick="showhide(mydiv)">Show/Hide</button>_x000D_
<div id="showmehideme">_x000D_
This div will show and hide on button click._x000D_
</div>
_x000D_
_x000D_
_x000D_
Display loading image while post with ajax
_x000D_
_x000D_
//$(document).ready(function(){_x000D_
// $("a").click(function(event){_x000D_
// event.preventDefault();_x000D_
// $("div").html("This is prevent link...");_x000D_
// });_x000D_
//}); _x000D_
_x000D_
$(document).ready(function(){_x000D_
$("a").click(function(event){_x000D_
event.preventDefault();_x000D_
$.ajax({_x000D_
beforeSend: function(){_x000D_
$('#text').html("<img src='ajax-loader.gif' /> Loading...");_x000D_
},_x000D_
success : function(){_x000D_
setInterval(function(){ $('#text').load("cd_catalog.txt"); },1000);_x000D_
}_x000D_
});_x000D_
});_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>_x000D_
_x000D_
<a href="http://www.wantyourhelp.com">[click to redirect][1]</a>_x000D_
<div id="text"></div>
_x000D_
_x000D_
_x000D_
SQLite error 'attempt to write a readonly database' during insert?
This can happen when the owner of the SQLite file itself is not the same as the user running the script. Similar errors can occur if the entire directory path (meaning each directory along the way) can't be written to.
Who owns the SQLite file? You?
Who is the script running as? Apache or Nobody?
Ways to iterate over a list in Java
A JDK8-style iteration:
public class IterationDemo {
public static void main(String[] args) {
List<Integer> list = Arrays.asList(1, 2, 3);
list.stream().forEach(elem -> System.out.println("element " + elem));
}
}
Split files using tar, gz, zip, or bzip2
You can use the split
command with the -b
option:
split -b 1024m file.tar.gz
It can be reassembled on a Windows machine using @Joshua's answer.
copy /b file1 + file2 + file3 + file4 filetogether
Edit: As @Charlie stated in the comment below, you might want to set a prefix explicitly because it will use x
otherwise, which can be confusing.
split -b 1024m "file.tar.gz" "file.tar.gz.part-"
// Creates files: file.tar.gz.part-aa, file.tar.gz.part-ab, file.tar.gz.part-ac, ...
Edit: Editing the post because question is closed and the most effective solution is very close to the content of this answer:
# create archives
$ tar cz my_large_file_1 my_large_file_2 | split -b 1024MiB - myfiles_split.tgz_
# uncompress
$ cat myfiles_split.tgz_* | tar xz
This solution avoids the need to use an intermediate large file when (de)compressing. Use the tar -C option to use a different directory for the resulting files. btw if the archive consists from only a single file, tar could be avoided and only gzip used:
# create archives
$ gzip -c my_large_file | split -b 1024MiB - myfile_split.gz_
# uncompress
$ cat myfile_split.gz_* | gunzip -c > my_large_file
For windows you can download ported versions of the same commands or use cygwin.
Getting msbuild.exe without installing Visual Studio
Download MSBuild with the link from @Nicodemeus answer was OK, yet the installation was broken until I've added these keys into a register:
[HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\MSBuild\ToolsVersions\12.0]
"VCTargetsPath11"="$([MSBuild]::ValueOrDefault('$(VCTargetsPath11)','$(MSBuildExtensionsPath32)\\Microsoft.Cpp\\v4.0\\V110\\'))"
"VCTargetsPath"="$([MSBuild]::ValueOrDefault('$(VCTargetsPath)','$(MSBuildExtensionsPath32)\\Microsoft.Cpp\\v4.0\\V110\\'))"
Build tree array from flat array in javascript
I wrote an ES6 version based on @Halcyon answer
const array = [
{
id: '12',
parentId: '0',
text: 'one-1'
},
{
id: '6',
parentId: '12',
text: 'one-1-6'
},
{
id: '7',
parentId: '12',
text: 'one-1-7'
},
{
id: '9',
parentId: '0',
text: 'one-2'
},
{
id: '11',
parentId: '9',
text: 'one-2-11'
}
];
// Prevent changes to the original data
const arrayCopy = array.map(item => ({ ...item }));
const listToTree = list => {
const map = {};
const roots = [];
list.forEach((v, i) => {
map[v.id] = i;
list[i].children = [];
});
list.forEach(v => (v.parentId !== '0' ? list[map[v.parentId]].children.push(v) : roots.push(v)));
return roots;
};
console.log(listToTree(arrayCopy));
The principle of this algorithm is to use "map" to establish an index relationship. It is easy to find "item" in the list by "parentId", and add "children" to each "item", because "list" is a reference relationship, so "roots" will Build relationships with the entire tree.
How to duplicate sys.stdout to a log file?
None of the answers above really seems to answer the problem posed. I know this is an old thread, but I think this problem is a lot simpler than everyone is making it:
class tee_err(object):
def __init__(self):
self.errout = sys.stderr
sys.stderr = self
self.log = 'logfile.log'
log = open(self.log,'w')
log.close()
def write(self, line):
log = open(self.log,'a')
log.write(line)
log.close()
self.errout.write(line)
Now this will repeat everything to the normal sys.stderr handler and your file. Create another class tee_out
for sys.stdout
.
How do I check if a type is a subtype OR the type of an object?
Apparently, no.
Here's the options:
Type.IsSubclassOf
As you've already found out, this will not work if the two types are the same, here's a sample LINQPad program that demonstrates:
void Main()
{
typeof(Derived).IsSubclassOf(typeof(Base)).Dump();
typeof(Base).IsSubclassOf(typeof(Base)).Dump();
}
public class Base { }
public class Derived : Base { }
Output:
True
False
Which indicates that Derived
is a subclass of Base
, but that Base
is (obviously) not a subclass of itself.
Type.IsAssignableFrom
Now, this will answer your particular question, but it will also give you false positives. As Eric Lippert has pointed out in the comments, while the method will indeed return True
for the two above questions, it will also return True
for these, which you probably don't want:
void Main()
{
typeof(Base).IsAssignableFrom(typeof(Derived)).Dump();
typeof(Base).IsAssignableFrom(typeof(Base)).Dump();
typeof(int[]).IsAssignableFrom(typeof(uint[])).Dump();
}
public class Base { }
public class Derived : Base { }
Here you get the following output:
True
True
True
The last True
there would indicate, if the method only answered the question asked, that uint[]
inherits from int[]
or that they're the same type, which clearly is not the case.
So IsAssignableFrom
is not entirely correct either.
is
and as
The "problem" with is
and as
in the context of your question is that they will require you to operate on the objects and write one of the types directly in code, and not work with Type
objects.
In other words, this won't compile:
SubClass is BaseClass
^--+---^
|
+-- need object reference here
nor will this:
typeof(SubClass) is typeof(BaseClass)
^-------+-------^
|
+-- need type name here, not Type object
nor will this:
typeof(SubClass) is BaseClass
^------+-------^
|
+-- this returns a Type object, And "System.Type" does not
inherit from BaseClass
Conclusion
While the above methods might fit your needs, the only correct answer to your question (as I see it) is that you will need an extra check:
typeof(Derived).IsSubclassOf(typeof(Base)) || typeof(Derived) == typeof(Base);
which of course makes more sense in a method:
public bool IsSameOrSubclass(Type potentialBase, Type potentialDescendant)
{
return potentialDescendant.IsSubclassOf(potentialBase)
|| potentialDescendant == potentialBase;
}
How can I check the size of a file in a Windows batch script?
Important to note is the INT32 limit of Batch: 'Invalid number. Numbers are limited to 32-bits of precision.'
Try the following statements:
IF 2147483647 GTR 2147483646 echo A is greater than B (will be TRUE)
IF 2147483648 GTR 2147483647 echo A is greater than B (will be FALSE!)
Any number greater than the max INT32 value will BREAK THE SCRIPT! Seeing as filesize is measured in bytes, the scripts will support a maximum filesize of about 255.9999997615814 MB !
Dynamically load JS inside JS
I need to do this frequently, so I use this:
var loadJS = function(url, implementationCode, location){
//url is URL of external file, implementationCode is the code
//to be called from the file, location is the location to
//insert the <script> element
var scriptTag = document.createElement('script');
scriptTag.src = url;
scriptTag.onload = implementationCode;
scriptTag.onreadystatechange = implementationCode;
location.appendChild(scriptTag);
};
var yourCodeToBeCalled = function(){
//your code goes here
}
loadJS('yourcode.js', yourCodeToBeCalled, document.body);
For more information, see this site How do I include a JavaScript file in another JavaScript file?, which is the source of my function idea.
Limiting floats to two decimal points
The method I use is that of string slicing. It's relatively quick and simple.
First, convert the float to a string, the choose the length you would like it to be.
float = str(float)[:5]
In the single line above, we've converted the value to a string, then kept the string only to its first four digits or characters (inclusive).
Hope that helps!
Convert a string representation of a hex dump to a byte array using Java?
I found Kernel Panic to have the solution most useful to me, but ran into problems if the hex string was an odd number. solved it this way:
boolean isOdd(int value)
{
return (value & 0x01) !=0;
}
private int hexToByte(byte[] out, int value)
{
String hexVal = "0123456789ABCDEF";
String hexValL = "0123456789abcdef";
String st = Integer.toHexString(value);
int len = st.length();
if (isOdd(len))
{
len+=1; // need length to be an even number.
st = ("0" + st); // make it an even number of chars
}
out[0]=(byte)(len/2);
for (int i =0;i<len;i+=2)
{
int hh = hexVal.indexOf(st.charAt(i));
if (hh == -1) hh = hexValL.indexOf(st.charAt(i));
int lh = hexVal.indexOf(st.charAt(i+1));
if (lh == -1) lh = hexValL.indexOf(st.charAt(i+1));
out[(i/2)+1] = (byte)((hh << 4)|lh);
}
return (len/2)+1;
}
I am adding a number of hex numbers to an array, so i pass the reference to the array I am using, and the int I need converted and returning the relative position of the next hex number. So the final byte array has [0] number of hex pairs, [1...] hex pairs, then the number of pairs...
How to call a stored procedure from Java and JPA
For me, only the following worked with Oracle 11g and Glassfish 2.1 (Toplink):
Query query = entityManager.createNativeQuery("BEGIN PROCEDURE_NAME(); END;");
query.executeUpdate();
The variant with curly braces resulted in ORA-00900.
How to increment variable under DOS?
Coming to the party very very late, but from my old memory of DOS batch files, you can keep adding a character to the string each loop then look for a string of that many of that character. for 250 iterations, you either have a very long "cycles" string, or you have one loop inside using one set of variables counting to 10, then another loop outside that uses another set of variable counting to 25.
Here is the basic loop to 30:
@echo off
rem put how many dots you want to loop
set cycles=..............................
set cntr=
:LOOP
set cntr=%cntr%.
echo around we go again
if "%cycles%"=="%cntr%" goto done
goto loop
:DONE
echo around we went
IIS error, Unable to start debugging on the webserver
If you can check your logs you should be able to get an error status and substatus.
Logs are usually located at %SystemDrive%\inetpub\logs\LogFiles
I just had to face a similar problem, looking at the log i've found:
2018-11-12 10:09:22 ::1 DEBUG /PPD/debugattach.aspx - 80 - ::1 - - 403 4 5 0
Here the status is 403 and substatus is 4, this table https://support.microsoft.com/en-ca/help/943891/the-http-status-code-in-iis-7-0-iis-7-5-and-iis-8-0 provided the knowledge to fix the problem! 403.4 is in fact SSL Required, once i've changed the project URL in Visual Studio from http to https (Project properties -> Web -> Server -> Project URL) the problem disappeared.
I've described my fix only to clarify the steps involved in fixing the issue, read all the answer and not just from "once i've changed the project URL..." and follow your logs!
Good luck!
Stop handler.postDelayed()
Boolean condition=false; //Instance variable declaration.
//-----------------Inside oncreate---------------------------------------------------
start =(Button)findViewById(R.id.id_start);
start.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
starthandler();
if(condition=true)
{
condition=false;
}
}
});
stop=(Button) findViewById(R.id.id_stoplocatingsmartplug);
stop.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
stophandler();
}
});
}
//-----------------Inside oncreate---------------------------------------------------
public void starthandler()
{
handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
if(!condition)
{
//Do something after 100ms
}
}
}, 5000);
}
public void stophandler()
{
condition=true;
}
Android Gallery on Android 4.4 (KitKat) returns different URI for Intent.ACTION_GET_CONTENT
This requires no special permissions, and works with the Storage Access Framework, as well as the unofficial ContentProvider
pattern (file path in _data
field).
/**
* Get a file path from a Uri. This will get the the path for Storage Access
* Framework Documents, as well as the _data field for the MediaStore and
* other file-based ContentProviders.
*
* @param context The context.
* @param uri The Uri to query.
* @author paulburke
*/
public static String getPath(final Context context, final Uri uri) {
final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
// DocumentProvider
if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
// ExternalStorageProvider
if (isExternalStorageDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
if ("primary".equalsIgnoreCase(type)) {
return Environment.getExternalStorageDirectory() + "/" + split[1];
}
// TODO handle non-primary volumes
}
// DownloadsProvider
else if (isDownloadsDocument(uri)) {
final String id = DocumentsContract.getDocumentId(uri);
final Uri contentUri = ContentUris.withAppendedId(
Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
return getDataColumn(context, contentUri, null, null);
}
// MediaProvider
else if (isMediaDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
Uri contentUri = null;
if ("image".equals(type)) {
contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
} else if ("video".equals(type)) {
contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
} else if ("audio".equals(type)) {
contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
}
final String selection = "_id=?";
final String[] selectionArgs = new String[] {
split[1]
};
return getDataColumn(context, contentUri, selection, selectionArgs);
}
}
// MediaStore (and general)
else if ("content".equalsIgnoreCase(uri.getScheme())) {
// Return the remote address
if (isGooglePhotosUri(uri))
return uri.getLastPathSegment();
return getDataColumn(context, uri, null, null);
}
// File
else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
return null;
}
/**
* Get the value of the data column for this Uri. This is useful for
* MediaStore Uris, and other file-based ContentProviders.
*
* @param context The context.
* @param uri The Uri to query.
* @param selection (Optional) Filter used in the query.
* @param selectionArgs (Optional) Selection arguments used in the query.
* @return The value of the _data column, which is typically a file path.
*/
public static String getDataColumn(Context context, Uri uri, String selection,
String[] selectionArgs) {
Cursor cursor = null;
final String column = "_data";
final String[] projection = {
column
};
try {
cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
null);
if (cursor != null && cursor.moveToFirst()) {
final int index = cursor.getColumnIndexOrThrow(column);
return cursor.getString(index);
}
} finally {
if (cursor != null)
cursor.close();
}
return null;
}
/**
* @param uri The Uri to check.
* @return Whether the Uri authority is ExternalStorageProvider.
*/
public static boolean isExternalStorageDocument(Uri uri) {
return "com.android.externalstorage.documents".equals(uri.getAuthority());
}
/**
* @param uri The Uri to check.
* @return Whether the Uri authority is DownloadsProvider.
*/
public static boolean isDownloadsDocument(Uri uri) {
return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}
/**
* @param uri The Uri to check.
* @return Whether the Uri authority is MediaProvider.
*/
public static boolean isMediaDocument(Uri uri) {
return "com.android.providers.media.documents".equals(uri.getAuthority());
}
/**
* @param uri The Uri to check.
* @return Whether the Uri authority is Google Photos.
*/
public static boolean isGooglePhotosUri(Uri uri) {
return "com.google.android.apps.photos.content".equals(uri.getAuthority());
}
See an up-to-date version of this method here.
Ruby: How to post a file via HTTP as multipart/form-data?
Well the solution with NetHttp has a drawback that is when posting big files it loads the whole file into memory first.
After playing a bit with it I came up with the following solution:
class Multipart
def initialize( file_names )
@file_names = file_names
end
def post( to_url )
boundary = '----RubyMultipartClient' + rand(1000000).to_s + 'ZZZZZ'
parts = []
streams = []
@file_names.each do |param_name, filepath|
pos = filepath.rindex('/')
filename = filepath[pos + 1, filepath.length - pos]
parts << StringPart.new ( "--" + boundary + "\r\n" +
"Content-Disposition: form-data; name=\"" + param_name.to_s + "\"; filename=\"" + filename + "\"\r\n" +
"Content-Type: video/x-msvideo\r\n\r\n")
stream = File.open(filepath, "rb")
streams << stream
parts << StreamPart.new (stream, File.size(filepath))
end
parts << StringPart.new ( "\r\n--" + boundary + "--\r\n" )
post_stream = MultipartStream.new( parts )
url = URI.parse( to_url )
req = Net::HTTP::Post.new(url.path)
req.content_length = post_stream.size
req.content_type = 'multipart/form-data; boundary=' + boundary
req.body_stream = post_stream
res = Net::HTTP.new(url.host, url.port).start {|http| http.request(req) }
streams.each do |stream|
stream.close();
end
res
end
end
class StreamPart
def initialize( stream, size )
@stream, @size = stream, size
end
def size
@size
end
def read ( offset, how_much )
@stream.read ( how_much )
end
end
class StringPart
def initialize ( str )
@str = str
end
def size
@str.length
end
def read ( offset, how_much )
@str[offset, how_much]
end
end
class MultipartStream
def initialize( parts )
@parts = parts
@part_no = 0;
@part_offset = 0;
end
def size
total = 0
@parts.each do |part|
total += part.size
end
total
end
def read ( how_much )
if @part_no >= @parts.size
return nil;
end
how_much_current_part = @parts[@part_no].size - @part_offset
how_much_current_part = if how_much_current_part > how_much
how_much
else
how_much_current_part
end
how_much_next_part = how_much - how_much_current_part
current_part = @parts[@part_no].read(@part_offset, how_much_current_part )
if how_much_next_part > 0
@part_no += 1
@part_offset = 0
next_part = read ( how_much_next_part )
current_part + if next_part
next_part
else
''
end
else
@part_offset += how_much_current_part
current_part
end
end
end
What is a Y-combinator?
Here are answers to the original questions, compiled from the article (which is TOTALY worth reading) mentioned in the answer by Nicholas Mancuso, as well as other answers:
What is a Y-combinator?
An Y-combinator is a "functional" (or a higher-order function — a function that operates on other functions) that takes a single argument, which is a function that isn't recursive, and returns a version of the function which is recursive.
Somewhat recursive =), but more in-depth definition:
A combinator — is just a lambda expression with no free variables.
Free variable — is a variable that is not a bound variable.
Bound variable — variable which is contained inside the body of a lambda expression that has that variable name as one of its arguments.
Another way to think about this is that combinator is such a lambda expression, in which you are able to replace the name of a combinator with its definition everywhere it is found and have everything still work (you will get into an infinite loop if combinator would contain reference to itself, inside the lambda body).
Y-combinator is a fixed-point combinator.
Fixed point of a function is an element of the function's domain that is mapped to itself by the function.
That is to say, c
is a fixed point of the function f(x)
if f(c) = c
This means f(f(...f(c)...)) = fn(c) = c
How do combinators work?
Examples below assume strong + dynamic typing:
Lazy (normal-order) Y-combinator:
This definition applies to languages with lazy (also: deferred, call-by-need) evaluation — evaluation strategy which delays the evaluation of an expression until its value is needed.
Y = ?f.(?x.f(x x)) (?x.f(x x)) = ?f.(?x.(x x)) (?x.f(x x))
What this means is that, for a given function f
(which is a non-recursive function), the corresponding recursive function can be obtained first by computing ?x.f(x x)
, and then applying this lambda expression to itself.
Strict (applicative-order) Y-combinator:
This definition applies to languages with strict (also: eager, greedy) evaluation — evaluation strategy in which an expression is evaluated as soon as it is bound to a variable.
Y = ?f.(?x.f(?y.((x x) y))) (?x.f(?y.((x x) y))) = ?f.(?x.(x x)) (?x.f(?y.((x x) y)))
It is same as lazy one in it's nature, it just has an extra ?
wrappers to delay the lambda's body evaluation. I've asked another question, somewhat related to this topic.
What are they good for?
Stolen borrowed from answer by Chris Ammerman: Y-combinator generalizes recursion, abstracting its implementation, and thereby separating it from the actual work of the function in question.
Even though, Y-combinator has some practical applications, it is mainly a theoretical concept, understanding of which will expand your overall vision and will, likely, increase your analytical and developer skills.
Are they useful in procedural languages?
As stated by Mike Vanier: it is possible to define a Y combinator in many statically typed languages, but (at least in the examples I've seen) such definitions usually require some non-obvious type hackery, because the Y combinator itself doesn't have a straightforward static type. That's beyond the scope of this article, so I won't mention it further
And as mentioned by Chris Ammerman: most procedural languages has static-typing.
So answer to this one — not really.
How to Diff between local uncommitted changes and origin
I know it's not an answer to the exact question asked, but I found this question looking to diff a file in a branch and a local uncommitted file and I figured I would share
Syntax:
git diff <commit-ish>:./ -- <path>
Examples:
git diff origin/master:./ -- README.md
git diff HEAD^:./ -- README.md
git diff stash@{0}:./ -- README.md
git diff 1A2B3C4D:./ -- README.md
(Thanks Eric Boehs for a way to not have to type the filename twice)
findAll() in yii
Try:
$id =101;
$comments = EmailArchive::model()->findAll(
array("condition"=>"email_id = $id","order"=>"id"));
OR
$id =101;
$criteria = new CDbCriteria();
$criteria->addCondition("email_id=:email_id");
$criteria->params = array(':email_id' => $id);
$comments = EmailArchive::model()->findAll($criteria);
OR
$Criteria = new CDbCriteria();
$Criteria->condition = "email_id = $id";
$Products = Product::model()->findAll($Criteria);
How line ending conversions work with git core.autocrlf between different operating systems
Things are about to change on the "eol conversion" front, with the upcoming Git 1.7.2:
A new config setting core.eol
is being added/evolved:
This is a replacement for the 'Add "core.eol
" config variable' commit that's currently in pu
(the last one in my series).
Instead of implying that "core.autocrlf=true
" is a replacement for "* text=auto
", it makes explicit the fact that autocrlf
is only for users who want to work with
CRLFs in their working directory on a repository that doesn't have text
file normalization.
When it is enabled, "core.eol" is ignored.
Introduce a new configuration variable, "core.eol
", that allows the user to set which line endings to use for end-of-line-normalized files in the working directory.
It defaults to "native
", which means CRLF on Windows and LF everywhere else.
Note that "core.autocrlf
" overrides core.eol
.
This means that:
[core]
autocrlf = true
puts CRLFs in the working directory even if core.eol
is set to "lf
".
core.eol:
Sets the line ending type to use in the working directory for files that have the text
property set.
Alternatives are 'lf', 'crlf' and 'native', which uses the platform's native line ending.
The default value is native
.
Other evolutions are being considered:
For 1.8, I would consider making core.autocrlf
just turn on normalization and leave the working directory line ending decision to core.eol, but that will break people's setups.
git 2.8 (March 2016) improves the way core.autocrlf
influences the eol:
See commit 817a0c7 (23 Feb 2016), commit 6e336a5, commit df747b8, commit df747b8 (10 Feb 2016), commit df747b8, commit df747b8 (10 Feb 2016), and commit 4b4024f, commit bb211b4, commit 92cce13, commit 320d39c, commit 4b4024f, commit bb211b4, commit 92cce13, commit 320d39c (05 Feb 2016) by Torsten Bögershausen (tboegi
).
(Merged by Junio C Hamano -- gitster
-- in commit c6b94eb, 26 Feb 2016)
convert.c
: refactor crlf_action
Refactor the determination and usage of crlf_action
.
Today, when no "crlf
" attribute are set on a file, crlf_action
is set to
CRLF_GUESS
. Use CRLF_UNDEFINED
instead, and search for "text
" or "eol
" as before.
Replace the old CRLF_GUESS
usage:
CRLF_GUESS && core.autocrlf=true -> CRLF_AUTO_CRLF
CRLF_GUESS && core.autocrlf=false -> CRLF_BINARY
CRLF_GUESS && core.autocrlf=input -> CRLF_AUTO_INPUT
Make more clear, what is what, by defining:
- CRLF_UNDEFINED : No attributes set. Temparally used, until core.autocrlf
and core.eol is evaluated and one of CRLF_BINARY,
CRLF_AUTO_INPUT or CRLF_AUTO_CRLF is selected
- CRLF_BINARY : No processing of line endings.
- CRLF_TEXT : attribute "text" is set, line endings are processed.
- CRLF_TEXT_INPUT: attribute "input" or "eol=lf" is set. This implies text.
- CRLF_TEXT_CRLF : attribute "eol=crlf" is set. This implies text.
- CRLF_AUTO : attribute "auto" is set.
- CRLF_AUTO_INPUT: core.autocrlf=input (no attributes)
- CRLF_AUTO_CRLF : core.autocrlf=true (no attributes)
As torek adds in the comments:
all these translations (any EOL conversion from eol=
or autocrlf
settings, and "clean
" filters) are run when files move from work-tree to index, i.e., during git add
rather than at git commit
time.
(Note that git commit -a
or --only
or --include
do add files to the index at that time, though.)
For more on that, see "What is difference between autocrlf and eol".
Finding Key associated with max Value in a Java Map
For completeness, here is a java-8 way of doing it
countMap.entrySet().stream().max((entry1, entry2) -> entry1.getValue() > entry2.getValue() ? 1 : -1).get().getKey();
or
Collections.max(countMap.entrySet(), (entry1, entry2) -> entry1.getValue() - entry2.getValue()).getKey();
or
Collections.max(countMap.entrySet(), Comparator.comparingInt(Map.Entry::getValue)).getKey();
How do I compare strings in GoLang?
Assuming there are no prepending/succeeding whitespace characters, there are still a few ways to assert string equality. Some of those are:
Here are some basic benchmark results (in these tests, strings.EqualFold(.., ..)
seems like the most performant choice):
goos: darwin
goarch: amd64
BenchmarkStringOps/both_strings_equal::equality_op-4 10000 182944 ns/op
BenchmarkStringOps/both_strings_equal::strings_equal_fold-4 10000 114371 ns/op
BenchmarkStringOps/both_strings_equal::fold_caser-4 10000 2599013 ns/op
BenchmarkStringOps/both_strings_equal::lower_caser-4 10000 3592486 ns/op
BenchmarkStringOps/one_string_in_caps::equality_op-4 10000 417780 ns/op
BenchmarkStringOps/one_string_in_caps::strings_equal_fold-4 10000 153509 ns/op
BenchmarkStringOps/one_string_in_caps::fold_caser-4 10000 3039782 ns/op
BenchmarkStringOps/one_string_in_caps::lower_caser-4 10000 3861189 ns/op
BenchmarkStringOps/weird_casing_situation::equality_op-4 10000 619104 ns/op
BenchmarkStringOps/weird_casing_situation::strings_equal_fold-4 10000 148489 ns/op
BenchmarkStringOps/weird_casing_situation::fold_caser-4 10000 3603943 ns/op
BenchmarkStringOps/weird_casing_situation::lower_caser-4 10000 3637832 ns/op
Since there are quite a few options, so here's the code to generate benchmarks.
package main
import (
"fmt"
"strings"
"testing"
"golang.org/x/text/cases"
"golang.org/x/text/language"
)
func BenchmarkStringOps(b *testing.B) {
foldCaser := cases.Fold()
lowerCaser := cases.Lower(language.English)
tests := []struct{
description string
first, second string
}{
{
description: "both strings equal",
first: "aaaa",
second: "aaaa",
},
{
description: "one string in caps",
first: "aaaa",
second: "AAAA",
},
{
description: "weird casing situation",
first: "aAaA",
second: "AaAa",
},
}
for _, tt := range tests {
b.Run(fmt.Sprintf("%s::equality op", tt.description), func(b *testing.B) {
for i := 0; i < b.N; i++ {
benchmarkStringEqualsOperation(tt.first, tt.second, b)
}
})
b.Run(fmt.Sprintf("%s::strings equal fold", tt.description), func(b *testing.B) {
for i := 0; i < b.N; i++ {
benchmarkStringsEqualFold(tt.first, tt.second, b)
}
})
b.Run(fmt.Sprintf("%s::fold caser", tt.description), func(b *testing.B) {
for i := 0; i < b.N; i++ {
benchmarkStringsFoldCaser(tt.first, tt.second, foldCaser, b)
}
})
b.Run(fmt.Sprintf("%s::lower caser", tt.description), func(b *testing.B) {
for i := 0; i < b.N; i++ {
benchmarkStringsLowerCaser(tt.first, tt.second, lowerCaser, b)
}
})
}
}
func benchmarkStringEqualsOperation(first, second string, b *testing.B) {
for n := 0; n < b.N; n++ {
_ = strings.ToLower(first) == strings.ToLower(second)
}
}
func benchmarkStringsEqualFold(first, second string, b *testing.B) {
for n := 0; n < b.N; n++ {
_ = strings.EqualFold(first, second)
}
}
func benchmarkStringsFoldCaser(first, second string, caser cases.Caser, b *testing.B) {
for n := 0; n < b.N; n++ {
_ = caser.String(first) == caser.String(second)
}
}
func benchmarkStringsLowerCaser(first, second string, caser cases.Caser, b *testing.B) {
for n := 0; n < b.N; n++ {
_ = caser.String(first) == caser.String(second)
}
}
How do I force detach Screen from another SSH session?
Short answer
- Reattach without ejecting others:
screen -x
- Get list of displays:
^A
*
, select the one to disconnect, press d
Explained answer
Background: When I was looking for the solution with same problem description, I have always landed on this answer. I would like to provide more sensible solution. (For example: the other attached screen has a different size and a I cannot force resize it in my terminal.)
Note: PREFIX
is usually ^A
= ctrl+a
Note: the display may also be called:
- "user front-end" (in
at
command manual in screen)
- "client" (tmux vocabulary where this functionality is
detach-client
)
- "terminal" (as we call the window in our user interface) /depending on
1. Reattach a session: screen -x
-x
attach to a not detached screen session without detaching it
2. List displays of this session: PREFIX
*
It is the default key binding for: PREFIX
:displays
.
Performing it within the screen, identify the other display we want to disconnect (e.g. smaller size). (Your current display is displayed in brighter color/bold when not selected).
term-type size user interface window Perms
---------- ------- ---------- ----------------- ---------- -----
screen 240x60 you@/dev/pts/2 nb 0(zsh) rwx
screen 78x40 you@/dev/pts/0 nb 0(zsh) rwx
Using arrows ?
?
, select the targeted display, press d
If nothing happens, you tried to detach your own display and screen will not detach it. If it was another one, within a second or two, the entry will disappear.
Press ENTER
to quit the listing.
Optionally: in order to make the content fit your screen, reflow: PREFIX
F
(uppercase F)
Excerpt from man page of screen:
displays
Shows a tabular listing of all currently connected user front-ends (displays). This is most useful for multiuser sessions. The following keys can be used in displays list:
mouseclick
Move to the selected line. Available when "mousetrack" is set to on.
space
Refresh the list
d
Detach that display
D
Power detach that display
C-g
, enter
, or escape
Exit the list
How to make all controls resize accordingly proportionally when window is maximized?
In WPF there are certain 'container' controls that automatically resize their contents and there are some that don't.
Here are some that do not resize their contents (I'm guessing that you are using one or more of these):
StackPanel
WrapPanel
Canvas
TabControl
Here are some that do resize their contents:
Grid
UniformGrid
DockPanel
Therefore, it is almost always preferable to use a Grid
instead of a StackPanel
unless you do not want automatic resizing to occur. Please note that it is still possible for a Grid
to not size its inner controls... it all depends on your Grid.RowDefinition
and Grid.ColumnDefinition
settings:
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="100" /> <!--<<< Exact Height... won't resize -->
<RowDefinition Height="Auto" /> <!--<<< Will resize to the size of contents -->
<RowDefinition Height="*" /> <!--<<< Will resize taking all remaining space -->
</Grid.RowDefinitions>
</Grid>
You can find out more about the Grid
control from the Grid
Class page on MSDN. You can also find out more about these container controls from the WPF Container Controls Overview page on MSDN.
Further resizing can be achieved using the FrameworkElement.HorizontalAlignment
and FrameworkElement.VerticalAlignment
properties. The default value of these properties is Stretch
which will stretch elements to fit the size of their containing controls. However, when they are set to any other value, the elements will not stretch.
UPDATE >>>
In response to the questions in your comment:
Use the Grid.RowDefinition
and Grid.ColumnDefinition
settings to organise a basic structure first... it is common to add Grid
controls into the cells of outer Grid
controls if need be. You can also use the Grid.ColumnSpan
and Grid.RowSpan
properties to enable controls to span multiple columns and/or rows of a Grid
.
It is most common to have at least one row/column with a Height
/Width
of "*"
which will fill all remaining space, but you can have two or more with this setting, in which case the remaining space will be split between the two (or more) rows/columns. 'Auto' is a good setting to use for the rows/columns that are not set to '"*"', but it really depends on how you want the layout to be.
There is no Auto
setting that you can use on the controls in the cells, but this is just as well, because we want the Grid
to size the controls for us... therefore, we don't want to set the Height
or Width
of these controls at all.
The point that I made about the FrameworkElement.HorizontalAlignment
and FrameworkElement.VerticalAlignment
properties was just to let you know of their existence... as their default value is already Stretch
, you don't generally need to set them explicitly.
The Margin
property is generally just used to space your controls out evenly... if you drag and drop controls from the Visual Studio Toolbox, VS will set the Margin
property to place your control exactly where you dropped it but generally, this is not what we want as it will mess with the auto sizing of controls. If you do this, then just delete or edit the Margin
property to suit your needs.
'Invalid update: invalid number of rows in section 0
You need to remove the object from your data array before you call deleteRowsAtIndexPaths:withRowAnimation:
. So, your code should look like this:
// Editing of rows is enabled
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
if (editingStyle == UITableViewCellEditingStyleDelete) {
//when delete is tapped
[currentCart removeObjectAtIndex:indexPath.row];
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
}
}
You can also simplify your code a little by using the array creation shortcut @[]
:
[tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];