FlutterError: Unable to load asset
Encountered the same issue with a slightly different code. In my case, I was using a "assets" folder subdivided into sub-folders for assets (sprites, audio, UI).
My code was simply at first in pubspec.yaml- alternative would be to detail every single file.
flutter:
assets:
- assets
Indentation and flutter clean was not enough to fix it. The files in the sub-folders were not loading by flutter. It seems like flutter needs to be "taken by the hand" and not looking at sub-folders without explicitly asking it to look at them. This worked for me:
flutter:
assets:
- assets/sprites/
- assets/audio/
- assets/UI/
So I had to detail each folder and each sub-folder that contains assets (mp3, jpg, etc). Doing so made the app work and saved me tons of time as the only solution detailed above would require me to manually list 30+ assets while the code here is just a few lines and easier to maintain.
ImageMagick security policy 'PDF' blocking conversion
I was experiencing this issue with nextcloud which would fail to create thumbnails for pdf files.
However, none of the suggested steps would solve the issue for me.
Eventually I found the reason: The accepted answer did work but I had to also restart php-fpm after editing the policy.xml file:
sudo systemctl restart php7.2-fpm.service
Flutter - The method was called on null
You have a CryptoListPresenter _presenter
but you are never initializing it. You should either be doing that when you declare it or in your initState()
(or another appropriate but called-before-you-need-it method).
One thing I find that helps is that if I know a member is functionally 'final', to actually set it to final as that way the analyzer complains that it hasn't been initialized.
EDIT:
I see diegoveloper beat me to answering this, and that the OP asked a follow up.
@Jake - it's hard for us to tell without knowing exactly what CryptoListPresenter is, but depending on what exactly CryptoListPresenter actually is, generally you'd do final CryptoListPresenter _presenter = new CryptoListPresenter(...);
, or
CryptoListPresenter _presenter;
@override
void initState() {
_presenter = new CryptoListPresenter(...);
}
convert:not authorized `aaaa` @ error/constitute.c/ReadImage/453
If you don't need to handle raster files and PDF/PS/EPS through the same tool, don't loosen ImageMagick's security.
Instead, keep your defense in depth for your web applications intact, check that your Ghostscript has been patched for all known -dSAFER
vulnerabilities and then invoke it directly.
gs -dSAFER -r300 -sDEVICE=png16m -o document-%03d.png document.pdf
-dSAFER
opts you out of the legacy-compatibility "run Postscript will full permission to interact with the outside world as a turing-complete programming language" mode.
-r300
sets the desired DPI to 300 (the default is 72)
-sDEVICE
specifies the output format (See the Devices section of the manual for other choices.)
-o
is a shorthand for -dBATCH -dNOPAUSE -sOutputFile=
- This section of the Ghostscript manual gives some example formats for for multi-file filename output but, for the actual syntax definition, it points you at the documentation for the C printf(3) function.
If you're rendering EPS files, add -dEPSCrop
so it won't pad your output to page size and use -sDEVICE=pngalpha
to get transparent backgrounds.
How to update RecyclerView Adapter Data?
These methods are efficient and good to start using a basic RecyclerView
.
private List<YourItem> items;
public void setItems(List<YourItem> newItems)
{
clearItems();
addItems(newItems);
}
public void addItem(YourItem item, int position)
{
if (position > items.size()) return;
items.add(item);
notifyItemInserted(position);
}
public void addMoreItems(List<YourItem> newItems)
{
int position = items.size() + 1;
newItems.addAll(newItems);
notifyItemChanged(position, newItems);
}
public void addItems(List<YourItem> newItems)
{
items.addAll(newItems);
notifyDataSetChanged();
}
public void clearItems()
{
items.clear();
notifyDataSetChanged();
}
public void addLoader()
{
items.add(null);
notifyItemInserted(items.size() - 1);
}
public void removeLoader()
{
items.remove(items.size() - 1);
notifyItemRemoved(items.size());
}
public void removeItem(int position)
{
if (position >= items.size()) return;
items.remove(position);
notifyItemRemoved(position);
}
public void swapItems(int positionA, int positionB)
{
if (positionA > items.size()) return;
if (positionB > items.size()) return;
YourItem firstItem = items.get(positionA);
videoList.set(positionA, items.get(positionB));
videoList.set(positionB, firstItem);
notifyDataSetChanged();
}
You can implement them inside of an Adapter Class or in your Fragment or Activity but in that case you have to instantiate the Adapter to call the notification methods. In my case I usually implement it in the Adapter.
How to loop through an array of objects in swift
The photos
property is an optional array and must be unwrapped before accessing its elements (the same as you do to get the count
property of the array):
for var i = 0; i < userPhotos!.count ; ++i {
let url = userPhotos![i].url
}
How to open a different activity on recyclerView item onclick
The problem occurs in declaring context, while using Glide for ImageView or While using intent in recyclerview for item onClick. I Found this working for me which helps me to Declare context to use in Glide or Intent or Toast.
public class NoteAdapter extends FirestoreRecyclerAdapter<Note,NoteAdapter.NoteHolder> {
Context context;
public NoteAdapter(@NonNull FirestoreRecyclerOptions<Note> options) {
super(options);
}
@Override
protected void onBindViewHolder(@NonNull NoteHolder holder, int position, @NonNull Note model) {
holder.r_tv.setText(model.getTitle());
Glide.with(CategoryActivity.context).load(model.getImage()).into(holder.r_iv);
context = holder.itemView.getContext();
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(context, SuggestActivity.class);
context.startActivity(i);
}
});
}
@NonNull
@Override
public NoteHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_category,parent,false);
return new NoteHolder(v);
}
public static class NoteHolder extends RecyclerView.ViewHolder
{
TextView r_tv;
ImageView r_iv;
public NoteHolder(@NonNull View itemView) {
super(itemView);
r_tv = itemView.findViewById(R.id.r_tv);
r_iv = itemView.findViewById(R.id.r_iv);
}
}
}
Can not deserialize instance of java.lang.String out of START_ARRAY token
The error is:
Can not deserialize instance of java.lang.String out of START_ARRAY
token at [Source: line: 1, column: 1095] (through reference chain:
JsonGen["platforms"])
In JSON, platforms
look like this:
"platforms": [
{
"platform": "iphone"
},
{
"platform": "ipad"
},
{
"platform": "android_phone"
},
{
"platform": "android_tablet"
}
]
So try change your pojo to something like this:
private List platforms;
public List getPlatforms(){
return this.platforms;
}
public void setPlatforms(List platforms){
this.platforms = platforms;
}
EDIT: you will need change mobile_networks
too. Will look like this:
private List mobile_networks;
public List getMobile_networks() {
return mobile_networks;
}
public void setMobile_networks(List mobile_networks) {
this.mobile_networks = mobile_networks;
}
Unable to add window -- token null is not valid; is your activity running?
This error happens when you are trying to show popUpWindow too early ,to fix it, give Id to main layout as main_layout
and use below code
Java:
findViewById(R.id.main_layout).post(new Runnable() {
public void run() {
popupWindow.showAtLocation(findViewById(R.id.main_layout), Gravity.CENTER, 0, 0);
}
});
Kotlin:
main_layout.post {
popupWindow?.showAtLocation(main_layout, Gravity.CENTER, 0, 0)
}
Credit to @kordzik
Multipart File Upload Using Spring Rest Template + Spring Web MVC
For those who are getting the error as:
I/O error on POST request for "anothermachine:31112/url/path";: class path
resource [fileName.csv] cannot be resolved to URL because it does not exist.
It can be resolved by using the
LinkedMultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
map.add("file", new FileSystemResource(file));
If the file is not present in the classpath, and an absolute path is required.
Display a RecyclerView in Fragment
This was asked some time ago now, but based on the answer that @nacho_zona3 provided, and previous experience with fragments, the issue is that the views have not been created by the time you are trying to find them with the findViewById()
method in onCreate()
to fix this, move the following code:
// 1. get a reference to recyclerView
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.list);
// 2. set layoutManger
recyclerView.setLayoutManager(new LinearLayoutManager(this));
// this is data fro recycler view
ItemData itemsData[] = { new ItemData("Indigo",R.drawable.circle),
new ItemData("Red",R.drawable.color_ic_launcher),
new ItemData("Blue",R.drawable.indigo),
new ItemData("Green",R.drawable.circle),
new ItemData("Amber",R.drawable.color_ic_launcher),
new ItemData("Deep Orange",R.drawable.indigo)};
// 3. create an adapter
MyAdapter mAdapter = new MyAdapter(itemsData);
// 4. set adapter
recyclerView.setAdapter(mAdapter);
// 5. set item animator to DefaultAnimator
recyclerView.setItemAnimator(new DefaultItemAnimator());
to your fragment's onCreateView()
call. A small amount of refactoring is required because all variables and methods called from this method have to be static. The final code should look like:
public class ColorsFragment extends Fragment {
public ColorsFragment() {}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_colors, container, false);
// 1. get a reference to recyclerView
RecyclerView recyclerView = (RecyclerView) rootView.findViewById(R.id.list);
// 2. set layoutManger
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
// this is data fro recycler view
ItemData itemsData[] = {
new ItemData("Indigo", R.drawable.circle),
new ItemData("Red", R.drawable.color_ic_launcher),
new ItemData("Blue", R.drawable.indigo),
new ItemData("Green", R.drawable.circle),
new ItemData("Amber", R.drawable.color_ic_launcher),
new ItemData("Deep Orange", R.drawable.indigo)
};
// 3. create an adapter
MyAdapter mAdapter = new MyAdapter(itemsData);
// 4. set adapter
recyclerView.setAdapter(mAdapter);
// 5. set item animator to DefaultAnimator
recyclerView.setItemAnimator(new DefaultItemAnimator());
return rootView;
}
}
So the main thing here is that anywhere you call findViewById()
you will need to use rootView.findViewById()
How to get file name from file path in android
I think you can use substring method to get name of the file from the path string.
String path=":/storage/sdcard0/DCIM/Camera/1414240995236.jpg";
// it contains your image path...I'm using a temp string...
String filename=path.substring(path.lastIndexOf("/")+1);
Is there an addHeaderView equivalent for RecyclerView?
Maybe wrap header and recyclerview into a coordinatorlayout:
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:elevation="0dp">
<View
android:id="@+id/header"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_scrollFlags="scroll" />
</android.support.design.widget.AppBarLayout>
<android.support.v7.widget.RecyclerView
android:id="@+id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior" />
Can't find keyplane that supports type 4 for keyboard iPhone-Portrait-NumberPad; using 3876877096_Portrait_iPhone-Simple-Pad_Default
Why the long code and not use the UIToolbar? since the warning is still persist?
UIToolbar is working for any iOS Version here's my sample code
UIToolbar *doneToolbar = [[UIToolbar alloc] initWithFrame:(CGRect){0, 0, 50, 50}]; // Create and init
doneToolbar.barStyle = UIBarStyleBlackTranslucent; // Specify the preferred barStyle
doneToolbar.items = @[
[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil],
[[UIBarButtonItem alloc] initWithTitle:@"Done" style:UIBarButtonItemStylePlain target:self action:@selector(doneEditAction)] // Add your target action
]; // Define items -- you can add more
yourField.inputAccessoryView = doneToolbar; // Now add toolbar to your field's inputview and run
[doneToolbar sizeToFit]; // call this to auto fit to the view
- (void)doneEditAction {
[self.view endEditing:YES];
}
notifyDataSetChanged not working on RecyclerView
Just to complement the other answers as I don't think anyone mentioned this here: notifyDataSetChanged()
should be executed on the main thread (other notify<Something>
methods of RecyclerView.Adapter
as well, of course)
From what I gather, since you have the parsing procedures and the call to notifyDataSetChanged()
in the same block, either you're calling it from a worker thread, or you're doing JSON parsing on main thread (which is also a no-no as I'm sure you know). So the proper way would be:
protected void parseResponse(JSONArray response, String url) {
// insert dummy data for demo
// <yadda yadda yadda>
mBusinessAdapter = new BusinessAdapter(mBusinesses);
// or just use recyclerView.post() or [Fragment]getView().post()
// instead, but make sure views haven't been destroyed while you were
// parsing
new Handler(Looper.getMainLooper()).post(new Runnable() {
public void run() {
mBusinessAdapter.notifyDataSetChanged();
}
});
}
PS Weird thing is, I don't think you get any indications about the main thread thing from either IDE or run-time logs. This is just from my personal observations: if I do call notifyDataSetChanged()
from a worker thread, I don't get the obligatory Only the original thread that created a view hierarchy can touch its views message or anything like that - it just fails silently (and in my case one off-main-thread call can even prevent succeeding main-thread calls from functioning properly, probably because of some kind of race condition)
Moreover, neither the RecyclerView.Adapter api reference nor the relevant official dev guide explicitly mention the main thread requirement at the moment (the moment is 2017) and none of the Android Studio lint inspection rules seem to concern this issue either.
But, here is an explanation of this by the author himself
Create a button programmatically and set a background image
Swift 5 version of accepted answer:
let image = UIImage(named: "image_name")
let button = UIButton(type: UIButton.ButtonType.custom)
button.frame = CGRect(x: 100, y: 100, width: 200, height: 100)
button.setImage(image, for: .normal)
button.addTarget(self, action: #selector(function), for: .touchUpInside)
//button.backgroundColor = .lightGray
self.view.addSubview(button)
where of course
@objc func function() {...}
The image is aligned to center by default. You can change this by setting button's imageEdgeInsets, like this:
// In this case image is 40 wide and aligned to the left
button.imageEdgeInsets = UIEdgeInsets(top: 5, left: 5, bottom: 5, right: button.frame.width - 45)
How do I use disk caching in Picasso?
I don't know how good that solution is but it is definitely THE EASY
ONE i just used in my app and it is working fine
you load the image like that
public void loadImage (){
Picasso picasso = Picasso.get();
picasso.setIndicatorsEnabled(true);
picasso.load(quiz.getImageUrl()).into(quizImage);
}
You can get the bimap
like that
Bitmap bitmap = Picasso.get().load(quiz.getImageUrl()).get();
Now covert that Bitmap
into a JPG
file and store in the in the cache, below is complete code for getting the bimap and caching it
Thread thread = new Thread() {
public void run() {
File file = new File(getCacheDir() + "/" +member.getMemberId() + ".jpg");
try {
Bitmap bitmap = Picasso.get().load(uri).get();
FileOutputStream fOut = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100,new FileOutputStream(file));
fOut.flush();
fOut.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
};
thread.start();
})
the get()
method of Piccasso
need to be called on separate thread , i am saving that image also on that same thread.
Once the image is saved you can get all the files like that
List<File> files = new LinkedList<>(Arrays.asList(context.getExternalCacheDir().listFiles()));
now you can find the file you are looking for like below
for(File file : files){
if(file.getName().equals("fileyouarelookingfor" + ".jpg")){ // you need the name of the file, for example you are storing user image and the his image name is same as his id , you can call getId() on user to get the file name
Picasso.get() // if file found then load it
.load(file)
.into(mThumbnailImage);
return; // return
}
// fetch it over the internet here because the file is not found
}
open the file upload dialogue box onclick the image
<input type="file" id="imgupload" style="display:none"/>
<label for='imgupload'> <button id="OpenImgUpload">Image Upload</button></label>
On click of for= attribute will automatically focus on "file input" and upload dialog box will open
Summernote image upload
Summernote converts your uploaded images to a base64 encoded string by default, you can process this string or as other fellows mentioned you can upload images using onImageUpload
callback. You can take a look at this gist which I modified a bit to adapt laravel csrf token
here. But that did not work for me and I had no time to find out why! Instead, I solved it via a server-side solution based on this blog post. It gets the output of the summernote and then it will upload the images and updates the final markdown HTML.
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
Route::get('/your-route-to-editor', function () {
return view('your-view');
});
Route::post('/your-route-to-processor', function (Request $request) {
$this->validate($request, [
'editordata' => 'required',
]);
$data = $request->input('editordata');
//loading the html data from the summernote editor and select the img tags from it
$dom = new \DomDocument();
$dom->loadHtml($data, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
$images = $dom->getElementsByTagName('img');
foreach($images as $k => $img){
//for now src attribute contains image encrypted data in a nonsence string
$data = $img->getAttribute('src');
//getting the original file name that is in data-filename attribute of img
$file_name = $img->getAttribute('data-filename');
//extracting the original file name and extension
$arr = explode('.', $file_name);
$upload_base_directory = 'public/';
$original_file_name='time()'.$k;
$original_file_extension='png';
if (sizeof($arr) == 2) {
$original_file_name = $arr[0];
$original_file_extension = $arr[1];
}
else
{
//the file name contains extra . in itself
$original_file_name = implode("_",array_slice($arr,0,sizeof($arr)-1));
$original_file_extension = $arr[sizeof($arr)-1];
}
list($type, $data) = explode(';', $data);
list(, $data) = explode(',', $data);
$data = base64_decode($data);
$path = $upload_base_directory.$original_file_name.'.'.$original_file_extension;
//uploading the image to an actual file on the server and get the url to it to update the src attribute of images
Storage::put($path, $data);
$img->removeAttribute('src');
//you can remove the data-filename attribute here too if you want.
$img->setAttribute('src', Storage::url($path));
// data base stuff here :
//saving the attachments path in an array
}
//updating the summernote WYSIWYG markdown output.
$data = $dom->saveHTML();
// data base stuff here :
// save the post along with it attachments array
return view('your-preview-page')->with(['data'=>$data]);
});
Write Base64-encoded image to file
Try this:
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;
public class WriteImage
{
public static void main( String[] args )
{
BufferedImage image = null;
try {
URL url = new URL("URL_IMAGE");
image = ImageIO.read(url);
ImageIO.write(image, "jpg",new File("C:\\out.jpg"));
ImageIO.write(image, "gif",new File("C:\\out.gif"));
ImageIO.write(image, "png",new File("C:\\out.png"));
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Done");
}
}
ImportError: numpy.core.multiarray failed to import
I used Anaconda environment and had the same issue. I tried all the aforementioned approaches and, alas, it didn't help me. Accumulated the suggestions, here the way which helped me:
Delete all NumPy folders in the virtual environment or in the system if you don't use a virtual environment, for example in my case:
~/home/anaconda3/envs//lib/python/site-packages/numpy
~/home/anaconda3/envs//lib/python/site-packages/numpy.libs
~/home/anaconda3/envs//lib/python/site-packages/numpy-.dist-info
Install new Numpy with:
pip install numpy -U
Hope, it could help in the same case
Getting path of captured image in Android using camera intent
There is a solution to create file (on external cache dir or anywhere else) and put this file's uri as output extra to camera intent - this will define path where taken picture will be stored.
Here is an example:
File file;
Uri fileUri;
final int RC_TAKE_PHOTO = 1;
private void takePhoto() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
file = new File(getActivity().getExternalCacheDir(),
String.valueOf(System.currentTimeMillis()) + ".jpg");
fileUri = Uri.fromFile(file);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
getActivity().startActivityForResult(intent, RC_TAKE_PHOTO);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RC_TAKE_PHOTO && resultCode == RESULT_OK) {
//do whatever you need with taken photo using file or fileUri
}
}
}
Then if you don't need the file anymore, you can delete it using file.delete();
By the way, files from cache dir will be removed when user clears app's cache from apps settings.
Redirect to Action by parameter mvc
This should work!
[HttpPost]
public ActionResult RedirectToImages(int id)
{
return RedirectToAction("Index", "ProductImageManeger", new { id = id });
}
[HttpGet]
public ViewResult Index(int id)
{
return View(_db.ProductImages.Where(rs => rs.ProductId == id).ToList());
}
Notice that you don't have to pass the name of view if you are returning the same view as implemented by the action.
Your view should inherit the model as this:
@model <Your class name>
You can then access your model in view as:
@Model.<property_name>
HTML5 Canvas Resize (Downscale) Image High Quality?
Suggestion 1 - extend the process pipe-line
You can use step-down as I describe in the links you refer to but you appear to use them in a wrong way.
Step down is not needed to scale images to ratios above 1:2 (typically, but not limited to). It is where you need to do a drastic down-scaling you need to split it up in two (and rarely, more) steps depending on content of the image (in particular where high-frequencies such as thin lines occur).
Every time you down-sample an image you will loose details and information. You cannot expect the resulting image to be as clear as the original.
If you are then scaling down the images in many steps you will loose a lot of information in total and the result will be poor as you already noticed.
Try with just one extra step, or at tops two.
Convolutions
In case of Photoshop notice that it applies a convolution after the image has been re-sampled, such as sharpen. It's not just bi-cubic interpolation that takes place so in order to fully emulate Photoshop we need to also add the steps Photoshop is doing (with the default setup).
For this example I will use my original answer that you refer to in your post, but I have added a sharpen convolution to it to improve quality as a post process (see demo at bottom).
Here is code for adding sharpen filter (it's based on a generic convolution filter - I put the weight matrix for sharpen inside it as well as a mix factor to adjust the pronunciation of the effect):
Usage:
sharpen(context, width, height, mixFactor);
The mixFactor
is a value between [0.0, 1.0] and allow you do downplay the sharpen effect - rule-of-thumb: the less size the less of the effect is needed.
Function (based on this snippet):
function sharpen(ctx, w, h, mix) {
var weights = [0, -1, 0, -1, 5, -1, 0, -1, 0],
katet = Math.round(Math.sqrt(weights.length)),
half = (katet * 0.5) |0,
dstData = ctx.createImageData(w, h),
dstBuff = dstData.data,
srcBuff = ctx.getImageData(0, 0, w, h).data,
y = h;
while(y--) {
x = w;
while(x--) {
var sy = y,
sx = x,
dstOff = (y * w + x) * 4,
r = 0, g = 0, b = 0, a = 0;
for (var cy = 0; cy < katet; cy++) {
for (var cx = 0; cx < katet; cx++) {
var scy = sy + cy - half;
var scx = sx + cx - half;
if (scy >= 0 && scy < h && scx >= 0 && scx < w) {
var srcOff = (scy * w + scx) * 4;
var wt = weights[cy * katet + cx];
r += srcBuff[srcOff] * wt;
g += srcBuff[srcOff + 1] * wt;
b += srcBuff[srcOff + 2] * wt;
a += srcBuff[srcOff + 3] * wt;
}
}
}
dstBuff[dstOff] = r * mix + srcBuff[dstOff] * (1 - mix);
dstBuff[dstOff + 1] = g * mix + srcBuff[dstOff + 1] * (1 - mix);
dstBuff[dstOff + 2] = b * mix + srcBuff[dstOff + 2] * (1 - mix)
dstBuff[dstOff + 3] = srcBuff[dstOff + 3];
}
}
ctx.putImageData(dstData, 0, 0);
}
The result of using this combination will be:
ONLINE DEMO HERE
Depending on how much of the sharpening you want to add to the blend you can get result from default "blurry" to very sharp:
Suggestion 2 - low level algorithm implementation
If you want to get the best result quality-wise you'll need to go low-level and consider to implement for example this brand new algorithm to do this.
See Interpolation-Dependent Image Downsampling (2011) from IEEE.
Here is a link to the paper in full (PDF).
There are no implementations of this algorithm in JavaScript AFAIK of at this time so you're in for a hand-full if you want to throw yourself at this task.
The essence is (excerpts from the paper):
Abstract
An interpolation oriented adaptive down-sampling algorithm is proposed
for low bit-rate image coding in this paper. Given an image, the
proposed algorithm is able to obtain a low resolution image, from
which a high quality image with the same resolution as the input
image can be interpolated. Different from the traditional
down-sampling algorithms, which are independent from the
interpolation process, the proposed down-sampling algorithm hinges the
down-sampling to the interpolation process. Consequently, the
proposed down-sampling algorithm is able to maintain the original
information of the input image to the largest extent. The down-sampled
image is then fed into JPEG. A total variation (TV) based post
processing is then applied to the decompressed low resolution image.
Ultimately, the processed image is interpolated to maintain the
original resolution of the input image. Experimental results verify
that utilizing the downsampled image by the proposed algorithm, an
interpolated image with much higher quality can be achieved. Besides,
the proposed algorithm is able to achieve superior performance than
JPEG for low bit rate image coding.
(see provided link for all details, formulas etc.)
php resize image on upload
Building onto answer from @zeusstl, for multiple images uploaded:
function img_resize()
{
$input = 'input-upload-img1'; // Name of input
$maxDim = 400;
foreach ($_FILES[$input]['tmp_name'] as $file_name){
list($width, $height, $type, $attr) = getimagesize( $file_name );
if ( $width > $maxDim || $height > $maxDim ) {
$target_filename = $file_name;
$ratio = $width/$height;
if( $ratio > 1) {
$new_width = $maxDim;
$new_height = $maxDim/$ratio;
} else {
$new_width = $maxDim*$ratio;
$new_height = $maxDim;
}
$src = imagecreatefromstring( file_get_contents( $file_name ) );
$dst = imagecreatetruecolor( $new_width, $new_height );
imagecopyresampled( $dst, $src, 0, 0, 0, 0, $new_width, $new_height, $width, $height );
imagedestroy( $src );
imagepng( $dst, $target_filename ); // adjust format as needed
imagedestroy( $dst );
}
}
}
Adding Table rows Dynamically in Android
Create an init() function and point the table layout.
Then create the needed rows and columns.
public void init() {
TableLayout stk = (TableLayout) findViewById(R.id.table_main);
TableRow tbrow0 = new TableRow(this);
TextView tv0 = new TextView(this);
tv0.setText(" Sl.No ");
tv0.setTextColor(Color.WHITE);
tbrow0.addView(tv0);
TextView tv1 = new TextView(this);
tv1.setText(" Product ");
tv1.setTextColor(Color.WHITE);
tbrow0.addView(tv1);
TextView tv2 = new TextView(this);
tv2.setText(" Unit Price ");
tv2.setTextColor(Color.WHITE);
tbrow0.addView(tv2);
TextView tv3 = new TextView(this);
tv3.setText(" Stock Remaining ");
tv3.setTextColor(Color.WHITE);
tbrow0.addView(tv3);
stk.addView(tbrow0);
for (int i = 0; i < 25; i++) {
TableRow tbrow = new TableRow(this);
TextView t1v = new TextView(this);
t1v.setText("" + i);
t1v.setTextColor(Color.WHITE);
t1v.setGravity(Gravity.CENTER);
tbrow.addView(t1v);
TextView t2v = new TextView(this);
t2v.setText("Product " + i);
t2v.setTextColor(Color.WHITE);
t2v.setGravity(Gravity.CENTER);
tbrow.addView(t2v);
TextView t3v = new TextView(this);
t3v.setText("Rs." + i);
t3v.setTextColor(Color.WHITE);
t3v.setGravity(Gravity.CENTER);
tbrow.addView(t3v);
TextView t4v = new TextView(this);
t4v.setText("" + i * 15 / 32 * 10);
t4v.setTextColor(Color.WHITE);
t4v.setGravity(Gravity.CENTER);
tbrow.addView(t4v);
stk.addView(tbrow);
}
}
Call init function in your onCreate method:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
init();
}
Layout file like:
<ScrollView
android:id="@+id/scrollView1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#3d455b"
android:layout_alignParentLeft="true" >
<HorizontalScrollView
android:id="@+id/hscrll1"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<RelativeLayout
android:id="@+id/RelativeLayout1"
android:layout_width="fill_parent"
android:layout_gravity="center"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TableLayout
android:id="@+id/table_main"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true" >
</TableLayout>
</RelativeLayout>
</HorizontalScrollView>
</ScrollView>
Will look like:
Get Selected Item Using Checkbox in Listview
I had similar problem. Provided xml sample is put as single ListViewItem, and i couldn't click on Item itself, but checkbox was workng.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="50dp"
android:id="@+id/source_container"
>
<ImageView
android:layout_width="40dp"
android:layout_height="40dp"
android:id="@+id/menu_source_icon"
android:background="@drawable/bla"
android:layout_margin="5dp"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/menu_source_name"
android:text="Test"
android:textScaleX="1.5"
android:textSize="20dp"
android:padding="8dp"
android:layout_weight="1"
android:layout_gravity="center_vertical"
android:textColor="@color/source_text_color"/>
<CheckBox
android:layout_width="40dp"
android:layout_height="match_parent"
android:id="@+id/menu_source_check_box"/>
</LinearLayout>
Solution: add attribute
android:focusable="false"
to CheckBox control.
Scale Image to fill ImageView width and keep aspect ratio
I had a similar issue, I found the reason for this is because you need to calculate the dp
. Android studio is calculating the ImageView
when you load it from the drawable
, but when you are using another method, like loading from bitmap the dp
is not automatically accounted for,
Here is my xml
<ImageView
android:id="@+id/imageViewer"
android:layout_width="match_parent"
android:layout_height="match_parent"//dp is not automaticly updated, when loading from a other source
android:scaleType="fitCenter"
tools:srcCompat="@drawable/a8" />
I'm using Kotlin, and loading drawable from an asset file, here's how I calculate this
val d = Drawable.createFromStream(assets.open("imageData/${imageName}.png"), null)
bitHeight = d.minimumHeight//get the image height
imageViewer.layoutParams.height = (bitHeight * resources.displayMetrics.density).toInt()//set the height
imageViewer.setImageDrawable(d)//set the image from the drawable
imageViewer.requestLayout()//here I apply it to the layout
How to upload images into MySQL database using PHP code
This is the perfect code for uploading and displaying image through MySQL database.
<html>
<body>
<form method="post" enctype="multipart/form-data">
<input type="file" name="image"/>
<input type="submit" name="submit" value="Upload"/>
</form>
<?php
if(isset($_POST['submit']))
{
if(getimagesize($_FILES['image']['tmp_name'])==FALSE)
{
echo " error ";
}
else
{
$image = $_FILES['image']['tmp_name'];
$image = addslashes(file_get_contents($image));
saveimage($image);
}
}
function saveimage($image)
{
$dbcon=mysqli_connect('localhost','root','','dbname');
$qry="insert into tablename (name) values ('$image')";
$result=mysqli_query($dbcon,$qry);
if($result)
{
echo " <br/>Image uploaded.";
header('location:urlofpage.php');
}
else
{
echo " error ";
}
}
?>
</body>
</html>
Equivalent of Super Keyword in C#
C# equivalent of your code is
class Imagedata : PDFStreamEngine
{
// C# uses "base" keyword whenever Java uses "super"
// so instead of super(...) in Java we should call its C# equivalent (base):
public Imagedata()
: base(ResourceLoader.loadProperties("org/apache/pdfbox/resources/PDFTextStripper.properties", true))
{ }
// Java methods are virtual by default, when C# methods aren't.
// So we should be sure that processOperator method in base class
// (that is PDFStreamEngine)
// declared as "virtual"
protected override void processOperator(PDFOperator operations, List arguments)
{
base.processOperator(operations, arguments);
}
}
Set Icon Image in Java
Your problem is often due to looking in the wrong place for the image, or if your classes and images are in a jar file, then looking for files where files don't exist. I suggest that you use resources to get rid of the second problem.
e.g.,
// the path must be relative to your *class* files
String imagePath = "res/Image.png";
InputStream imgStream = Game.class.getResourceAsStream(imagePath );
BufferedImage myImg = ImageIO.read(imgStream);
// ImageIcon icon = new ImageIcon(myImg);
// use icon here
game.frame.setIconImage(myImg);
AngularJS Uploading An Image With ng-upload
There's little-no documentation on angular for uploading files. A lot of solutions require custom directives other dependencies (jquery in primis... just to upload a file...). After many tries I've found this with just angularjs (tested on v.1.0.6)
html
<input type="file" name="file" onchange="angular.element(this).scope().uploadFile(this.files)"/>
Angularjs (1.0.6) not support ng-model on "input-file" tags so you have to do it in a "native-way" that pass the all (eventually) selected files from the user.
controller
$scope.uploadFile = function(files) {
var fd = new FormData();
//Take the first selected file
fd.append("file", files[0]);
$http.post(uploadUrl, fd, {
withCredentials: true,
headers: {'Content-Type': undefined },
transformRequest: angular.identity
}).success( ...all right!... ).error( ..damn!... );
};
The cool part is the undefined content-type and the transformRequest: angular.identity that give at the $http the ability to choose the right "content-type" and manage the boundary needed when handling multipart data.
Change Image of ImageView programmatically in Android
That happens because you're setting the src of the ImageView
instead of the background.
Use this instead:
qImageView.setBackgroundResource(R.drawable.thumbs_down);
Here's a thread that talks about the differences between the two methods.
Clone an image in cv2 python
My favorite method uses cv2.copyMakeBorder with no border, like so.
copy = cv2.copyMakeBorder(original,0,0,0,0,cv2.BORDER_REPLICATE)
How can I print using JQuery
function printResult() {
var DocumentContainer = document.getElementById('your_div_id');
var WindowObject = window.open('', "PrintWindow", "width=750,height=650,top=50,left=50,toolbars=no,scrollbars=yes,status=no,resizable=yes");
WindowObject.document.writeln(DocumentContainer.innerHTML);
WindowObject.document.close();
WindowObject.focus();
WindowObject.print();
WindowObject.close();
}
Convert Uri to String and String to Uri
You can use Drawable instead of Uri.
ImageView iv=(ImageView)findViewById(R.id.imageView1);
String pathName = "/external/images/media/470939";
Drawable image = Drawable.createFromPath(pathName);
iv.setImageDrawable(image);
This would work.
Go: panic: runtime error: invalid memory address or nil pointer dereference
According to the docs for func (*Client) Do
:
"An error is returned if caused by client policy (such as CheckRedirect), or if there was an HTTP protocol error. A non-2xx response doesn't cause an error.
When err is nil, resp always contains a non-nil resp.Body."
Then looking at this code:
res, err := client.Do(req)
defer res.Body.Close()
if err != nil {
return nil, err
}
I'm guessing that err
is not nil
. You're accessing the .Close()
method on res.Body
before you check for the err
.
The defer
only defers the function call. The field and method are accessed immediately.
So instead, try checking the error immediately.
res, err := client.Do(req)
if err != nil {
return nil, err
}
defer res.Body.Close()
How to create a circular ImageView in Android?
I too needed a rounded ImageView, I used the below code, you can modify it accordingly:
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.ImageView;
public class RoundedImageView extends ImageView {
public RoundedImageView(Context context) {
super(context);
}
public RoundedImageView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public RoundedImageView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
protected void onDraw(Canvas canvas) {
Drawable drawable = getDrawable();
if (drawable == null) {
return;
}
if (getWidth() == 0 || getHeight() == 0) {
return;
}
Bitmap b = ((BitmapDrawable) drawable).getBitmap();
Bitmap bitmap = b.copy(Bitmap.Config.ARGB_8888, true);
int w = getWidth();
@SuppressWarnings("unused")
int h = getHeight();
Bitmap roundBitmap = getCroppedBitmap(bitmap, w);
canvas.drawBitmap(roundBitmap, 0, 0, null);
}
public static Bitmap getCroppedBitmap(Bitmap bmp, int radius) {
Bitmap sbmp;
if (bmp.getWidth() != radius || bmp.getHeight() != radius) {
float smallest = Math.min(bmp.getWidth(), bmp.getHeight());
float factor = smallest / radius;
sbmp = Bitmap.createScaledBitmap(bmp,
(int) (bmp.getWidth() / factor),
(int) (bmp.getHeight() / factor), false);
} else {
sbmp = bmp;
}
Bitmap output = Bitmap.createBitmap(radius, radius, Config.ARGB_8888);
Canvas canvas = new Canvas(output);
final String color = "#BAB399";
final Paint paint = new Paint();
final Rect rect = new Rect(0, 0, radius, radius);
paint.setAntiAlias(true);
paint.setFilterBitmap(true);
paint.setDither(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(Color.parseColor(color));
canvas.drawCircle(radius / 2 + 0.7f, radius / 2 + 0.7f,
radius / 2 + 0.1f, paint);
paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
canvas.drawBitmap(sbmp, rect, rect, paint);
return output;
}
}
fatal error LNK1169: one or more multiply defined symbols found in game programming
You can't put variable definitions in header files, as these will then be a part of all source file you include the header into.
The #pragma once
is just to protect against multiple inclusions in the same source file, not against multiple inclusions in multiple source files.
You could declare the variables as extern
in the header file, and then define them in a single source file. Or you could declare the variables as const
in the header file and then the compiler and linker will manage it.
Get file path of image on Android
I am doing this on click of Button.
private static final int CAMERA_PIC_REQUEST = 1;
private View.OnClickListener OpenCamera=new View.OnClickListener() {
@Override
public void onClick(View paramView) {
// TODO Auto-generated method stub
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
NewSelectedImageURL=null;
//outfile where we are thinking of saving it
Date date = new Date();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
String newPicFile = RecipeName+ df.format(date) + ".png";
String outPath =Environment.getExternalStorageDirectory() + "/myFolderName/"+ newPicFile ;
File outFile = new File(outPath);
CapturedImageURL=outFile.toString();
Uri outuri = Uri.fromFile(outFile);
cameraIntent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, outuri);
startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST);
}
};
You can get the URL of the recently Captured Image from variable CapturedImageURL
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//////////////////////////////////////
if (requestCode == CAMERA_PIC_REQUEST) {
// do something
if (resultCode == RESULT_OK)
{
Uri uri = null;
if (data != null)
{
uri = data.getData();
}
if (uri == null && CapturedImageURL != null)
{
uri = Uri.fromFile(new File(CapturedImageURL));
}
File file = new File(CapturedImageURL);
if (!file.exists()) {
file.mkdir();
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://"+Environment.getExternalStorageDirectory())));
}
}
}
PHP check if file is an image
Using file extension and getimagesize
function to detect if uploaded file has right format is just the entry level check and it can simply bypass by uploading a file with true extension and some byte of an image header but wrong content.
for being secure and safe you may make thumbnail/resize (even with original image sizes) the uploaded picture and save this version instead the uploaded one.
Also its possible to get uploaded file content and search it for special character like <?php
to find the file is image or not.
Android set bitmap to Imageview
Please try this:
byte[] decodedString = Base64.decode(person_object.getPhoto(),Base64.NO_WRAP);
InputStream inputStream = new ByteArrayInputStream(decodedString);
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
user_image.setImageBitmap(bitmap);
What's the best way to cancel event propagation between nested ng-click calls?
What @JosephSilber said, or pass the $event object into ng-click
callback and stop the propagation inside of it:
<div ng-controller="OverlayCtrl" class="overlay" ng-click="hideOverlay()">
<img src="http://some_src" ng-click="nextImage($event)"/>
</div>
$scope.nextImage = function($event) {
$event.stopPropagation();
// Some code to find and display the next image
}
Fit Image in ImageButton in Android
Refer below link and try to find what you really want:
ImageView.ScaleType CENTER Center the image in the view, but perform
no scaling.
ImageView.ScaleType CENTER_CROP Scale the image uniformly (maintain
the image's aspect ratio) so that both dimensions (width and height)
of the image will be equal to or larger than the corresponding
dimension of the view (minus padding).
ImageView.ScaleType CENTER_INSIDE Scale the image uniformly (maintain
the image's aspect ratio) so that both dimensions (width and height)
of the image will be equal to or less than the corresponding dimension
of the view (minus padding).
ImageView.ScaleType FIT_CENTER Scale the image using CENTER.
ImageView.ScaleType FIT_END Scale the image using END.
ImageView.ScaleType FIT_START Scale the image using START.
ImageView.ScaleType FIT_XY Scale the image using FILL.
ImageView.ScaleType MATRIX Scale using the image matrix when drawing.
https://developer.android.com/reference/android/widget/ImageView.ScaleType.html
Resize UIImage and change the size of UIImageView
if([[SDWebImageManager sharedManager] diskImageExistsForURL:[NSURL URLWithString:@"URL STRING1"]])
{
NSString *key = [[SDWebImageManager sharedManager] cacheKeyForURL:[NSURL URLWithString:@"URL STRING1"]];
UIImage *tempImage=[self imageWithImage:[[SDImageCache sharedImageCache] imageFromDiskCacheForKey:key] scaledToWidth:cell.imgview.bounds.size.width];
cell.imgview.image=tempImage;
}
else
{
[cell.imgview sd_setImageWithURL:[NSURL URLWithString:@"URL STRING1"] placeholderImage:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL)
{
UIImage *tempImage=[self imageWithImage:image scaledToWidth:cell.imgview.bounds.size.width];
cell.imgview.image=tempImage;
// [tableView beginUpdates];
// [tableView endUpdates];
}];
}
How to remove outliers in boxplot in R?
See ?boxplot
for all the help you need.
outline: if ‘outline’ is not true, the outliers are not drawn (as
points whereas S+ uses lines).
boxplot(x,horizontal=TRUE,axes=FALSE,outline=FALSE)
And for extending the range of the whiskers and suppressing the outliers inside this range:
range: this determines how far the plot whiskers extend out from the
box. If ‘range’ is positive, the whiskers extend to the most
extreme data point which is no more than ‘range’ times the
interquartile range from the box. A value of zero causes the
whiskers to extend to the data extremes.
# change the value of range to change the whisker length
boxplot(x,horizontal=TRUE,axes=FALSE,range=2)
Java converting Image to BufferedImage
One way to handle this is to create a new BufferedImage, and tell it's graphics object to draw your scaled image into the new BufferedImage:
final float FACTOR = 4f;
BufferedImage img = ImageIO.read(new File("graphic.png"));
int scaleX = (int) (img.getWidth() * FACTOR);
int scaleY = (int) (img.getHeight() * FACTOR);
Image image = img.getScaledInstance(scaleX, scaleY, Image.SCALE_SMOOTH);
BufferedImage buffered = new BufferedImage(scaleX, scaleY, TYPE);
buffered.getGraphics().drawImage(image, 0, 0 , null);
That should do the trick without casting.
How to set image in imageview in android?
1> You can add image from layout itself:
<ImageView
android:id="@+id/iv_your_image"
android:layout_width="wrap_content"
android:layout_height="25dp"
android:background="@mipmap/your_image"
android:padding="2dp" />
OR
2> Programmatically in java class:
ImageView ivYouImage= (ImageView)findViewById(R.id.iv_your_image);
ivYouImage.setImageResource(R.mipmap.ic_changeImage);
OR for fragments:
View rowView= inflater.inflate(R.layout.your_layout, null, true);
ImageView ivYouImage= (ImageView) rowView.findViewById(R.id.iv_your_image);
ivYouImage.setImageResource(R.mipmap.ic_changeImage);
PHP upload image
I would recommend you to save the image in the server, and then save the URL in MYSQL database.
First of all, you should do more validation on your image, before non-validated files can lead to huge security risks.
Check the image
if (empty($_FILES['image']))
throw new Exception('Image file is missing');
Save the image in a variable
$image = $_FILES['image'];
Check the upload time errors
if ($image['error'] !== 0) {
if ($image['error'] === 1)
throw new Exception('Max upload size exceeded');
throw new Exception('Image uploading error: INI Error');
}
Check whether the uploaded file exists in the server
if (!file_exists($image['tmp_name']))
throw new Exception('Image file is missing in the server');
Validate the file size (Change it according to your needs)
$maxFileSize = 2 * 10e6; // = 2 000 000 bytes = 2MB
if ($image['size'] > $maxFileSize)
throw new Exception('Max size limit exceeded');
Validate the image (Check whether the file is an image)
$imageData = getimagesize($image['tmp_name']);
if (!$imageData)
throw new Exception('Invalid image');
Validate the image mime type (Do this according to your needs)
$mimeType = $imageData['mime'];
$allowedMimeTypes = ['image/jpeg', 'image/png', 'image/gif'];
if (!in_array($mimeType, $allowedMimeTypes))
throw new Exception('Only JPEG, PNG and GIFs are allowed');
This might help you to create a secure image uploading script with PHP.
Code source: https://developer.hyvor.com/php/image-upload-ajax-php-mysql
Additionally, I suggest you use MYSQLI prepared statements for queries to improve security.
Thank you.
How to print strings with line breaks in java
package test2;
public class main {
public static void main(String[] args) {
vehical vehical1 = new vehical("civic", "black","2012");
System.out.println(vehical1.name+"\n"+vehical1.colour+"\n"+vehical1.model);
}
}
Android ImageView setImageResource in code
You can use this code:
// Create an array that matches any country to its id (as String):
String[][] countriesId = new String[NUMBER_OF_COUNTRIES_SUPPORTED][];
// Initialize the array, where the first column will be the country's name (in uppercase) and the second column will be its id (as String):
countriesId[0] = new String[] {"US", String.valueOf(R.drawable.us)};
countriesId[1] = new String[] {"FR", String.valueOf(R.drawable.fr)};
// and so on...
// And after you get the variable "countryCode":
int i;
for(i = 0; i<countriesId.length; i++) {
if(countriesId[i][0].equals(countryCode))
break;
}
// Now "i" is the index of the country
img.setImageResource(Integer.parseInt(countriesId[i][1]));
Android view pager with page indicator
you have to do following:
1-Download the full project from here https://github.com/JakeWharton/ViewPagerIndicator
ViewPager Indicator
2- Import into the Eclipse.
After importing if you want to make following type of screen then follow below steps -
change in
Sample circles Default
package com.viewpagerindicator.sample;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import com.viewpagerindicator.CirclePageIndicator;
public class SampleCirclesDefault extends BaseSampleActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.simple_circles);
mAdapter = new TestFragmentAdapter(getSupportFragmentManager());
mPager = (ViewPager)findViewById(R.id.pager);
// mPager.setAdapter(mAdapter);
ImageAdapter adapter = new ImageAdapter(SampleCirclesDefault.this);
mPager.setAdapter(adapter);
mIndicator = (CirclePageIndicator)findViewById(R.id.indicator);
mIndicator.setViewPager(mPager);
}
}
ImageAdapter
package com.viewpagerindicator.sample;
import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
public class ImageAdapter extends PagerAdapter {
private Context mContext;
private Integer[] mImageIds = { R.drawable.about1, R.drawable.about2,
R.drawable.about3, R.drawable.about4, R.drawable.about5,
R.drawable.about6, R.drawable.about7
};
public ImageAdapter(Context context) {
mContext = context;
}
public int getCount() {
return mImageIds.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
@Override
public Object instantiateItem(ViewGroup container, final int position) {
LayoutInflater inflater = (LayoutInflater) container.getContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View convertView = inflater.inflate(R.layout.gallery_view, null);
ImageView view_image = (ImageView) convertView
.findViewById(R.id.view_image);
TextView description = (TextView) convertView
.findViewById(R.id.description);
view_image.setImageResource(mImageIds[position]);
view_image.setScaleType(ImageView.ScaleType.FIT_XY);
description.setText("The natural habitat of the Niligiri tahr,Rajamala Rajamala is 2695 Mts above sea level"
+ "The natural habitat of the Niligiri tahr,Rajamala Rajamala is 2695 Mts above sea level"
+ "The natural habitat of the Niligiri tahr,Rajamala Rajamala is 2695 Mts above sea level");
((ViewPager) container).addView(convertView, 0);
return convertView;
}
@Override
public boolean isViewFromObject(View view, Object object) {
return view == ((View) object);
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
((ViewPager) container).removeView((ViewGroup) object);
}
}
gallery_view.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@drawable/about_bg"
android:orientation="vertical" >
<LinearLayout
android:id="@+id/about_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:weightSum="1" >
<LinearLayout
android:id="@+id/about_layout1"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight=".4"
android:orientation="vertical" >
<ImageView
android:id="@+id/view_image"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/about1">
</ImageView>
</LinearLayout>
<LinearLayout
android:id="@+id/about_layout2"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight=".6"
android:orientation="vertical" >
<TextView
android:id="@+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="SIGNATURE LANDMARK OF MALAYSIA-SINGAPORE CAUSEWAY"
android:textColor="#000000"
android:gravity="center"
android:padding="18dp"
android:textStyle="bold"
android:textAppearance="?android:attr/textAppearance" />
<ScrollView
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:fillViewport="false"
android:orientation="vertical"
android:scrollbars="none"
android:layout_marginBottom="10dp"
android:padding="10dp" >
<TextView
android:id="@+id/description"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textColor="#000000"
android:text="TextView" />
</ScrollView>
</LinearLayout>
</LinearLayout>
adding a datatable in a dataset
I assume that you haven't set the TableName
property of the DataTable, for example via constructor:
var tbl = new DataTable("dtImage");
If you don't provide a name, it will be automatically created with "Table1"
, the next table will get "Table2"
and so on.
Then the solution would be to provide the TableName
and then check with Contains(nameOfTable)
.
To clarify it: You'll get an ArgumentException
if that DataTable already belongs to the DataSet (the same reference). You'll get a DuplicateNameException
if there's already a DataTable in the DataSet with the same name(not case-sensitive).
http://msdn.microsoft.com/en-us/library/as4zy2kc.aspx
How to set the image from drawable dynamically in android?
This works fine for me.
final R.drawable drawableResources = new R.drawable();
final Class<R.drawable> c = R.drawable.class;
final Field[] fields = c.getDeclaredFields();
for (int i=0; i < fields.length;i++)
{
resourceId[i] = fields[i].getInt(drawableResources);
/* till here you get all the images into the int array resourceId.*/
}
imageview= (ImageView)findViewById(R.id.imageView);
if(your condition)
{
imageview.setImageResource(resourceId[any]);
}
Creating a thumbnail from an uploaded image
I'm guessing you have already figured this one out. But I see that you are storing the images as "longblobs" leading me to think you are storing the entire binary content of the pic.
I hope you have realized that it makes much more sense to simply store the file names in your DB and then use that info to grab the pics out of an "upload" folder or similar.
TIP - dont save a file path.. just the file name .. add the path info in your code as needed. That way you have the most freedom down the line. If you need to change folder structure, you can do it in your code rather than changing DB records.
Save bitmap to file function
Two example works for me, for your reference.
Bitmap bitmap = Utils.decodeBase64(base64);
try {
File file = new File(filePath);
FileOutputStream fOut = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 85, fOut);
fOut.flush();
fOut.close();
}
catch (Exception e) {
e.printStackTrace();
LOG.i(null, "Save file error!");
return false;
}
and this one
Bitmap savePic = Utils.decodeBase64(base64);
File file = new File(filePath);
File path = new File(file.getParent());
if (savePic != null) {
try {
// build directory
if (file.getParent() != null && !path.isDirectory()) {
path.mkdirs();
}
// output image to file
FileOutputStream fos = new FileOutputStream(filePath);
savePic.compress(Bitmap.CompressFormat.PNG, 90, fos);
fos.close();
ret = true;
} catch (Exception e) {
e.printStackTrace();
}
} else {
LOG.i(TAG, "savePicture image parsing error");
}
Bad File Descriptor with Linux Socket write() Bad File Descriptor C
In general, when "Bad File Descriptor" is encountered, it means that the socket file descriptor you passed into the API is not valid, which has multiple possible reasons:
- The fd is already closed somewhere.
- The fd has a wrong value, which is inconsistent with the value obtained from socket() api
How to set image to UIImage
Try this code to 100% work....
UIImageView * imageview = [[UIImageView alloc] initWithFrame:CGRectMake(20,100, 80, 80)];
imageview.image = [UIImage imageNamed:@"myimage.jpg"];
[self.view addSubview:imageview];
How To Save Canvas As An Image With canvas.toDataURL()?
This work for me: (Only google chrome)
<html>
<head>
<script>
function draw(){
var canvas = document.getElementById("thecanvas");
var ctx = canvas.getContext("2d");
ctx.fillStyle = "rgba(125, 46, 138, 0.5)";
ctx.fillRect(25,25,100,100);
ctx.fillStyle = "rgba( 0, 146, 38, 0.5)";
ctx.fillRect(58, 74, 125, 100);
}
function downloadImage()
{
var canvas = document.getElementById("thecanvas");
var image = canvas.toDataURL();
var aLink = document.createElement('a');
var evt = document.createEvent("HTMLEvents");
evt.initEvent("click");
aLink.download = 'image.png';
aLink.href = image;
aLink.dispatchEvent(evt);
}
</script>
</head>
<body onload="draw()">
<canvas width=200 height=200 id="thecanvas"></canvas>
<div><button onclick="downloadImage()">Download</button></div>
<image id="theimage"></image>
</body>
</html>
Android Image View Pinch Zooming
Custom zoom view in Kotlin
import android.content.Context
import android.graphics.Matrix
import android.graphics.PointF
import android.util.AttributeSet
import android.util.Log
import android.view.MotionEvent
import android.view.ScaleGestureDetector
import android.view.ScaleGestureDetector.SimpleOnScaleGestureListener
import androidx.appcompat.widget.AppCompatImageView
class ZoomImageview : AppCompatImageView {
var matri: Matrix? = null
var mode = NONE
// Remember some things for zooming
var last = PointF()
var start = PointF()
var minScale = 1f
var maxScale = 3f
lateinit var m: FloatArray
var viewWidth = 0
var viewHeight = 0
var saveScale = 1f
protected var origWidth = 0f
protected var origHeight = 0f
var oldMeasuredWidth = 0
var oldMeasuredHeight = 0
var mScaleDetector: ScaleGestureDetector? = null
var contex: Context? = null
constructor(context: Context) : super(context) {
sharedConstructing(context)
}
constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
sharedConstructing(context)
}
private fun sharedConstructing(context: Context) {
super.setClickable(true)
this.contex= context
mScaleDetector = ScaleGestureDetector(context, ScaleListener())
matri = Matrix()
m = FloatArray(9)
imageMatrix = matri
scaleType = ScaleType.MATRIX
setOnTouchListener { v, event ->
mScaleDetector!!.onTouchEvent(event)
val curr = PointF(event.x, event.y)
when (event.action) {
MotionEvent.ACTION_DOWN -> {
last.set(curr)
start.set(last)
mode = DRAG
}
MotionEvent.ACTION_MOVE -> if (mode == DRAG) {
val deltaX = curr.x - last.x
val deltaY = curr.y - last.y
val fixTransX = getFixDragTrans(deltaX, viewWidth.toFloat(), origWidth * saveScale)
val fixTransY = getFixDragTrans(deltaY, viewHeight.toFloat(), origHeight * saveScale)
matri!!.postTranslate(fixTransX, fixTransY)
fixTrans()
last[curr.x] = curr.y
}
MotionEvent.ACTION_UP -> {
mode = NONE
val xDiff = Math.abs(curr.x - start.x).toInt()
val yDiff = Math.abs(curr.y - start.y).toInt()
if (xDiff < CLICK && yDiff < CLICK) performClick()
}
MotionEvent.ACTION_POINTER_UP -> mode = NONE
}
imageMatrix = matri
invalidate()
true // indicate event was handled
}
}
fun setMaxZoom(x: Float) {
maxScale = x
}
private inner class ScaleListener : SimpleOnScaleGestureListener() {
override fun onScaleBegin(detector: ScaleGestureDetector): Boolean {
mode = ZOOM
return true
}
override fun onScale(detector: ScaleGestureDetector): Boolean {
var mScaleFactor = detector.scaleFactor
val origScale = saveScale
saveScale *= mScaleFactor
if (saveScale > maxScale) {
saveScale = maxScale
mScaleFactor = maxScale / origScale
} else if (saveScale < minScale) {
saveScale = minScale
mScaleFactor = minScale / origScale
}
if (origWidth * saveScale <= viewWidth || origHeight * saveScale <= viewHeight) matri!!.postScale(mScaleFactor, mScaleFactor, viewWidth / 2.toFloat(), viewHeight / 2.toFloat()) else matri!!.postScale(mScaleFactor, mScaleFactor, detector.focusX, detector.focusY)
fixTrans()
return true
}
}
fun fixTrans() {
matri!!.getValues(m)
val transX = m[Matrix.MTRANS_X]
val transY = m[Matrix.MTRANS_Y]
val fixTransX = getFixTrans(transX, viewWidth.toFloat(), origWidth * saveScale)
val fixTransY = getFixTrans(transY, viewHeight.toFloat(), origHeight * saveScale)
if (fixTransX != 0f || fixTransY != 0f) matri!!.postTranslate(fixTransX, fixTransY)
}
fun getFixTrans(trans: Float, viewSize: Float, contentSize: Float): Float {
val minTrans: Float
val maxTrans: Float
if (contentSize <= viewSize) {
minTrans = 0f
maxTrans = viewSize - contentSize
} else {
minTrans = viewSize - contentSize
maxTrans = 0f
}
if (trans < minTrans) return -trans + minTrans
if (trans > maxTrans) return -trans + maxTrans
return 0f
}
fun getFixDragTrans(delta: Float, viewSize: Float, contentSize: Float): Float {
if (contentSize <= viewSize) {
return 0f
} else {
return delta
}
}
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec)
viewWidth = MeasureSpec.getSize(widthMeasureSpec)
viewHeight = MeasureSpec.getSize(heightMeasureSpec)
//
// Rescales image on rotation
//
if (oldMeasuredHeight == viewWidth && oldMeasuredHeight == viewHeight || viewWidth == 0 || viewHeight == 0) return
oldMeasuredHeight = viewHeight
oldMeasuredWidth = viewWidth
if (saveScale == 1f) {
//Fit to screen.
val scale: Float
val drawable = drawable
if (drawable == null || drawable.intrinsicWidth == 0 || drawable.intrinsicHeight == 0) return
val bmWidth = drawable.intrinsicWidth
val bmHeight = drawable.intrinsicHeight
Log.d("bmSize", "bmWidth: $bmWidth bmHeight : $bmHeight")
val scaleX = viewWidth.toFloat() / bmWidth.toFloat()
val scaleY = viewHeight.toFloat() / bmHeight.toFloat()
scale = Math.min(scaleX, scaleY)
matri!!.setScale(scale, scale)
// Center the image
var redundantYSpace = viewHeight.toFloat() - scale * bmHeight.toFloat()
var redundantXSpace = viewWidth.toFloat() - scale * bmWidth.toFloat()
redundantYSpace /= 2.toFloat()
redundantXSpace /= 2.toFloat()
matri!!.postTranslate(redundantXSpace, redundantYSpace)
origWidth = viewWidth - 2 * redundantXSpace
origHeight = viewHeight - 2 * redundantYSpace
imageMatrix = matri
}
fixTrans()
}
companion object {
// We can be in one of these 3 states
const val NONE = 0
const val DRAG = 1
const val ZOOM = 2
const val CLICK = 3
}
}
How to adjust an UIButton's imageSize?
i think, your image size is also same as button size then you put image in background of the button like :
[myLikesButton setBackgroundImage:[UIImage imageNamed:@"icon-heart.png"] forState:UIControlStateNormal];
you mast have same size of image and button.i hope you understand my point.
Android get image from gallery into ImageView
@Parag Chauhan soltution is working well, but I had problem - some file manager apps are returning in Intent object "file:///..." instead of "content://..." - which is needed to use query.
There is my short solution for that problem:
public String getRealPathFromURI(Context context, Uri contentUri) {
Cursor cursor = null;
try {
if("content".equals(contentUri.getScheme())) {
String[] proj = {MediaStore.Images.Media.DATA};
cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
else{
return contentUri.getPath();
}
} finally {
if (cursor != null) {
cursor.close();
}
}
}
Based on @Parag solution,
partial solution here (@nobre) Android: Getting a file URI from a content URI?
parital solution here (@Nikolay) Get filename and path from URI from mediastore
Getting Image from URL (Java)
This code worked fine for me.
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
public class SaveImageFromUrl {
public static void main(String[] args) throws Exception {
String imageUrl = "http://www.avajava.com/images/avajavalogo.jpg";
String destinationFile = "image.jpg";
saveImage(imageUrl, destinationFile);
}
public static void saveImage(String imageUrl, String destinationFile) throws IOException {
URL url = new URL(imageUrl);
InputStream is = url.openStream();
OutputStream os = new FileOutputStream(destinationFile);
byte[] b = new byte[2048];
int length;
while ((length = is.read(b)) != -1) {
os.write(b, 0, length);
}
is.close();
os.close();
}
}
Can I get image from canvas element and use it in img src tag?
canvas.toDataURL
is not working if the original image URL (either relative or absolute) does not belong to the same domain as the web page. Tested from a bookmarklet and a simple javascript in the web page containing the images.
Have a look to David Walsh working example. Put the html and images on your own web server, switch original image to relative or absolute URL, change to an external image URL. Only the first two cases are working.
Android Camera : data intent returns null
After much try and study, I was able to figure it out. First, the variable data from Intent will always be null so, therefore, checking for !null
will crash your app so long you are passing a URI to startActivityForResult.Follow the example below.
I will be using Kotlin.
Open the camera intent
fun addBathroomPhoto(){
addbathroomphoto.setOnClickListener{
request_capture_image=2
var takePictureIntent:Intent?
takePictureIntent =Intent(MediaStore.ACTION_IMAGE_CAPTURE)
if(takePictureIntent.resolveActivity(activity?.getPackageManager()) != null){
val photoFile: File? = try {
createImageFile()
} catch (ex: IOException) {
// Error occurred while creating the File
null
}
if (photoFile != null) {
val photoURI: Uri = FileProvider.getUriForFile(
activity!!,
"ogavenue.ng.hotelroomkeeping.fileprovider",photoFile)
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
photoURI);
startActivityForResult(takePictureIntent,
request_capture_image);
}
}
}
}`
Create the createImageFile().But you MUST make the imageFilePath variable global. Example on how to create it is on Android official documentation and pretty straightforward
Get Intent
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (requestCode == 1 && resultCode == RESULT_OK) {
add_room_photo_txt.text=""
var myBitmap=BitmapFactory.decodeFile(imageFilePath)
addroomphoto.setImageBitmap(myBitmap)
var file=File(imageFilePath)
var fis=FileInputStream(file)
var bm = BitmapFactory.decodeStream(fis);
roomphoto=getBytesFromBitmap(bm) }}
The getBytesFromBitmap method
fun getBytesFromBitmap(bitmap:Bitmap):ByteArray{
var stream=ByteArrayOutputStream()
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
return stream.toByteArray();
}
I hope this helps.
Storing image in database directly or as base64 data?
I contend that images (files) are NOT usually stored in a database base64 encoded. Instead, they are stored in their raw binary form in a binary (blob) column (or file).
Base64 is only used as a transport mechanism, not for storage. For example, you can embed a base64 encoded image into an XML document or an email message.
Base64 is also stream friendly. You can encode and decode on the fly (without knowing the total size of the data).
While base64 is fine for transport, do not store your images base64 encoded.
Base64 provides no checksum or anything of any value for storage.
Base64 encoding increases the storage requirement by 33% over a raw binary format. It also increases the amount of data that must be read from persistent storage, which is still generally the largest bottleneck in computing. It's generally faster to read less bytes and encode them on the fly. Only if your system is CPU bound instead of IO bound, and you're regularly outputting the image in base64, then consider storing in base64.
Inline images (base64 encoded images embedded in HTML) are a bottleneck themselves--you're sending 33% more data over the wire, and doing it serially (the web browser has to wait on the inline images before it can finish downloading the page HTML).
If you still wish to store images base64 encoded, please, whatever you do, make sure you don't store base64 encoded data in a UTF8 column then index it.
How to change the current URL in javascript?
This is more robust:
mi = location.href.split(/(\d+)/);
no = mi.length - 2;
os = mi[no];
mi[no]++;
if ((mi[no] + '').length < os.length) mi[no] = os.match(/0+/) + mi[no];
location.href = mi.join('');
When the URL has multiple numbers, it will change the last one:
http://mywebsite.com/8815/1.html
It supports numbers with leading zeros:
http://mywebsite.com/0001.html
Example
Android fade in and fade out with ImageView
you can do it by two simple point and change in your code
1.In your xml in anim folder of your project, Set the fade in and fade out duration time not equal
2.In you java class before the start of fade out animation, set second imageView visibility Gone then after fade out animation started set second imageView visibility which you want to fade in visible
fadeout.xml
<alpha
android:duration="4000"
android:fromAlpha="1.0"
android:interpolator="@android:anim/accelerate_interpolator"
android:toAlpha="0.0" />
fadein.xml
<alpha
android:duration="6000"
android:fromAlpha="0.0"
android:interpolator="@android:anim/accelerate_interpolator"
android:toAlpha="1.0" />
In you java class
Animation animFadeOut = AnimationUtils.loadAnimation(this, R.anim.fade_out);
ImageView iv = (ImageView) findViewById(R.id.imageView1);
ImageView iv2 = (ImageView) findViewById(R.id.imageView2);
iv.setVisibility(View.VISIBLE);
iv2.setVisibility(View.GONE);
animFadeOut.reset();
iv.clearAnimation();
iv.startAnimation(animFadeOut);
Animation animFadeIn = AnimationUtils.loadAnimation(this, R.anim.fade_in);
iv2.setVisibility(View.VISIBLE);
animFadeIn.reset();
iv2.clearAnimation();
iv2.startAnimation(animFadeIn);
ios Upload Image and Text using HTTP POST
For http post image and username and password sending through post
method
NSString *str=[NSString stringWithFormat:@"%@registration.php",appdel.baseUrl];
NSString *urlString = [NSString stringWithFormat:@"%@",str];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:@"POST"];
NSMutableData *body = [NSMutableData data];
NSString *boundary = @"---------------------------14737809831466499882746641449";
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
[request addValue:contentType forHTTPHeaderField: @"Content-Type"];
[body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"Content-Disposition: form-data; name=\"file\"; filename=\"a.jpg\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:imgData]];
[body appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
// parameter username
[body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"username\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[userName.text dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
// parameter token
[body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"email\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[eMail.text dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
// parameter method
[body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"pass\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[passWord.text dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
//parameter method
NSLog(@"%@",countryCode);
[body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"country\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[countryCode dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
// close form
[body appendData:[[NSString stringWithFormat:@"--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
// setting the body of the post to the reqeust
[request setHTTPBody:body];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
// NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSDictionary *dict=[NSJSONSerialization JSONObjectWithData:returnData options:NSJSONReadingMutableLeaves error:nil];
Nslog(@"%@",dict);
//
Get Bitmap attached to ImageView
For those who are looking for Kotlin
solution to get Bitmap
from ImageView
.
var bitmap = (image.drawable as BitmapDrawable).bitmap
How to Disable GUI Button in Java
You should put the statement btnConvertDocuments.setEnabled(false);
in the actionPerformed(ActionEvent event)
method. Your conditional above only get call once in the constructor when IPGUI object is being instantiated.
if (command.equals("w")) {
FileConverter fc = new FileConverter();
btn1Clicked = true;
btnConvertDocuments.setEnabled(false);
}
Get pixel color from canvas, on mousemove
Merging various references found here in StackOverflow (including the article above) and in other sites, I did so using javascript and JQuery:
<html>
<body>
<canvas id="myCanvas" width="400" height="400" style="border:1px solid #c3c3c3;">
Your browser does not support the canvas element.
</canvas>
<script src="jquery.js"></script>
<script type="text/javascript">
window.onload = function(){
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var img = new Image();
img.src = 'photo_apple.jpg';
context.drawImage(img, 0, 0);
};
function findPos(obj){
var current_left = 0, current_top = 0;
if (obj.offsetParent){
do{
current_left += obj.offsetLeft;
current_top += obj.offsetTop;
}while(obj = obj.offsetParent);
return {x: current_left, y: current_top};
}
return undefined;
}
function rgbToHex(r, g, b){
if (r > 255 || g > 255 || b > 255)
throw "Invalid color component";
return ((r << 16) | (g << 8) | b).toString(16);
}
$('#myCanvas').click(function(e){
var position = findPos(this);
var x = e.pageX - position.x;
var y = e.pageY - position.y;
var coordinate = "x=" + x + ", y=" + y;
var canvas = this.getContext('2d');
var p = canvas.getImageData(x, y, 1, 1).data;
var hex = "#" + ("000000" + rgbToHex(p[0], p[1], p[2])).slice(-6);
alert("HEX: " + hex);
});
</script>
<img src="photo_apple.jpg"/>
</body>
</html>
This is my complete solution. Here I only used canvas and one image, but if you need to use <map>
over the image, it's possible too.
Save image from url with curl PHP
This is easiest implement.
function downloadFile($url, $path)
{
$newfname = $path;
$file = fopen($url, 'rb');
if ($file) {
$newf = fopen($newfname, 'wb');
if ($newf) {
while (!feof($file)) {
fwrite($newf, fread($file, 1024 * 8), 1024 * 8);
}
}
}
if ($file) {
fclose($file);
}
if ($newf) {
fclose($newf);
}
}
how to set imageview src?
What you are looking for is probably this:
ImageView myImageView;
myImageView = mDialog.findViewById(R.id.image_id);
String src = "imageFileName"
int drawableId = this.getResources().getIdentifier(src, "drawable", context.getPackageName())
popupImageView.setImageResource(drawableId);
Let me know if this was helpful :)
Show ImageView programmatically
int id = getResources().getIdentifier("gameover", "drawable", getPackageName());
ImageView imageView = new ImageView(this);
LinearLayout.LayoutParams vp =
new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
imageView.setLayoutParams(vp);
imageView.setImageResource(id);
someLinearLayout.addView(imageView);
onActivityResult is not being called in Fragment
Most of these answers keep saying that you have to call super.onActivityResult(...)
in your host Activity
for your Fragment
. But that did not seem to be working for me.
So, in your host Activity
you should call your Fragments
onActivityResult(...)
instead. Here is an example.
public class HostActivity extends Activity {
private MyFragment myFragment;
protected void onActivityResult(...) {
super.onActivityResult(...);
this.myFragment.onActivityResult(...);
}
}
At some point in your HostActivity
you will need to assign this.myFragment
the Fragment
you are using. Or, use the FragmentManager
to get the Fragment
instead of keeping a reference to it in your HostActivity
. Also, check for null
before you try to call the this.myFragment.onActivityResult(...);
.
UIButton: set image for selected-highlighted state
If you have a good reason to do that, this will do the trick
add these targets:
[button addTarget:self action:@selector(buttonTouchDown:) forControlEvents:UIControlEventTouchDown];
[button addTarget:self action:@selector(buttonTouchUp:) forControlEvents:UIControlEventTouchUpInside];
-(void)buttonTouchDown:(id)sender{
UIButton *button=(UIButton *)sender;
if(button.selected){
[button setImage:[UIImage imageNamed:@"pressed.png"] forState:UIControlStateNormal];
}
}
-(void)buttonTouchUp:(id)sender{
UIButton *button=(UIButton *)sender;
[button setImage:[UIImage imageNamed:@"normal.png"] forState:UIControlStateNormal];
}
How to create a RelativeLayout programmatically with two buttons one on top of the other?
I have written a quick example to demonstrate how to create a layout programmatically.
public class CodeLayout extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Creating a new RelativeLayout
RelativeLayout relativeLayout = new RelativeLayout(this);
// Defining the RelativeLayout layout parameters.
// In this case I want to fill its parent
RelativeLayout.LayoutParams rlp = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.FILL_PARENT,
RelativeLayout.LayoutParams.FILL_PARENT);
// Creating a new TextView
TextView tv = new TextView(this);
tv.setText("Test");
// Defining the layout parameters of the TextView
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
lp.addRule(RelativeLayout.CENTER_IN_PARENT);
// Setting the parameters on the TextView
tv.setLayoutParams(lp);
// Adding the TextView to the RelativeLayout as a child
relativeLayout.addView(tv);
// Setting the RelativeLayout as our content view
setContentView(relativeLayout, rlp);
}
}
In theory everything should be clear as it is commented. If you don't understand something just tell me.
What's the best way to set a single pixel in an HTML5 canvas?
To complete Phrogz very thorough answer, there is a critical difference between fillRect()
and putImageData()
.
The first uses context to draw over by adding a rectangle (NOT a pixel), using the fillStyle alpha value AND the context globalAlpha and the transformation matrix, line caps etc..
The second replaces an entire set of pixels (maybe one, but why ?)
The result is different as you can see on jsperf.
Nobody wants to set one pixel at a time (meaning drawing it on screen). That is why there is no specific API to do that (and rightly so).
Performance wise, if the goal is to generate a picture (for example a ray-tracing software), you always want to use an array obtained by getImageData()
which is an optimized Uint8Array. Then you call putImageData()
ONCE or a few times per second using setTimeout/seTInterval
.
How to Resize a Bitmap in Android?
import android.graphics.Matrix
public Bitmap getResizedBitmap(Bitmap bm, int newWidth, int newHeight) {
int width = bm.getWidth();
int height = bm.getHeight();
float scaleWidth = ((float) newWidth) / width;
float scaleHeight = ((float) newHeight) / height;
// CREATE A MATRIX FOR THE MANIPULATION
Matrix matrix = new Matrix();
// RESIZE THE BIT MAP
matrix.postScale(scaleWidth, scaleHeight);
// "RECREATE" THE NEW BITMAP
Bitmap resizedBitmap = Bitmap.createBitmap(
bm, 0, 0, width, height, matrix, false);
bm.recycle();
return resizedBitmap;
}
EDIT: as suggested by by @aveschini, I have added bm.recycle();
for memory leaks. Please note that in case if you are using the previous object for some other purposes, then handle accordingly.
Aligning text and image on UIButton with imageEdgeInsets and titleEdgeInsets
Here is a simple example of how to use imageEdgeInsets
This will make a 30x30 button with a hittable area 10 pixels bigger all the way around (50x50)
var expandHittableAreaAmt : CGFloat = 10
var buttonWidth : CGFloat = 30
var button = UIButton.buttonWithType(UIButtonType.Custom) as UIButton
button.frame = CGRectMake(0, 0, buttonWidth+expandHittableAreaAmt, buttonWidth+expandHittableAreaAmt)
button.imageEdgeInsets = UIEdgeInsetsMake(expandHittableAreaAmt, expandHittableAreaAmt, expandHittableAreaAmt, expandHittableAreaAmt)
button.setImage(UIImage(named: "buttonImage"), forState: .Normal)
button.addTarget(self, action: "didTouchButton:", forControlEvents:.TouchUpInside)
Get the ID of a drawable in ImageView
As of today, there is no support on this function. However, I found a little hack on this one.
imageView.setImageResource(R.drawable.ic_star_black_48dp);
imageView.setTag(R.drawable.ic_star_black_48dp);
So if you want to get the ID of the view, just get it's tag.
if (imageView.getTag() != null) {
int resourceID = (int) imageView.getTag();
//
// drawable id.
//
}
How to capture UIView to UIImage without loss of quality on retina display
To improve answers by @Tommy and @Dima, use the following category to render UIView into UIImage with transparent background and without loss of quality. Working on iOS7. (Or just reuse that method in implementation, replacing self
reference with your image)
UIView+RenderViewToImage.h
#import <UIKit/UIKit.h>
@interface UIView (RenderToImage)
- (UIImage *)imageByRenderingView;
@end
UIView+RenderViewToImage.m
#import "UIView+RenderViewToImage.h"
@implementation UIView (RenderViewToImage)
- (UIImage *)imageByRenderingView
{
UIGraphicsBeginImageContextWithOptions(self.bounds.size, NO, 0.0);
[self drawViewHierarchyInRect:self.bounds afterScreenUpdates:YES];
UIImage * snapshotImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return snapshotImage;
}
@end
How can I make a horizontal ListView in Android?
My app uses a ListView in portraint mode which is simply switches to Gallery in landscape mode. Both of them use one BaseAdapter. This looks like shown below.
setContentView(R.layout.somelayout);
orientation = getResources().getConfiguration().orientation;
if ( orientation == Configuration.ORIENTATION_LANDSCAPE )
{
Gallery gallery = (Gallery)findViewById( R.id.somegallery );
gallery.setAdapter( someAdapter );
gallery.setOnItemClickListener( new OnItemClickListener() {
@Override
public void onItemClick( AdapterView<?> parent, View view,
int position, long id ) {
onClick( position );
}
});
}
else
{
setListAdapter( someAdapter );
getListView().setOnScrollListener(this);
}
To handle scrolling events I've inherited my own widget from Gallery and override onFling().
Here's the layout.xml:
<view
class="package$somegallery"
android:id="@+id/somegallery"
android:layout_height="fill_parent"
android:layout_width="fill_parent">
</view>
and code:
public static class somegallery extends Gallery
{
private Context mCtx;
public somegallery(Context context, AttributeSet attrs)
{
super(context, attrs);
mCtx = context;
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
float velocityY) {
( (CurrentActivity)mCtx ).onScroll();
return super.onFling(e1, e2, velocityX, velocityY);
}
}
Loading an image to a <img> from <input file>
In browsers supporting the File API, you can use the FileReader constructor to read files once they have been selected by the user.
Example
document.getElementById('picField').onchange = function (evt) {
var tgt = evt.target || window.event.srcElement,
files = tgt.files;
// FileReader support
if (FileReader && files && files.length) {
var fr = new FileReader();
fr.onload = function () {
document.getElementById(outImage).src = fr.result;
}
fr.readAsDataURL(files[0]);
}
// Not supported
else {
// fallback -- perhaps submit the input to an iframe and temporarily store
// them on the server until the user's session ends.
}
}
Browser support
- IE 10
- Safari 6.0.2
- Chrome 7
- Firefox 3.6
- Opera 12.02
Where the File API is unsupported, you cannot (in most security conscious browsers) get the full path of a file from a file input box, nor can you access the data. The only viable solution would be to submit the form to a hidden iframe and have the file pre-uploaded to the server. Then, when that request completes you could set the src of the image to the location of the uploaded file.
Custom ImageView with drop shadow
This is taken from Romain Guy's presentation at Devoxx, pdf found here.
Paint mShadow = new Paint();
// radius=10, y-offset=2, color=black
mShadow.setShadowLayer(10.0f, 0.0f, 2.0f, 0xFF000000);
// in onDraw(Canvas)
canvas.drawBitmap(bitmap, 0.0f, 0.0f, mShadow);
Hope this helps.
NOTES
- Don't forget for Honeycomb and above you need to invoke
setLayerType(LAYER_TYPE_SOFTWARE, mShadow)
, otherwise you will not see your shadow! (@Dmitriy_Boichenko)
SetShadowLayer
does
not work with hardware acceleration unfortunately so it greatly
reduces performances (@Matt Wear) [1] [2]
C# LINQ select from list
In likeness of how I found this question using Google, I wanted to take it one step further.
Lets say I have a string[] states
and a db Entity
of StateCounties
and I just want the states from the list returned and not all of the StateCounties
.
I would write:
db.StateCounties.Where(x => states.Any(s => x.State.Equals(s))).ToList();
I found this within the sample of CheckBoxList
for nu-get.
Android: How to stretch an image to the screen width while maintaining aspect ratio?
I have managed to achieve this using this XML code only. It might be the case that eclipse does not render the height to show it expanding to fit; however, when you actually run this on a device, it properly renders and provides the desired result. (well at least for me)
<FrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:scaleType="centerCrop"
android:src="@drawable/whatever" />
</FrameLayout>
How to clear an ImageView in Android?
Hey i know i am extremely late to this answer, but just thought i must share this,
The method to call when u reset the image must be the same method that u called while u were setting it.
When u want to reset the image source @dennis.sheepard answer works fine only if u are originally setting the image in the bitmap using setImageResource()
for instance,
i had used setImageBitmap()
and hence setting setImageResource(0)
didn work, instead i used setImageBitmap(null)
.
Add button to navigationbar programmatically
Hello everyone !! I created the solution to the issue at hand where Two UIInterface orientations are wanted using the UIIMagePicker.. In my ViewController where I handle the segue to the UIImagePickerController
**I use a..
-(void) editButtonPressed:(id)sender {
BOOL editPressed = YES;
NSUserDefaults *boolDefaults = [NSUserDefaults standardUserDefaults];
[boolDefaults setBool:editPressed forKey:@"boolKey"];
[boolDefaults synchronize];
[self performSegueWithIdentifier:@"photoSegue" sender:nil];
}
**
Then in the AppDelegate Class I do the following.
- (NSUInteger)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window {
BOOL appDelBool;
NSUserDefaults *boolDefaults = [NSUserDefaults standardUserDefaults];
appDelBool = [boolDefaults boolForKey:@"boolKey"];
if (appDelBool == YES)
return (UIInterfaceOrientationMaskPortrait);
else
return UIInterfaceOrientationMaskLandscapeLeft;
}
overlay two images in android to set an imageview
Its a bit late answer, but it covers merging images from urls using Picasso
MergeImageView
import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Build;
import android.util.AttributeSet;
import android.util.SparseArray;
import android.widget.ImageView;
import com.squareup.picasso.Picasso;
import java.io.IOException;
import java.util.List;
public class MergeImageView extends ImageView {
private SparseArray<Bitmap> bitmaps = new SparseArray<>();
private Picasso picasso;
private final int DEFAULT_IMAGE_SIZE = 50;
private int MIN_IMAGE_SIZE = DEFAULT_IMAGE_SIZE;
private int MAX_WIDTH = DEFAULT_IMAGE_SIZE * 2, MAX_HEIGHT = DEFAULT_IMAGE_SIZE * 2;
private String picassoRequestTag = null;
public MergeImageView(Context context) {
super(context);
}
public MergeImageView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public MergeImageView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public MergeImageView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}
@Override
public boolean isInEditMode() {
return true;
}
public void clearResources() {
if (bitmaps != null) {
for (int i = 0; i < bitmaps.size(); i++)
bitmaps.get(i).recycle();
bitmaps.clear();
}
// cancel picasso requests
if (picasso != null && AppUtils.ifNotNullEmpty(picassoRequestTag))
picasso.cancelTag(picassoRequestTag);
picasso = null;
bitmaps = null;
}
public void createMergedBitmap(Context context, List<String> imageUrls, String picassoTag) {
picasso = Picasso.with(context);
int count = imageUrls.size();
picassoRequestTag = picassoTag;
boolean isEven = count % 2 == 0;
// if url size are not even make MIN_IMAGE_SIZE even
MIN_IMAGE_SIZE = DEFAULT_IMAGE_SIZE + (isEven ? count / 2 : (count / 2) + 1);
// set MAX_WIDTH and MAX_HEIGHT to twice of MIN_IMAGE_SIZE
MAX_WIDTH = MAX_HEIGHT = MIN_IMAGE_SIZE * 2;
// in case of odd urls increase MAX_HEIGHT
if (!isEven) MAX_HEIGHT = MAX_WIDTH + MIN_IMAGE_SIZE;
// create default bitmap
Bitmap bitmap = Bitmap.createScaledBitmap(BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_wallpaper),
MIN_IMAGE_SIZE, MIN_IMAGE_SIZE, false);
// change default height (wrap_content) to MAX_HEIGHT
int height = Math.round(AppUtils.convertDpToPixel(MAX_HEIGHT, context));
setMinimumHeight(height * 2);
// start AsyncTask
for (int index = 0; index < count; index++) {
// put default bitmap as a place holder
bitmaps.put(index, bitmap);
new PicassoLoadImage(index, imageUrls.get(index)).execute();
// if you want parallel execution use
// new PicassoLoadImage(index, imageUrls.get(index)).(AsyncTask.THREAD_POOL_EXECUTOR);
}
}
private class PicassoLoadImage extends AsyncTask<String, Void, Bitmap> {
private int index = 0;
private String url;
PicassoLoadImage(int index, String url) {
this.index = index;
this.url = url;
}
@Override
protected Bitmap doInBackground(String... params) {
try {
// synchronous picasso call
return picasso.load(url).resize(MIN_IMAGE_SIZE, MIN_IMAGE_SIZE).tag(picassoRequestTag).get();
} catch (IOException e) {
}
return null;
}
@Override
protected void onPostExecute(Bitmap output) {
super.onPostExecute(output);
if (output != null)
bitmaps.put(index, output);
// create canvas
Bitmap.Config conf = Bitmap.Config.RGB_565;
Bitmap canvasBitmap = Bitmap.createBitmap(MAX_WIDTH, MAX_HEIGHT, conf);
Canvas canvas = new Canvas(canvasBitmap);
canvas.drawColor(Color.WHITE);
// if height and width are equal we have even images
boolean isEven = MAX_HEIGHT == MAX_WIDTH;
int imageSize = bitmaps.size();
int count = imageSize;
// we have odd images
if (!isEven) count = imageSize - 1;
for (int i = 0; i < count; i++) {
Bitmap bitmap = bitmaps.get(i);
canvas.drawBitmap(bitmap, bitmap.getWidth() * (i % 2), bitmap.getHeight() * (i / 2), null);
}
// if images are not even set last image width to MAX_WIDTH
if (!isEven) {
Bitmap scaledBitmap = Bitmap.createScaledBitmap(bitmaps.get(count), MAX_WIDTH, MIN_IMAGE_SIZE, false);
canvas.drawBitmap(scaledBitmap, scaledBitmap.getWidth() * (count % 2), scaledBitmap.getHeight() * (count / 2), null);
}
// set bitmap
setImageBitmap(canvasBitmap);
}
}
}
xml
<com.example.MergeImageView
android:id="@+id/iv_thumb"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
Example
List<String> urls = new ArrayList<>();
String picassoTag = null;
// add your urls
((MergeImageView)findViewById(R.id.iv_thumb)).
createMergedBitmap(MainActivity.this, urls,picassoTag);
HorizontalScrollView within ScrollView Touch Handling
I've found out that somethimes one ScrollView regains focus and the other loses focus. You can prevent that, by only granting one of the scrollView focus:
scrollView1= (ScrollView) findViewById(R.id.scrollscroll);
scrollView1.setAdapter(adapter);
scrollView1.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
scrollView1.getParent().requestDisallowInterceptTouchEvent(true);
return false;
}
});
UIImage resize (Scale proportion)
I used this single line of code to create a new UIImage which is scaled. Set the scale and orientation params to achieve what you want. The first line of code just grabs the image.
// grab the original image
UIImage *originalImage = [UIImage imageNamed:@"myImage.png"];
// scaling set to 2.0 makes the image 1/2 the size.
UIImage *scaledImage =
[UIImage imageWithCGImage:[originalImage CGImage]
scale:(originalImage.scale * 2.0)
orientation:(originalImage.imageOrientation)];
"unrecognized selector sent to instance" error in Objective-C
Another reason/solution to add to the list. This one is caused by iOS6.0 (and/or bad programming). In older versions the selector would match if the parameter types matched, but in iOS 6.0 I got crashes in previously working code where the name of the parameter wasn't correct.
I was doing something like
[objectName methodName:@"somestring" lat:latValue lng:lngValue];
but in the definition (both .h and .m) I had
(viod) methodName:(NSString *) latitude:(double)latitude longitude:(double)longitude;
This worked fine on iOS5 but not on 6, even the exact same build deployed to different devices.
I don't get why the compiler coudn't tell me this, anyway - problem soled.
UIButton: how to center an image and a text using imageEdgeInsets and titleEdgeInsets?
Subclass UIButton
- (void)layoutSubviews {
[super layoutSubviews];
CGFloat spacing = 6.0;
CGSize imageSize = self.imageView.image.size;
CGSize titleSize = [self.titleLabel sizeThatFits:CGSizeMake(self.frame.size.width, self.frame.size.height - (imageSize.height + spacing))];
self.imageView.frame = CGRectMake((self.frame.size.width - imageSize.width)/2, (self.frame.size.height - (imageSize.height+spacing+titleSize.height))/2, imageSize.width, imageSize.height);
self.titleLabel.frame = CGRectMake((self.frame.size.width - titleSize.width)/2, CGRectGetMaxY(self.imageView.frame)+spacing, titleSize.width, titleSize.height);
}
Routing with Multiple Parameters using ASP.NET MVC
You can pass arbitrary parameters through the query string, but you can also set up custom routes to handle it in a RESTful way:
http://ws.audioscrobbler.com/2.0/?method=artist.getimages&artist=cher&
api_key=b25b959554ed76058ac220b7b2e0a026
That could be:
routes.MapRoute(
"ArtistsImages",
"{ws}/artists/{artist}/{action}/{*apikey}",
new { ws = "2.0", controller="artists" artist = "", action="", apikey="" }
);
So if someone used the following route:
ws.audioscrobbler.com/2.0/artists/cher/images/b25b959554ed76058ac220b7b2e0a026/
It would take them to the same place your example querystring did.
The above is just an example, and doesn't apply the business rules and constraints you'd have to set up to make sure people didn't 'hack' the URL.
How Do I Take a Screen Shot of a UIView?
There is new API from iOS 10
extension UIView {
func makeScreenshot() -> UIImage {
let renderer = UIGraphicsImageRenderer(bounds: self.bounds)
return renderer.image { (context) in
self.layer.render(in: context.cgContext)
}
}
}
Get Image Height and Width as integer values?
PHP's getimagesize()
returns an array of data. The first two items in the array are the two items you're interested in: the width and height. To get these, you would simply request the first two indexes in the returned array:
var $imagedata = getimagesize("someimage.jpg");
print "Image width is: " . $imagedata[0];
print "Image height is: " . $imagedata[1];
For further information, see the documentation.
scale Image in an UIButton to AspectFit?
I had problems with the image not resizing proportionately so the way I fixed it was using edge insets.
fooButton.contentEdgeInsets = UIEdgeInsetsMake(10, 15, 10, 15);
c# Image resizing to different size while preserving aspect ratio
Note: this code resizes and removes everything outside the aspect ratio instead of padding it..
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
namespace MyPhotos.Common
{
public class ThumbCreator
{
public enum VerticalAlign
{
Top,
Middle,
Bottom
}
public enum HorizontalAlign
{
Left,
Middle,
Right
}
public void Convert(string sourceFile, string targetFile, ImageFormat targetFormat, int height, int width, VerticalAlign valign, HorizontalAlign halign)
{
using (Image img = Image.FromFile(sourceFile))
{
using (Image targetImg = Convert(img, height, width, valign, halign))
{
string directory = Path.GetDirectoryName(targetFile);
if (!Directory.Exists(directory))
{
Directory.CreateDirectory(directory);
}
if (targetFormat == ImageFormat.Jpeg)
{
SaveJpeg(targetFile, targetImg, 100);
}
else
{
targetImg.Save(targetFile, targetFormat);
}
}
}
}
/// <summary>
/// Saves an image as a jpeg image, with the given quality
/// </summary>
/// <param name="path">Path to which the image would be saved.</param>
// <param name="quality">An integer from 0 to 100, with 100 being the
/// highest quality</param>
public static void SaveJpeg(string path, Image img, int quality)
{
if (quality < 0 || quality > 100)
throw new ArgumentOutOfRangeException("quality must be between 0 and 100.");
// Encoder parameter for image quality
EncoderParameter qualityParam =
new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality);
// Jpeg image codec
ImageCodecInfo jpegCodec = GetEncoderInfo("image/jpeg");
EncoderParameters encoderParams = new EncoderParameters(1);
encoderParams.Param[0] = qualityParam;
img.Save(path, jpegCodec, encoderParams);
}
/// <summary>
/// Returns the image codec with the given mime type
/// </summary>
private static ImageCodecInfo GetEncoderInfo(string mimeType)
{
// Get image codecs for all image formats
ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();
// Find the correct image codec
for (int i = 0; i < codecs.Length; i++)
if (codecs[i].MimeType == mimeType)
return codecs[i];
return null;
}
public Image Convert(Image img, int height, int width, VerticalAlign valign, HorizontalAlign halign)
{
Bitmap result = new Bitmap(width, height);
using (Graphics g = Graphics.FromImage(result))
{
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
float ratio = (float)height / (float)img.Height;
int temp = (int)((float)img.Width * ratio);
if (temp == width)
{
//no corrections are needed!
g.DrawImage(img, 0, 0, width, height);
return result;
}
else if (temp > width)
{
//den e för bred!
int overFlow = (temp - width);
if (halign == HorizontalAlign.Middle)
{
g.DrawImage(img, 0 - overFlow / 2, 0, temp, height);
}
else if (halign == HorizontalAlign.Left)
{
g.DrawImage(img, 0, 0, temp, height);
}
else if (halign == HorizontalAlign.Right)
{
g.DrawImage(img, -overFlow, 0, temp, height);
}
}
else
{
//den e för hög!
ratio = (float)width / (float)img.Width;
temp = (int)((float)img.Height * ratio);
int overFlow = (temp - height);
if (valign == VerticalAlign.Top)
{
g.DrawImage(img, 0, 0, width, temp);
}
else if (valign == VerticalAlign.Middle)
{
g.DrawImage(img, 0, -overFlow / 2, width, temp);
}
else if (valign == VerticalAlign.Bottom)
{
g.DrawImage(img, 0, -overFlow, width, temp);
}
}
}
return result;
}
}
}
Crop image in PHP
$image = imagecreatefromjpeg($_GET['src']);
$filename = 'images/cropped_whatever.jpg'
Must be replaced with:
$image = imagecreatefromjpeg($_GET['src']);
Then it will work!
How to send parameters from a notification-click to an activity?
I had the similar problem my application displays message notifications.
When there are multiple notifications and clicking each notification it displays that notification detail in a view message activity. I solved the problem of same extra parameters is being received in view message intent.
Here is the code which fixed this.
Code for creating the notification Intent.
Intent notificationIntent = new Intent(getApplicationContext(), viewmessage.class);
notificationIntent.putExtra("NotificationMessage", notificationMessage);
notificationIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingNotificationIntent = PendingIntent.getActivity(getApplicationContext(),notificationIndex,notificationIntent,PendingIntent.FLAG_UPDATE_CURRENT);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notification.setLatestEventInfo(getApplicationContext(), notificationTitle, notificationMessage, pendingNotificationIntent);
Code for view Message Activity.
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
onNewIntent(getIntent());
}
@Override
public void onNewIntent(Intent intent){
Bundle extras = intent.getExtras();
if(extras != null){
if(extras.containsKey("NotificationMessage"))
{
setContentView(R.layout.viewmain);
// extract the extra-data in the Notification
String msg = extras.getString("NotificationMessage");
txtView = (TextView) findViewById(R.id.txtMessage);
txtView.setText(msg);
}
}
}
Pass Additional ViewData to a Strongly-Typed Partial View
RenderPartial takes another parameter that is simply a ViewDataDictionary. You're almost there, just call it like this:
Html.RenderPartial(
"ProductImageForm",
image,
new ViewDataDictionary { { "index", index } }
);
Note that this will override the default ViewData that all your other Views have by default. If you are adding anything to ViewData, it will not be in this new dictionary that you're passing to your partial view.
A generic error occurred in GDI+, JPEG Image to MemoryStream
Had a very similar problem and also tried cloning the image which doesn't work. I found that the best solution was to create a new Bitmap object from the image that was loaded from the memory stream. That way the stream can be disposed of e.g.
using (var m = new MemoryStream())
{
var img = new Bitmap(Image.FromStream(m));
return img;
}
Hope this helps.
How to get image height and width using java?
I have found another way to read an image size (more generic).
You can use ImageIO class in cooperation with ImageReaders.
Here is the sample code:
private Dimension getImageDim(final String path) {
Dimension result = null;
String suffix = this.getFileSuffix(path);
Iterator<ImageReader> iter = ImageIO.getImageReadersBySuffix(suffix);
if (iter.hasNext()) {
ImageReader reader = iter.next();
try {
ImageInputStream stream = new FileImageInputStream(new File(path));
reader.setInput(stream);
int width = reader.getWidth(reader.getMinIndex());
int height = reader.getHeight(reader.getMinIndex());
result = new Dimension(width, height);
} catch (IOException e) {
log(e.getMessage());
} finally {
reader.dispose();
}
} else {
log("No reader found for given format: " + suffix));
}
return result;
}
Note that getFileSuffix is method that returns extension of path without "." so e.g.: png, jpg etc.
Example implementation is:
private String getFileSuffix(final String path) {
String result = null;
if (path != null) {
result = "";
if (path.lastIndexOf('.') != -1) {
result = path.substring(path.lastIndexOf('.'));
if (result.startsWith(".")) {
result = result.substring(1);
}
}
}
return result;
}
This solution is very quick as only image size is read from the file and not the whole image. I tested it and there is no comparison to ImageIO.read performance. I hope someone will find this useful.
Save bitmap to location
Hey just give the name to .bmp
Do this:
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
_bitmapScaled.compress(Bitmap.CompressFormat.PNG, 40, bytes);
//you can create a new file name "test.BMP" in sdcard folder.
File f = new File(Environment.getExternalStorageDirectory()
+ File.separator + "**test.bmp**")
it'll sound that IM JUST FOOLING AROUND but try it once it'll get saved in bmp foramt..Cheers
CGContextDrawImage draws image upside down when passed UIImage.CGImage
I'm not sure for UIImage
, but this kind of behaviour usually occurs when coordinates are flipped. Most of OS X coordinate systems have their origin at the lower left corner, as in Postscript and PDF. But CGImage
coordinate system has its origin at the upper left corner.
Possible solutions may involve an isFlipped
property or a scaleYBy:-1
affine transform.
Strange out of memory issue while loading an image to a Bitmap object
I think best way to avoid the OutOfMemoryError
is to face it and understand it.
I made an app to intentionally cause OutOfMemoryError
, and monitor memory usage.
After I've done a lot of experiments with this App, I've got the following conclusions:
I'm gonna talk about SDK versions before Honey Comb first.
Bitmap is stored in native heap, but it will get garbage collected automatically, calling recycle() is needless.
If {VM heap size} + {allocated native heap memory} >= {VM heap size limit for the device}, and you are trying to create bitmap, OOM will be thrown.
NOTICE: VM HEAP SIZE is counted rather than VM ALLOCATED MEMORY.
VM Heap size will never shrink after grown, even if the allocated VM memory is shrinked.
So you have to keep the peak VM memory as low as possible to keep VM Heap Size from growing too big to save available memory for Bitmaps.
Manually call System.gc() is meaningless, the system will call it first before trying to grow the heap size.
Native Heap Size will never shrink too, but it's not counted for OOM, so no need to worry about it.
Then, let's talk about SDK Starts from Honey Comb.
Bitmap is stored in VM heap, Native memory is not counted for OOM.
The condition for OOM is much simpler: {VM heap size} >= {VM heap size limit for the device}.
So you have more available memory to create bitmap with the same heap size limit, OOM is less likely to be thrown.
Here is some of my observations about Garbage Collection and Memory Leak.
You can see it yourself in the App. If an Activity executed an AsyncTask that was still running after the Activity was destroyed, the Activity will not get garbage collected until the AsyncTask finish.
This is because AsyncTask is an instance of an anonymous inner class, it holds a reference of the Activity.
Calling AsyncTask.cancel(true) will not stop the execution if the task is blocked in an IO operation in background thread.
Callbacks are anonymous inner classes too, so if a static instance in your project holds them and do not release them, memory would be leaked.
If you scheduled a repeating or delayed task, for example a Timer, and you do not call cancel() and purge() in onPause(), memory would be leaked.
Javascript - Get Image height
...but... wouldn't it be better to adjust the image size on the server side rather than transmitting the bytes to the browser and doing it there?
When I say adjust the image size, I don't mean set the height and width in the HTML image tag. If you do that, you are still shipping a large number of bytes from server to client. I mean, actually manipulate the image itself server side.
I have .NET C# code here that takes that approach, but there must be a php way to do it too: http://ifdefined.com/www/gallery.html
Also, by doing it server side, that opens up the possibility of doing the adjustment just once and then saving the adjusted image, which would be very fast.
How to redirect to a route in laravel 5 by using href tag if I'm not using blade or any template?
In addition to @chanafdo answer, you can use route name
when working with laravel blade
<a href="{{route('login')}}">login here</a>
with parameter in route name
when go to url like URI: profile/{id}
<a href="{{route('profile', ['id' => 1])}}">login here</a>
without blade
<a href="<?php echo route('login')?>">login here</a>
with parameter in route name
when go to url like URI: profile/{id}
<a href="<?php echo route('profile', ['id' => 1])?>">login here</a>
As of laravel 5.2 you can use @php @endphp
to create as <?php ?>
in laravel blade.
Using blade your personal opinion but I suggest to use it. Learn it.
It has many wonderful features as template inheritance, Components & Slots,subviews etc...
How to fix the "java.security.cert.CertificateException: No subject alternative names present" error?
For Spring Boot RestTemplate
:
- add
org.apache.httpcomponents.httpcore
dependency
use NoopHostnameVerifier
for SSL factory:
SSLContext sslContext = new SSLContextBuilder()
.loadTrustMaterial(new URL("file:pathToServerKeyStore"), storePassword)
// .loadKeyMaterial(new URL("file:pathToClientKeyStore"), storePassword, storePassword)
.build();
SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);
CloseableHttpClient client = HttpClients.custom().setSSLSocketFactory(socketFactory).build();
HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(client);
RestTemplate restTemplate = new RestTemplate(factory);
LINQ extension methods - Any() vs. Where() vs. Exists()
foreach (var item in model.Where(x => !model2.Any(y => y.ID == x.ID)).ToList())
{
enter code here
}
same work you also can do with Contains
secondly Where
is give you new list of values.
thirdly using Exist
is not a good practice, you can achieve your target from Any
and contains
like
EmployeeDetail _E = Db.EmployeeDetails.where(x=>x.Id==1).FirstOrDefault();
Hope this will clear your confusion.
break/exit script
This is an old question but there is no a clean solution yet. This probably is not answering this specific question, but those looking for answers on 'how to gracefully exit from an R script' will probably land here. It seems that R developers forgot to implement an exit() function. Anyway, the trick I've found is:
continue <- TRUE
tryCatch({
# You do something here that needs to exit gracefully without error.
...
# We now say bye-bye
stop("exit")
}, error = function(e) {
if (e$message != "exit") {
# Your error message goes here. E.g.
stop(e)
}
continue <<-FALSE
})
if (continue) {
# Your code continues here
...
}
cat("done.\n")
Basically, you use a flag to indicate the continuation or not of a specified block of code. Then you use the stop()
function to pass a customized message to the error handler of a tryCatch()
function. If the error handler receives your message to exit gracefully, then it just ignores the error and set the continuation flag to FALSE
.
Outline radius?
COMBINING BOX SHADOW AND OUTLINE.
A slight twist on Lea Hayes answer
I found
input[type=text]:focus {
box-shadow: 0 0 0 1pt red;
outline-width: 1px;
outline-color: red;
}
gets a really nice clean finish. No jumping in size which you get when using border-radius
Drop Down Menu/Text Field in one
I'd like to add a jQuery autocomplete based solution that does the job.
Step 1: Make the list fixed height and scrollable
Get the code from https://jqueryui.com/autocomplete/ "Scrollable" example, setting max height to the list of results so it behaves as a select box.
Step 2: Open the list on focus:
Display jquery ui auto-complete list on focus event
Step 3: Set minimum chars to 0 so it opens no matter how many chars are in the input
Final result:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>jQuery UI Autocomplete - Scrollable results</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="/resources/demos/style.css">
<style>
.ui-autocomplete {
max-height: 100px;
overflow-y: auto;
/* prevent horizontal scrollbar */
overflow-x: hidden;
}
/* IE 6 doesn't support max-height
* we use height instead, but this forces the menu to always be this tall
*/
* html .ui-autocomplete {
height: 100px;
}
</style>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
$( function() {
var availableTags = [
"ActionScript",
"AppleScript",
"Asp",
"BASIC",
"C",
"C++",
"Clojure",
"COBOL",
"ColdFusion",
"Erlang",
"Fortran",
"Groovy",
"Haskell",
"Java",
"JavaScript",
"Lisp",
"Perl",
"PHP",
"Python",
"Ruby",
"Scala",
"Scheme"
];
$( "#tags" ).autocomplete({
// source: availableTags, // uncomment this and comment the following to have normal autocomplete behavior
source: function (request, response) {
response( availableTags);
},
minLength: 0
}).focus(function(){
// $(this).data("uiAutocomplete").search($(this).val()); // uncomment this and comment the following to have autocomplete behavior when opening
$(this).data("uiAutocomplete").search('');
});
} );
</script>
</head>
<body>
<div class="ui-widget">
<label for="tags">Tags: </label>
<input id="tags">
</div>
</body>
</html>
Check jsfiddle here:
https://jsfiddle.net/bao7fhm3/1/
How do I make the first letter of a string uppercase in JavaScript?
57 81 different answers for this question, some off-topic, and yet none of them raise the important issue that none of the solutions listed will work with Asian characters, emoji's, and other high Unicode-point-value characters in many browsers. Here is a solution that will:
const consistantCapitalizeFirstLetter = "\uD852\uDF62".length === 1 ?
function(S) {
"use-strict"; // Hooray! The browser uses UTF-32!
return S.charAt(0).toUpperCase() + string.substring(1);
} : function(S) {
"use-strict";
// The browser is using UCS16 to store UTF-16
var code = S.charCodeAt(0)|0;
return (
code >= 0xD800 && code <= 0xDBFF ? // Detect surrogate pair
S.slice(0,2).toUpperCase() + string.substring(2) :
S.charAt(0).toUpperCase() + string.substring(1)
);
};
const prettyCapitalizeFirstLetter = "\uD852\uDF62".length === 1 ?
function(S) {
"use-strict"; // Hooray! The browser uses UTF-32!
return S.charAt(0).toLocaleUpperCase() + string.substring(1);
} : function(S) {
"use-strict";
// The browser is using UCS16 to store UTF-16
var code = S.charCodeAt(0)|0;
return (
code >= 0xD800 && code <= 0xDBFF ? // Detect surrogate pair
S.slice(0,2).toLocaleUpperCase() + string.substring(2) :
S.charAt(0).toLocaleUpperCase() + string.substring(1)
);
};
Do note that the above solution tries to account for UTF-32. However, the specification officially states that browsers are required to do everything in UTF-16 mapped into UCS2. Nevertheless, if we all come together, do our part, and start preparing for UTF32, then there is a chance that the TC39 may allow browsers to start using UTF-32 (like how Python uses 24-bits for each character of the string). This must seem silly to an English speaker: no one who uses only latin-1 has ever had to deal with Mojibake because Latin-I is supported by all character encodings. But, users in other countries (such as China, Japan, Indonesia, etc.) are not so fortunate. They constantly struggle with encoding problems not just from the webpage, but also from the JavaScript: many Chinese/Japanese characters are treated as two letters by JavaScript and thus may be broken apart in the middle, resulting in ? and ? (two question-marks that make no sense to the end user). If we could start getting ready for UTF-32, then the TC39 might just allow browsers do what Python did many years ago which had made Python very popular for working with high Unicode characters: using UTF-32.
consistantCapitalizeFirstLetter
works correctly in Internet Explorer 3+. prettyCapitalizeFirstLetter
requires Internet Explorer 5.5+ (see the top of page 250 of this document). However, these fact are more of just jokes because it is very likely that the rest of the code on your webpage will not even work in Internet Explorer 8 - because of all the DOM and JScript bugs and lack of features in these older browsers. Further, no one uses Internet Explorer 3 or Internet Explorer 5.5 any more.
How do I use select with date condition?
I always get the filter date into a datetime, with no time (time= 00:00:00.000)
DECLARE @FilterDate datetime --final destination, will not have any time on it
DECLARE @GivenDateD datetime --if you're given a datetime
DECLARE @GivenDateS char(23) --if you're given a string, it can be any valid date format, not just the yyyy/mm/dd hh:mm:ss.mmm that I'm using
SET @GivenDateD='2009/03/30 13:42:50.123'
SET @GivenDateS='2009/03/30 13:42:50.123'
--remove the time and assign it to the datetime
@FilterDate=dateadd(dd, datediff(dd, 0, @FilterDateD), 0)
--OR
@FilterDate=dateadd(dd, datediff(dd, 0, @FilterDateS), 0)
You can use this WHERE clause to then filter:
WHERE ColumnDateTime>=@FilterDate AND ColumnDateTime<@FilterDate+1
this will give all matches that are on or after the beginning of the day on 2009/03/30 up to and including the complete day on 2009/03/30
you can do the same for START and END filter parameters as well. Always make the start date a datetime and use zero time on the day you want, and make the condition ">=". Always make the end date the zero time on the day after you want and use "<". Doing that, you will always include any dates properly, regardless of the time portion of the date.
What's is the difference between train, validation and test set, in neural networks?
Training set: A set of examples used for learning, that is to fit
the parameters [i.e., weights] of the classifier.
Validation set:
A set of examples used to tune the parameters [i.e., architecture, not weights] of a classifier, for example to choose the number of hidden units in a neural network.
Test set:
A set of examples used only to assess the performance [generalization] of a fully specified classifier.
From ftp://ftp.sas.com/pub/neural/FAQ1.txt section "What are the population, sample, training set, design set, validation"
The error surface will be different for different sets of data from your data set (batch learning). Therefore if you find a very good local minima for your test set data, that may not be a very good point, and may be a very bad point in the surface generated by some other set of data for the same problem. Therefore you need to compute such a model which not only finds a good weight configuration for the training set but also should be able to predict new data (which is not in the training set) with good error. In other words the network should be able to generalize the examples so that it learns the data and does not simply remembers or loads the training set by overfitting the training data.
The validation data set is a set of data for the function you want to learn, which you are not directly using to train the network. You are training the network with a set of data which you call the training data set. If you are using gradient based algorithm to train the network then the error surface and the gradient at some point will completely depend on the training data set thus the training data set is being directly used to adjust the weights. To make sure you don't overfit the network you need to input the validation dataset to the network and check if the error is within some range. Because the validation set is not being using directly to adjust the weights of the netowork, therefore a good error for the validation and also the test set indicates that the network predicts well for the train set examples, also it is expected to perform well when new example are presented to the network which was not used in the training process.
Early stopping is a way to stop training. There are different variations available, the main outline is, both the train and the validation set errors are monitored, the train error decreases at each iteration (backprop and brothers) and at first the validation error decreases. The training is stopped at the moment the validation error starts to rise. The weight configuration at this point indicates a model, which predicts the training data well, as well as the data which is not seen by the network . But because the validation data actually affects the weight configuration indirectly to select the weight configuration. This is where the Test set comes in. This set of data is never used in the training process. Once a model is selected based on the validation set, the test set data is applied on the network model and the error for this set is found. This error is a representative of the error which we can expect from absolutely new data for the same problem.
EDIT:
Also, in the case you do not have enough data for a validation set, you can use crossvalidation to tune the parameters as well as estimate the test error.
how to read System environment variable in Spring applicationContext
You are close :o)
Spring 3.0 adds Spring Expression Language.
You can use
<util:properties id="dbProperties"
location="classpath:config_#{systemProperties['env']}/db.properties" />
Combined with java ... -Denv=QA
should solve your problem.
Note also a comment by @yiling:
In order to access system environment variable, that is OS level
variables as amoe commented, we can simply use "systemEnvironment"
instead of "systemProperties" in that EL. Like
#{systemEnvironment['ENV_VARIABLE_NAME']}
How to convert a datetime to string in T-SQL
You can use the convert
statement in Microsoft SQL Server to convert a date to a string. An example of the syntax used would be:
SELECT convert(varchar(20), getdate(), 120)
The above would return the current date and time in a string with the format of YYYY-MM-DD HH:MM:SS
in 24 hour clock.
You can change the number at the end of the statement to one of many which will change the returned strings format. A list of these codes can be found on the MSDN in the CAST and CONVERT reference section.
C# constructors overloading
You can factor out your common logic to a private method, for example called Initialize
that gets called from both constructors.
Due to the fact that you want to perform argument validation you cannot resort to constructor chaining.
Example:
public Point2D(double x, double y)
{
// Contracts
Initialize(x, y);
}
public Point2D(Point2D point)
{
if (point == null)
throw new ArgumentNullException("point");
// Contracts
Initialize(point.X, point.Y);
}
private void Initialize(double x, double y)
{
X = x;
Y = y;
}
How to extract numbers from a string and get an array of ints?
Extract all real numbers using this.
public static ArrayList<Double> extractNumbersInOrder(String str){
str+='a';
double[] returnArray = new double[]{};
ArrayList<Double> list = new ArrayList<Double>();
String singleNum="";
Boolean numStarted;
for(char c:str.toCharArray()){
if(isNumber(c)){
singleNum+=c;
} else {
if(!singleNum.equals("")){ //number ended
list.add(Double.valueOf(singleNum));
System.out.println(singleNum);
singleNum="";
}
}
}
return list;
}
public static boolean isNumber(char c){
if(Character.isDigit(c)||c=='-'||c=='+'||c=='.'){
return true;
} else {
return false;
}
}
How to get UTC value for SYSDATE on Oracle
If you want a timestamp instead of just a date with sysdate, you can specify a timezone using systimestamp:
select systimestamp at time zone 'UTC' from dual
outputs: 29-AUG-17 06.51.14.781998000 PM UTC
ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'undefined'
I had the same issue trying to do something the same as you and I fixed it with something similar to Richie Fredicson's answer.
When you run createComponent() it is created with undefined input variables.
Then after that when you assign data to those input variables it changes things and causes that error in your child template (in my case it was because I was using the input in an ngIf, which changed once I assigned the input data).
The only way I could find to avoid it in this specific case is to force change detection after you assign the data, however I didn't do it in ngAfterContentChecked().
Your example code is a bit hard to follow but if my solution works for you it would be something like this (in the parent component):
export class ParentComponent implements AfterViewInit {
// I'm assuming you have a WidgetDirective.
@ViewChild(WidgetDirective) widgetHost: WidgetDirective;
constructor(
private componentFactoryResolver: ComponentFactoryResolver,
private changeDetector: ChangeDetectorRef
) {}
ngAfterViewInit() {
renderWidgetInsideWidgetContainer();
}
renderWidgetInsideWidgetContainer() {
let component = this.storeFactory.getWidgetComponent(this.dataSource.ComponentName);
let componentFactory = this.componentFactoryResolver.resolveComponentFactory(component);
let viewContainerRef = this.widgetHost.viewContainerRef;
viewContainerRef.clear();
let componentRef = viewContainerRef.createComponent(componentFactory);
debugger;
// This <IDataBind> type you are using here needs to be changed to be the component
// type you used for the call to resolveComponentFactory() above (if it isn't already).
// It tells it that this component instance if of that type and then it knows
// that WidgetDataContext and WidgetPosition are @Inputs for it.
(<IDataBind>componentRef.instance).WidgetDataContext = this.dataSource.DataContext;
(<IDataBind>componentRef.instance).WidgetPosition = this.dataSource.Position;
this.changeDetector.detectChanges();
}
}
Mine is almost the same as that except I'm using @ViewChildren instead of @ViewChild as I have multiple host elements.
Is it possible to add an array or object to SharedPreferences on Android
So from the android developer site on Data Storage:
User Preferences
Shared preferences are not strictly for saving "user preferences," such as what ringtone a user has chosen. If you're interested in creating user preferences for your application, see PreferenceActivity, which provides an Activity framework for you to create user preferences, which will be automatically persisted (using shared preferences).
So I think it is okay since it is simply just key-value pairs which are persisted.
To the original poster, this is not that hard. You simply just iterate through your array list and add the items. In this example I use a map for simplicity but you can use an array list and change it appropriately:
// my list of names, icon locations
Map<String, String> nameIcons = new HashMap<String, String>();
nameIcons.put("Noel", "/location/to/noel/icon.png");
nameIcons.put("Bob", "another/location/to/bob/icon.png");
nameIcons.put("another name", "last/location/icon.png");
SharedPreferences keyValues = getContext().getSharedPreferences("name_icons_list", Context.MODE_PRIVATE);
SharedPreferences.Editor keyValuesEditor = keyValues.edit();
for (String s : nameIcons.keySet()) {
// use the name as the key, and the icon as the value
keyValuesEditor.putString(s, nameIcons.get(s));
}
keyValuesEditor.commit()
You would do something similar to read the key-value pairs again. Let me know if this works.
Update: If you're using API level 11 or later, there is a method to write out a String Set
What's onCreate(Bundle savedInstanceState)
onCreate(Bundle savedInstanceState) Function in Android:
When an Activity first call or launched then onCreate(Bundle savedInstanceState) method is responsible to create the activity.
When ever orientation(i.e. from horizontal to vertical or vertical to horizontal) of activity gets changed or when an Activity gets forcefully terminated by any Operating System then savedInstanceState i.e. object of Bundle Class will save the state of an Activity.
After Orientation changed then onCreate(Bundle savedInstanceState) will call and recreate the activity and load all data from savedInstanceState.
Basically Bundle class is used to stored the data of activity whenever above condition occur in app.
onCreate() is not required for apps. But the reason it is used in app is because that method is the best place to put initialization code.
You could also put your initialization code in onStart() or onResume() and when you app will load first, it will work same as in onCreate().
How do I use ROW_NUMBER()?
You can use Row_Number
for limit query result.
Example:
SELECT * FROM (
select row_number() OVER (order by createtime desc) AS ROWINDEX,*
from TABLENAME ) TB
WHERE TB.ROWINDEX between 0 and 10
--
With above query, I will get PAGE 1 of results from TABLENAME
.
How can I exclude multiple folders using Get-ChildItem -exclude?
I know this is quite old - but searching for an easy solution, I stumbled over this thread...
If I got the question right, you were looking for a way to list more than one directory using Get-ChildItem. There seems to be a much easier way using powershell 5.0 - example
Get-ChildItem -Path D:\ -Directory -Name -Exclude tmp,music
chaos
docs
downloads
games
pics
videos
Without the -Exclude clause, tmp and music would still be in that list. If you don't use -Name the -Exclude clause won't work, because of the detailed output of Get-ChildItem.
Hope this helps some people that are looking for an easy way to list all directory names without certain ones.
findAll() in yii
if you user $criteria, I recommend blow usage:
$criteria = new CDbCriteria();
$criteria->compare('email_id', 101);
$comments = EmailArchive::model()->findAll($criteria);
How to make a Qt Widget grow with the window size?
I found it was impossible to assign a layout to the centralwidget until I had added at least one child beneath it. Then I could highlight the tiny icon with the red 'disabled' mark and then click on a layout in the Designer toolbar at top.
Java - get the current class name?
In my case, I use this Java class:
private String getCurrentProcessName() {
String processName = "";
int pid = android.os.Process.myPid();
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
for (ActivityManager.RunningAppProcessInfo processInfo : manager.getRunningAppProcesses()) {
if (processInfo.pid == pid) {
processName = processInfo.processName;
break;
}
}
return processName;
}
How can I use Python to get the system hostname?
os.getenv('HOSTNAME')
and os.environ['HOSTNAME']
don't always work. In cron jobs and WSDL, HTTP HOSTNAME isn't set. Use this instead:
import socket
socket.gethostbyaddr(socket.gethostname())[0]
It always (even on Windows) returns a fully qualified host name, even if you defined a short alias in /etc/hosts.
If you defined an alias in /etc/hosts then socket.gethostname()
will return the alias. platform.uname()[1]
does the same thing.
I ran into a case where the above didn't work. This is what I'm using now:
import socket
if socket.gethostname().find('.')>=0:
name=socket.gethostname()
else:
name=socket.gethostbyaddr(socket.gethostname())[0]
It first calls gethostname to see if it returns something that looks like a host name, if not it uses my original solution.
GridLayout (not GridView) how to stretch all children evenly
Starting in API 21 the notion of weight was added to GridLayout. To support older android devices, you can use the GridLayout from the v7 support library.
The following XML gives an example of how you can use weights to fill the screen width.
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.GridLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:grid="http://schemas.android.com/apk/res-auto"
android:id="@+id/choice_grid"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:padding="4dp"
grid:alignmentMode="alignBounds"
grid:columnCount="2"
grid:rowOrderPreserved="false"
grid:useDefaultMargins="true">
<TextView
android:layout_width="0dp"
android:layout_height="100dp"
grid:layout_columnWeight="1"
grid:layout_gravity="fill_horizontal"
android:gravity="center"
android:background="#FF33B5E5"
android:text="Tile1" />
<TextView
android:layout_width="0dp"
android:layout_height="100dp"
grid:layout_columnWeight="1"
grid:layout_gravity="fill_horizontal"
android:gravity="center"
android:background="#FF33B5E5"
android:text="Tile2" />
<TextView
android:layout_width="0dp"
android:layout_height="100dp"
grid:layout_columnWeight="1"
grid:layout_gravity="fill_horizontal"
android:gravity="center"
android:background="#FF33B5E5"
android:text="Tile3" />
<TextView
android:layout_width="0dp"
android:layout_height="100dp"
grid:layout_columnWeight="1"
grid:layout_gravity="fill_horizontal"
android:gravity="center"
android:background="#FF33B5E5"
android:text="Tile4" />
</android.support.v7.widget.GridLayout>
Copy struct to struct in C
copy structure in c you just need to assign the values as follow:
struct RTCclk RTCclk1;
struct RTCclk RTCclkBuffert;
RTCclk1.second=3;
RTCclk1.minute=4;
RTCclk1.hour=5;
RTCclkBuffert=RTCclk1;
now RTCclkBuffert.hour will have value 5,
RTCclkBuffert.minute will have value 4
RTCclkBuffert.second will have value 3
Are there any log file about Windows Services Status?
Take a look at the System
log in Windows EventViewer (eventvwr
from the command line).
You should see entries with source as 'Service Control Manager'. e.g. on my WinXP machine,
Event Type: Information
Event Source: Service Control Manager
Event Category: None
Event ID: 7036
Date: 7/1/2009
Time: 12:09:43 PM
User: N/A
Computer: MyMachine
Description:
The Background Intelligent Transfer Service service entered the running state.
For more information, see Help and Support Center at http://go.microsoft.com/fwlink/events.asp.
SQL Query for Student mark functionality
I would have said:
select s.stname, s2.subname, highmarks.mark
from students s
join marks m on s.stid = m.stid
join Subject s2 on m.subid = s2.subid
join (select subid, max(mark) as mark
from marks group by subid) as highmarks
on highmarks.subid = m.subid and highmarks.mark = m.mark
order by subname, stname;
SQLFiddle here: http://sqlfiddle.com/#!2/5ef84/3
This is a:
- select on the students table to get the possible students
- a join to the marks table to match up students to marks,
- a join to the subjects table to resolve subject ids into names.
- a join to a derived table of the maximum marks in each subject.
Only the students that get maximum marks will meet all three join conditions. This lists all students who got that maximum mark, so if there are ties, both get listed.
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
The most common case I've seen for seemingly mysterious ArrayIndexOutOfBoundsExceptions, i.e. apparently not caused by your own array handling code, is the concurrent use of SimpleDateFormat. Particularly in a servlet or controller:
public class MyController {
SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
public void handleRequest(ServletRequest req, ServletResponse res) {
Date date = dateFormat.parse(req.getParameter("date"));
}
}
If two threads enter the SimplateDateFormat.parse() method together you will likely see an ArrayIndexOutOfBoundsException. Note the synchronization section of the class javadoc for SimpleDateFormat.
Make sure there is no place in your code that are accessing thread unsafe classes like SimpleDateFormat in a concurrent manner like in a servlet or controller. Check all instance variables of your servlets and controllers for likely suspects.
How to perform runtime type checking in Dart?
Dart Object
type has a runtimeType
instance member (source is from dart-sdk
v1.14, don't know if it was available earlier)
class Object {
//...
external Type get runtimeType;
}
Usage:
Object o = 'foo';
assert(o.runtimeType == String);
Best way to track onchange as-you-type in input type="text"?
These days listen for oninput
. It feels like onchange
without the need to lose focus on the element. It is HTML5.
It’s supported by everyone (even mobile), except IE8 and below. For IE add onpropertychange
. I use it like this:
_x000D_
_x000D_
const source = document.getElementById('source');_x000D_
const result = document.getElementById('result');_x000D_
_x000D_
const inputHandler = function(e) {_x000D_
result.innerHTML = e.target.value;_x000D_
}_x000D_
_x000D_
source.addEventListener('input', inputHandler);_x000D_
source.addEventListener('propertychange', inputHandler); // for IE8_x000D_
// Firefox/Edge18-/IE9+ don’t fire on <select><option>_x000D_
// source.addEventListener('change', inputHandler);
_x000D_
<input id="source">_x000D_
<div id="result"></div>
_x000D_
_x000D_
_x000D_
Excel VBA - Sum up a column
I think you are misinterpreting the source of the error; rExternalTotal appears to be equal to a single cell.
rReportData.offset(0,0) is equal to rReportData
rReportData.offset(261,0).end(xlUp) is likely also equal to rReportData, as you offset by 261 rows and then use the .end(xlUp) function which selects the top of a contiguous data range.
If you are interested in the sum of just a column, you can just refer to the whole column:
dExternalTotal = Application.WorksheetFunction.Sum(columns("A:A"))
or
dExternalTotal = Application.WorksheetFunction.Sum(columns((rReportData.column))
The worksheet function sum will correctly ignore blank spaces.
Let me know if this helps!
AWK: Access captured group from line pattern
With gawk, you can use the match
function to capture parenthesized groups.
gawk 'match($0, pattern, ary) {print ary[1]}'
example:
echo "abcdef" | gawk 'match($0, /b(.*)e/, a) {print a[1]}'
outputs cd
.
Note the specific use of gawk which implements the feature in question.
For a portable alternative you can achieve similar results with match()
and substr
.
example:
echo "abcdef" | awk 'match($0, /b[^e]*/) {print substr($0, RSTART+1, RLENGTH-1)}'
outputs cd
.
Launching Google Maps Directions via an intent on Android
You could use something like this:
Intent intent = new Intent(android.content.Intent.ACTION_VIEW,
Uri.parse("http://maps.google.com/maps?saddr=20.344,34.34&daddr=20.5666,45.345"));
startActivity(intent);
To start the navigation from the current location, remove the saddr
parameter and value.
You can use an actual street address instead of latitude and longitude. However this will give the user a dialog to choose between opening it via browser or Google Maps.
This will fire up Google Maps in navigation mode directly:
Intent intent = new Intent(android.content.Intent.ACTION_VIEW,
Uri.parse("google.navigation:q=an+address+city"));
UPDATE
In May 2017 Google launched the new API for universal, cross-platform Google Maps URLs:
https://developers.google.com/maps/documentation/urls/guide
You can use Intents with the new API as well.
What exactly is an instance in Java?
"creating an instance of a class" how about, "you are taking a class and making a new variable of that class that WILL change depending on an input that changes"
Class in the library called Nacho
variable Libre to hold the "instance" that will change
Nacho Libre = new Nacho(Variable, Scanner Input, or whatever goes here, This is the place that accepts the changes then puts the value in "Libre" on the left side of the equals sign (you know "Nacho Libre = new Nacho(Scanner.in)" "Nacho Libre" is on the left of the = (that's not tech talk, that's my way of explaining it)
I think that is better than saying "instance of type" or "instance of class". Really the point is it just needs to be detailed out more.... "instance of type or class" is not good enough for the beginner..... wow, its like a tongue twister and your brain cannot focus on tongue twisters very well.... that "instance" word is very annoying and the mere sound of it drives me nuts.... it begs for more detail.....it begs to be broken down better. I had to google what "instance" meant just to get my bearings straight..... try saying "instance of class" to your grandma.... yikes!
Javascript Append Child AFTER Element
You could also do
function insertAfter(node1, node2) {
node1.outerHTML += node2.outerHTML;
}
or
function insertAfter2(node1, node2) {
var wrap = document.createElement("div");
wrap.appendChild(node2.cloneNode(true));
var node2Html = wrap.innerHTML;
node1.insertAdjacentHTML('afterend', node2Html);
}
No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization
Do not use authorization instead of authentication. I should get whole access to service all clients with header.
The working code is :
public class TokenAuthenticationHandler : AuthenticationHandler<TokenAuthenticationOptions>
{
public IServiceProvider ServiceProvider { get; set; }
public TokenAuthenticationHandler (IOptionsMonitor<TokenAuthenticationOptions> options, ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock, IServiceProvider serviceProvider)
: base (options, logger, encoder, clock)
{
ServiceProvider = serviceProvider;
}
protected override Task<AuthenticateResult> HandleAuthenticateAsync ()
{
var headers = Request.Headers;
var token = "X-Auth-Token".GetHeaderOrCookieValue (Request);
if (string.IsNullOrEmpty (token)) {
return Task.FromResult (AuthenticateResult.Fail ("Token is null"));
}
bool isValidToken = false; // check token here
if (!isValidToken) {
return Task.FromResult (AuthenticateResult.Fail ($"Balancer not authorize token : for token={token}"));
}
var claims = new [] { new Claim ("token", token) };
var identity = new ClaimsIdentity (claims, nameof (TokenAuthenticationHandler));
var ticket = new AuthenticationTicket (new ClaimsPrincipal (identity), this.Scheme.Name);
return Task.FromResult (AuthenticateResult.Success (ticket));
}
}
Startup.cs :
#region Authentication
services.AddAuthentication (o => {
o.DefaultScheme = SchemesNamesConst.TokenAuthenticationDefaultScheme;
})
.AddScheme<TokenAuthenticationOptions, TokenAuthenticationHandler> (SchemesNamesConst.TokenAuthenticationDefaultScheme, o => { });
#endregion
And mycontroller.cs
[Authorize(AuthenticationSchemes = SchemesNamesConst.TokenAuthenticationDefaultScheme)]
public class MainController : BaseController
{ ... }
I can't find TokenAuthenticationOptions now, but it was empty. I found the same class PhoneNumberAuthenticationOptions :
public class PhoneNumberAuthenticationOptions : AuthenticationSchemeOptions
{
public Regex PhoneMask { get; set; }// = new Regex("7\\d{10}");
}
You should define static class SchemesNamesConst
. Something like:
public static class SchemesNamesConst
{
public const string TokenAuthenticationDefaultScheme = "TokenAuthenticationScheme";
}
Spring JDBC Template for calling Stored Procedures
There are a number of ways to call stored procedures in Spring.
If you use CallableStatementCreator
to declare parameters, you will be using Java's standard interface of CallableStatement
, i.e register out parameters and set them separately. Using SqlParameter
abstraction will make your code cleaner.
I recommend you looking at SimpleJdbcCall
. It may be used like this:
SimpleJdbcCall jdbcCall = new SimpleJdbcCall(jdbcTemplate)
.withSchemaName(schema)
.withCatalogName(package)
.withProcedureName(procedure)();
...
jdbcCall.addDeclaredParameter(new SqlParameter(paramName, OracleTypes.NUMBER));
...
jdbcCall.execute(callParams);
For simple procedures you may use jdbcTemplate
's update
method:
jdbcTemplate.update("call SOME_PROC (?, ?)", param1, param2);
EOFError: EOF when reading a line
width, height = map(int, input().split())
def rectanglePerimeter(width, height):
return ((width + height)*2)
print(rectanglePerimeter(width, height))
Running it like this produces:
% echo "1 2" | test.py
6
I suspect IDLE is simply passing a single string to your script. The first input()
is slurping the entire string. Notice what happens if you put some print statements in after the calls to input()
:
width = input()
print(width)
height = input()
print(height)
Running echo "1 2" | test.py
produces
1 2
Traceback (most recent call last):
File "/home/unutbu/pybin/test.py", line 5, in <module>
height = input()
EOFError: EOF when reading a line
Notice the first print statement prints the entire string '1 2'
. The second call to input()
raises the EOFError
(end-of-file error).
So a simple pipe such as the one I used only allows you to pass one string. Thus you can only call input()
once. You must then process this string, split it on whitespace, and convert the string fragments to ints yourself. That is what
width, height = map(int, input().split())
does.
Note, there are other ways to pass input to your program. If you had run test.py
in a terminal, then you could have typed 1
and 2
separately with no problem. Or, you could have written a program with pexpect to simulate a terminal, passing 1
and 2
programmatically. Or, you could use argparse to pass arguments on the command line, allowing you to call your program with
test.py 1 2
React-Router External link
I actually ended up building my own Component. <Redirect>
It takes info from the react-router
element so I can keep it in my routes. Such as:
<Route
path="/privacy-policy"
component={ Redirect }
loc="https://meetflo.zendesk.com/hc/en-us/articles/230425728-Privacy-Policies"
/>
Here is my component incase-anyone is curious:
import React, { Component } from "react";
export class Redirect extends Component {
constructor( props ){
super();
this.state = { ...props };
}
componentWillMount(){
window.location = this.state.route.loc;
}
render(){
return (<section>Redirecting...</section>);
}
}
export default Redirect;
EDIT -- NOTE:
This is with react-router: 3.0.5
, it is not so simple in 4.x
How do I create a WPF Rounded Corner container?
You don't need a custom control, just put your container in a border element:
<Border BorderBrush="#FF000000" BorderThickness="1" CornerRadius="8">
<Grid/>
</Border>
You can replace the <Grid/>
with any of the layout containers...
How to compare two lists in python?
Given the code you provided in comments, I assume you want to do this:
>>> dateList = "Thu Sep 16 13:14:15 CDT 2010".split()
>>> sdateList = "Thu Sep 16 14:14:15 CDT 2010".split()
>>> dateList == sdataList
false
The split
-method of the string returns a list. A list in Python is very different from an array. ==
in this case does an element-wise comparison of the two lists and returns if all their elements are equal and the number and order of the elements is the same. Read the documentation.
docker: "build" requires 1 argument. See 'docker build --help'
Did you copy the build command from somewhere else (webpage or some other file)? Try typing it in from scratch.
I copied a build command from an AWS tutorial and pasted it into my terminal and was getting this error. It was driving me crazy. After typing it in by hand, it worked! Looking closer and my previous failed commands, I noticed the "dash" character was different, it was a thinner, longer dash character than I got if I typed it myself using the "minus/dash" key.
Bad:
sudo docker build –t foo .
Good:
sudo docker build -t foo .
Can you see the difference?.. Cut and paste is hard.
"Could not load type [Namespace].Global" causing me grief
I was befuddled by the same darn issue. I tried to remove and and the global.asax
(closed VS2010 before adding). Cleaned the project/solution, checked for any changes in the web application configuration and other stuffs that had worked for other people here in SO threads. I finally cleaned the solution, deleted the bin/obj folders and stopped any running VS2010 development servers then I reverted all the changes back and found the application was running again. I redid the same things and now its working fine.
Happened again and this time this solution worked for me.
Converting HTML to PDF using PHP?
If you wish to create a pdf from php, pdflib will help you (as some others suggested).
Else, if you want to convert an HTML page to PDF via PHP, you'll find a little trouble outta here.. For 3 years I've been trying to do it as best as I can.
So, the options I know are:
DOMPDF : php class that wraps the html and builds the pdf. Works good, customizable (if you know php), based on pdflib, if I remember right it takes even some CSS. Bad news: slow when the html is big or complex.
HTML2PS: same as DOMPDF, but this one converts first to a .ps (ghostscript) file, then, to whatever format you need (pdf, jpg, png). For me is little better than dompdf, but has the same speed problem.. but, better compatibility with CSS.
Those two are php classes, but if you can install some software on the server, and access it throught passthru() or system(), give a look to these too:
wkhtmltopdf: based on webkit (safari's wrapper), is really fast and powerful.. seems like this is the best one (atm) for converting html pages to pdf on the fly; taking only 2 seconds for a 3 page xHTML document with CSS2. It is a recent project, anyway, the google.code page is often updated.
htmldoc : This one is a tank, it never really stops/crashes.. the project looks dead since 2007, but anyway if you don't need CSS compatibility this can be nice for you.
Get last 3 characters of string
Many ways this can be achieved.
Simple approach should be taking Substring
of an input string.
var result = input.Substring(input.Length - 3);
Another approach using Regular Expression
to extract last 3 characters.
var result = Regex.Match(input,@"(.{3})\s*$");
Working Demo
How to turn off the Eclipse code formatter for certain sections of Java code?
@xpmatteo has the answer to disabling portions of code, but in addition to this, the default eclipse settings should be set to only format edited lines of code instead of the whole file.
Preferences->Java->Editor->Save Actions->Format Source Code->Format Edited Lines
This would have prevented it from happening in the first place since your coworkers are reformatting code they didn't actually change. This is a good practice to prevent mishaps that render diff on your source control useless (when an entire file is reformatted because of minor format setting differences).
It would also prevent the reformatting if the on/off tags option was turned off.
How to write to a file in Scala?
Similar to this answer, here is an example with fs2
(version 1.0.4):
import cats.effect._
import fs2._
import fs2.io
import java.nio.file._
import scala.concurrent.ExecutionContext
import scala.language.higherKinds
import cats.syntax.functor._
object ScalaApp extends IOApp {
def write[T[_]](p: Path, s: String)
(implicit F: ConcurrentEffect[T], cs: ContextShift[T]): T[Unit] = {
Stream(s)
.covary[T]
.through(text.utf8Encode)
.through(
io.file.writeAll(
p,
scala.concurrent.ExecutionContext.global,
Seq(StandardOpenOption.CREATE)
)
)
.compile
.drain
}
def run(args: List[String]): IO[ExitCode] = {
implicit val executionContext: ExecutionContext =
scala.concurrent.ExecutionContext.Implicits.global
implicit val contextShift: ContextShift[IO] =
IO.contextShift(executionContext)
val outputFile: Path = Paths.get("output.txt")
write[IO](outputFile, "Hello world\n").as(ExitCode.Success)
}
}
Background Image for Select (dropdown) does not work in Chrome
Generally, it's considered a bad practice to style standard form controls because the output looks so different on each browser. See: http://www.456bereastreet.com/lab/styling-form-controls-revisited/select-single/ for some rendered examples.
That being said, I've had some luck making the background color an RGBA value:
<!DOCTYPE html>
<html>
<head>
<style>
body {
background: #d00;
}
select {
background: rgba(255,255,255,0.1) url('http://www.google.com/images/srpr/nav_logo6g.png') repeat-x 0 0;
padding:4px;
line-height: 21px;
border: 1px solid #fff;
}
</style>
</head>
<body>
<select>
<option>Foo</option>
<option>Bar</option>
<option>Something longer</option>
</body>
</html>
Google Chrome still renders a gradient on top of the background image in the color that you pass to rgba(r,g,b,0.1) but choosing a color that compliments your image and making the alpha 0.1 reduces the effect of this.
C++ String array sorting
Your loop does not do anything because your counter z
is 0 (and 0 < 0 evaluates to false
, so the loop never starts).
Instead, if you have access to C++11 (and you really should aim for that!) try to use iterators, e.g. by using the non-member function std::begin()
and std::end()
, and a range-for loop to display the result:
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main()
{
int z = 0;
string name[] = {"john", "bobby", "dear", "test1", "catherine", "nomi", "shinta", "martin", "abe", "may", "zeno", "zack", "angeal", "gabby"};
sort(begin(name),end(name));
for(auto n: name){
cout << n << endl;
}
return 0;
}
Live example.
Multiple "order by" in LINQ
Add "new":
var movies = _db.Movies.OrderBy( m => new { m.CategoryID, m.Name })
That works on my box. It does return something that can be used to sort. It returns an object with two values.
Similar, but different to sorting by a combined column, as follows.
var movies = _db.Movies.OrderBy( m => (m.CategoryID.ToString() + m.Name))
Turn ON/OFF Camera LED/flash light in Samsung Galaxy Ace 2.2.1 & Galaxy Tab
I will soon released a new version of my app to support to galaxy ace.
You can download here: https://play.google.com/store/apps/details?id=droid.pr.coolflashlightfree
In order to solve your problem you should do this:
this._camera = Camera.open();
this._camera.startPreview();
this._camera.autoFocus(new AutoFocusCallback() {
public void onAutoFocus(boolean success, Camera camera) {
}
});
Parameters params = this._camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_ON);
this._camera.setParameters(params);
params = this._camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_OFF);
this._camera.setParameters(params);
don't worry about FLASH_MODE_OFF because this will keep the light on, strange but it's true
to turn off the led just release the camera
SELECT query with CASE condition and SUM()
To get each sum in a separate column:
Select SUM(IF(CPaymentType='Check', CAmount, 0)) as PaymentAmountCheck,
SUM(IF(CPaymentType='Cash', CAmount, 0)) as PaymentAmountCash
from TableOrderPayment
where CPaymentType IN ('Check','Cash')
and CDate<=SYSDATETIME()
and CStatus='Active';
Copy and Paste a set range in the next empty row
You could also try this
Private Sub CommandButton1_Click()
Sheets("Sheet1").Range("A3:E3").Copy
Dim lastrow As Long
lastrow = Range("A65536").End(xlUp).Row
Sheets("Summary Info").Activate
Cells(lastrow + 1, 1).PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
End Sub
How can I easily convert DataReader to List<T>?
You cant simply (directly) convert the datareader to list.
You have to loop through all the elements in datareader and insert into list
below the sample code
using (drOutput)
{
System.Collections.Generic.List<CustomerEntity > arrObjects = new System.Collections.Generic.List<CustomerEntity >();
int customerId = drOutput.GetOrdinal("customerId ");
int CustomerName = drOutput.GetOrdinal("CustomerName ");
while (drOutput.Read())
{
CustomerEntity obj=new CustomerEntity ();
obj.customerId = (drOutput[customerId ] != Convert.DBNull) ? drOutput[customerId ].ToString() : null;
obj.CustomerName = (drOutput[CustomerName ] != Convert.DBNull) ? drOutput[CustomerName ].ToString() : null;
arrObjects .Add(obj);
}
}
How to select all instances of a variable and edit variable name in Sublime
To me, this is the biggest mistake in Sublime. Alt+F3 is hard to reach/remember, and Ctrl+Shift+G makes no sense considering Ctrl+D is "add next instance to selection".
Add this to your User Key Bindings (Preferences > Key Bindings):
{ "keys": ["ctrl+shift+d"], "command": "find_all_under" },
Now you can highlight something, press Ctrl+Shift+D, and it will add every other instance in the file to the selection.
Difference between map and collect in Ruby?
I did a benchmark test to try and answer this question, then found this post so here are my findings (which differ slightly from the other answers)
Here is the benchmark code:
require 'benchmark'
h = { abc: 'hello', 'another_key' => 123, 4567 => 'third' }
a = 1..10
many = 500_000
Benchmark.bm do |b|
GC.start
b.report("hash keys collect") do
many.times do
h.keys.collect(&:to_s)
end
end
GC.start
b.report("hash keys map") do
many.times do
h.keys.map(&:to_s)
end
end
GC.start
b.report("array collect") do
many.times do
a.collect(&:to_s)
end
end
GC.start
b.report("array map") do
many.times do
a.map(&:to_s)
end
end
end
And the results I got were:
user system total real
hash keys collect 0.540000 0.000000 0.540000 ( 0.570994)
hash keys map 0.500000 0.010000 0.510000 ( 0.517126)
array collect 1.670000 0.020000 1.690000 ( 1.731233)
array map 1.680000 0.020000 1.700000 ( 1.744398)
Perhaps an alias isn't free?
Understanding typedefs for function pointers in C
Consider the signal()
function from the C standard:
extern void (*signal(int, void(*)(int)))(int);
Perfectly obscurely obvious - it's a function that takes two arguments, an integer and a pointer to a function that takes an integer as an argument and returns nothing, and it (signal()
) returns a pointer to a function that takes an integer as an argument and returns nothing.
If you write:
typedef void (*SignalHandler)(int signum);
then you can instead declare signal()
as:
extern SignalHandler signal(int signum, SignalHandler handler);
This means the same thing, but is usually regarded as somewhat easier to read. It is clearer that the function takes an int
and a SignalHandler
and returns a SignalHandler
.
It takes a bit of getting used to, though. The one thing you can't do, though is write a signal handler function using the SignalHandler
typedef
in the function definition.
I'm still of the old-school that prefers to invoke a function pointer as:
(*functionpointer)(arg1, arg2, ...);
Modern syntax uses just:
functionpointer(arg1, arg2, ...);
I can see why that works - I just prefer to know that I need to look for where the variable is initialized rather than for a function called functionpointer
.
Sam commented:
I have seen this explanation before. And then, as is the case now, I think what I didn't get was the connection between the two statements:
extern void (*signal(int, void()(int)))(int); /*and*/
typedef void (*SignalHandler)(int signum);
extern SignalHandler signal(int signum, SignalHandler handler);
Or, what I want to ask is, what is the underlying concept that one can use to come up with the second version you have? What is the fundamental that connects "SignalHandler" and the first typedef? I think what needs to be explained here is what is typedef is actually doing here.
Let's try again. The first of these is lifted straight from the C standard - I retyped it, and checked that I had the parentheses right (not until I corrected it - it is a tough cookie to remember).
First of all, remember that typedef
introduces an alias for a type. So, the alias is SignalHandler
, and its type is:
a pointer to a function that takes an integer as an argument and returns nothing.
The 'returns nothing' part is spelled void
; the argument that is an integer is (I trust) self-explanatory. The following notation is simply (or not) how C spells pointer to function taking arguments as specified and returning the given type:
type (*function)(argtypes);
After creating the signal handler type, I can use it to declare variables and so on. For example:
static void alarm_catcher(int signum)
{
fprintf(stderr, "%s() called (%d)\n", __func__, signum);
}
static void signal_catcher(int signum)
{
fprintf(stderr, "%s() called (%d) - exiting\n", __func__, signum);
exit(1);
}
static struct Handlers
{
int signum;
SignalHandler handler;
} handler[] =
{
{ SIGALRM, alarm_catcher },
{ SIGINT, signal_catcher },
{ SIGQUIT, signal_catcher },
};
int main(void)
{
size_t num_handlers = sizeof(handler) / sizeof(handler[0]);
size_t i;
for (i = 0; i < num_handlers; i++)
{
SignalHandler old_handler = signal(handler[i].signum, SIG_IGN);
if (old_handler != SIG_IGN)
old_handler = signal(handler[i].signum, handler[i].handler);
assert(old_handler == SIG_IGN);
}
...continue with ordinary processing...
return(EXIT_SUCCESS);
}
Please note How to avoid using printf()
in a signal handler?
So, what have we done here - apart from omit 4 standard headers that would be needed to make the code compile cleanly?
The first two functions are functions that take a single integer and return nothing. One of them actually doesn't return at all thanks to the exit(1);
but the other does return after printing a message. Be aware that the C standard does not permit you to do very much inside a signal handler; POSIX is a bit more generous in what is allowed, but officially does not sanction calling fprintf()
. I also print out the signal number that was received. In the alarm_handler()
function, the value will always be SIGALRM
as that is the only signal that it is a handler for, but signal_handler()
might get SIGINT
or SIGQUIT
as the signal number because the same function is used for both.
Then I create an array of structures, where each element identifies a signal number and the handler to be installed for that signal. I've chosen to worry about 3 signals; I'd often worry about SIGHUP
, SIGPIPE
and SIGTERM
too and about whether they are defined (#ifdef
conditional compilation), but that just complicates things. I'd also probably use POSIX sigaction()
instead of signal()
, but that is another issue; let's stick with what we started with.
The main()
function iterates over the list of handlers to be installed. For each handler, it first calls signal()
to find out whether the process is currently ignoring the signal, and while doing so, installs SIG_IGN
as the handler, which ensures that the signal stays ignored. If the signal was not previously being ignored, it then calls signal()
again, this time to install the preferred signal handler. (The other value is presumably SIG_DFL
, the default signal handler for the signal.) Because the first call to 'signal()' set the handler to SIG_IGN
and signal()
returns the previous error handler, the value of old
after the if
statement must be SIG_IGN
- hence the assertion. (Well, it could be SIG_ERR
if something went dramatically wrong - but then I'd learn about that from the assert firing.)
The program then does its stuff and exits normally.
Note that the name of a function can be regarded as a pointer to a function of the appropriate type. When you do not apply the function-call parentheses - as in the initializers, for example - the function name becomes a function pointer. This is also why it is reasonable to invoke functions via the pointertofunction(arg1, arg2)
notation; when you see alarm_handler(1)
, you can consider that alarm_handler
is a pointer to the function and therefore alarm_handler(1)
is an invocation of a function via a function pointer.
So, thus far, I've shown that a SignalHandler
variable is relatively straight-forward to use, as long as you have some of the right type of value to assign to it - which is what the two signal handler functions provide.
Now we get back to the question - how do the two declarations for signal()
relate to each other.
Let's review the second declaration:
extern SignalHandler signal(int signum, SignalHandler handler);
If we changed the function name and the type like this:
extern double function(int num1, double num2);
you would have no problem interpreting this as a function that takes an int
and a double
as arguments and returns a double
value (would you? maybe you'd better not 'fess up if that is problematic - but maybe you should be cautious about asking questions as hard as this one if it is a problem).
Now, instead of being a double
, the signal()
function takes a SignalHandler
as its second argument, and it returns one as its result.
The mechanics by which that can also be treated as:
extern void (*signal(int signum, void(*handler)(int signum)))(int signum);
are tricky to explain - so I'll probably screw it up. This time I've given the parameters names - though the names aren't critical.
In general, in C, the declaration mechanism is such that if you write:
type var;
then when you write var
it represents a value of the given type
. For example:
int i; // i is an int
int *ip; // *ip is an int, so ip is a pointer to an integer
int abs(int val); // abs(-1) is an int, so abs is a (pointer to a)
// function returning an int and taking an int argument
In the standard, typedef
is treated as a storage class in the grammar, rather like static
and extern
are storage classes.
typedef void (*SignalHandler)(int signum);
means that when you see a variable of type SignalHandler
(say alarm_handler) invoked as:
(*alarm_handler)(-1);
the result has type void
- there is no result. And (*alarm_handler)(-1);
is an invocation of alarm_handler()
with argument -1
.
So, if we declared:
extern SignalHandler alt_signal(void);
it means that:
(*alt_signal)();
represents a void value. And therefore:
extern void (*alt_signal(void))(int signum);
is equivalent. Now, signal()
is more complex because it not only returns a SignalHandler
, it also accepts both an int and a SignalHandler
as arguments:
extern void (*signal(int signum, SignalHandler handler))(int signum);
extern void (*signal(int signum, void (*handler)(int signum)))(int signum);
If that still confuses you, I'm not sure how to help - it is still at some levels mysterious to me, but I've grown used to how it works and can therefore tell you that if you stick with it for another 25 years or so, it will become second nature to you (and maybe even a bit quicker if you are clever).
Open file in a relative location in Python
Python just passes the filename you give it to the operating system, which opens it. If your operating system supports relative paths like main/2091/data.txt
(hint: it does), then that will work fine.
You may find that the easiest way to answer a question like this is to try it and see what happens.
Why do I need to configure the SQL dialect of a data source?
Dialect is the SQL dialect that your database uses.
List of SQL dialects for Hibernate.
Either provide it in hibernate.cfg.xml as :
<hibernate-configuration>
<session-factory name="session-factory">
<property name="hibernate.dialect">org.hibernate.dialect.SQLServerDialect</property>
...
</session-factory>
</hibernate-configuration>
or in the properties file as :
hibernate.dialect=org.hibernate.dialect.SQLServerDialect
How can I put the current running linux process in background?
Suspend the process with CTRL+Z then use the command bg
to resume it in background. For example:
sleep 60
^Z #Suspend character shown after hitting CTRL+Z
[1]+ Stopped sleep 60 #Message showing stopped process info
bg #Resume current job (last job stopped)
More about job control and bg
usage in bash
manual page:
JOB CONTROL
Typing the suspend character (typically ^Z, Control-Z) while a process is running causes that process to be stopped and returns control to bash. [...] The user may then manipulate the state of this job, using the bg command to continue it in the background, [...]. A ^Z takes effect immediately, and has the additional side effect of causing pending output and typeahead to be discarded.
bg [jobspec ...]
Resume each suspended job jobspec in the background, as if it had been started with &. If jobspec is not present, the shell's notion of the current job is used.
EDIT
To start a process where you can even kill the terminal and it still carries on running
nohup [command] [-args] > [filename] 2>&1 &
e.g.
nohup /home/edheal/myprog -arg1 -arg2 > /home/edheal/output.txt 2>&1 &
To just ignore the output (not very wise) change the filename to /dev/null
To get the error message set to a different file change the &1
to a filename.
In addition: You can use the jobs
command to see an indexed list of those backgrounded processes. And you can kill a backgrounded process by running kill %1
or kill %2
with the number being the index of the process.
Get a list of dates between two dates using a function
WITH TEMP (DIA, SIGUIENTE_DIA ) AS
(SELECT
1,
CAST(@FECHAINI AS DATE)
FROM
DUAL
UNION ALL
SELECT
DIA,
DATEADD(DAY, DIA, SIGUIENTE_DIA)
FROM
TEMP
WHERE
DIA < DATEDIFF(DAY, @FECHAINI, @FECHAFIN)
AND DATEADD(DAY, 1, SIGUIENTE_DIA) <= CAST(@FECHAFIN AS DATE)
)
SELECT
SIGUIENTE_DIA AS CALENDARIO
FROM
TEMP
ORDER BY
SIGUIENTE_DIA
The detail is on the table DUAL but if your exchange this table for a dummy table this works.
VSCode Change Default Terminal
You can also select your default terminal by pressing F1 in VS Code and typing/selecting Terminal: Select Default Shell.
I want to get the type of a variable at runtime
If by the type of a variable you mean the runtime class of the object that the variable points to, then you can get this through the class reference that all objects have.
val name = "sam";
name: java.lang.String = sam
name.getClass
res0: java.lang.Class[_] = class java.lang.String
If you however mean the type that the variable was declared as, then you cannot get that. Eg, if you say
val name: Object = "sam"
then you will still get a String
back from the above code.
Difference between .dll and .exe?
Difference in DLL and EXE:
1) DLL is an In-Process Component which means running in the same memory space as the client process. EXE is an Out-Process Component which means it runs in its own separate memory space.
2) The DLL contains functions and procedures that other programs can use (promotes reuability) while EXE cannot be shared with other programs.
3) DLL cannot be directly executed as they're designed to be loaded and run by other programs. EXE is a program that is executed directly.
How can I set my Cygwin PATH to find javac?
Although all other answers are technically correct, I would recommend you adding the custom path to the beginning of your PATH, not at the end. That way it would be the first place to look for instead of the last:
Add to bottom of ~/.bash_profile
:
export PATH="/cygdrive/C/Program Files/Java/jdk1.6.0_23/bin/":$PATH
That way if you have more than one java
or javac
it will use the one you provided first.
When a 'blur' event occurs, how can I find out which element focus went *to*?
Can you reverse what you're checking and when? That is if you remeber what was blurred last:
<input id="myInput" onblur="lastBlurred=this;"></input>
and then in the onClick for your span, call function() with both objects:
<span id="mySpan" onClick="function(lastBlurred, this);">Hello World</span>
Your function could then decide whether or not to trigger the Ajax.AutoCompleter control. The function has the clicked object and the blurred object. The onBlur has already happened so it won't make the suggestions disappear.
Access denied for user 'test'@'localhost' (using password: YES) except root user
It looks like you're trying to make a user 'golden'@'%' but a different user by the name of 'golden'@'localhost' is getting in the way/has precedence.
Do this command to see the users:
SELECT user,host FROM mysql.user;
You should see two entries:
1) user= golden, host=%
2) user= golden, host=localhost
Do these Command:
DROP User 'golden'@'localhost';
DROP User 'golden'@'%';
Restart MySQL Workbench.
Then do your original commands again:
CREATE USER 'golden'@'%' IDENTIFIED BY 'password';
GRANT ALL PRIVILEGES ON * . * TO 'golden'@'%';
Then when you go to try to sign in to MySQL, type it in like this:
Hit 'Test Connection' and enter your password 'password'.
Adding content to a linear layout dynamically?
In your onCreate()
, write the following
LinearLayout myRoot = (LinearLayout) findViewById(R.id.my_root);
LinearLayout a = new LinearLayout(this);
a.setOrientation(LinearLayout.HORIZONTAL);
a.addView(view1);
a.addView(view2);
a.addView(view3);
myRoot.addView(a);
view1
, view2
and view3
are your TextView
s. They're easily created programmatically.
Is it possible to read from a InputStream with a timeout?
Assuming your stream is not backed by a socket (so you can't use Socket.setSoTimeout()
), I think the standard way of solving this type of problem is to use a Future.
Suppose I have the following executor and streams:
ExecutorService executor = Executors.newFixedThreadPool(2);
final PipedOutputStream outputStream = new PipedOutputStream();
final PipedInputStream inputStream = new PipedInputStream(outputStream);
I have writer that writes some data then waits for 5 seconds before writing the last piece of data and closing the stream:
Runnable writeTask = new Runnable() {
@Override
public void run() {
try {
outputStream.write(1);
outputStream.write(2);
Thread.sleep(5000);
outputStream.write(3);
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
};
executor.submit(writeTask);
The normal way of reading this is as follows. The read will block indefinitely for data and so this completes in 5s:
long start = currentTimeMillis();
int readByte = 1;
// Read data without timeout
while (readByte >= 0) {
readByte = inputStream.read();
if (readByte >= 0)
System.out.println("Read: " + readByte);
}
System.out.println("Complete in " + (currentTimeMillis() - start) + "ms");
which outputs:
Read: 1
Read: 2
Read: 3
Complete in 5001ms
If there was a more fundamental problem, like the writer not responding, the reader would block for ever.
If I wrap the read in a future, I can then control the timeout as follows:
int readByte = 1;
// Read data with timeout
Callable<Integer> readTask = new Callable<Integer>() {
@Override
public Integer call() throws Exception {
return inputStream.read();
}
};
while (readByte >= 0) {
Future<Integer> future = executor.submit(readTask);
readByte = future.get(1000, TimeUnit.MILLISECONDS);
if (readByte >= 0)
System.out.println("Read: " + readByte);
}
which outputs:
Read: 1
Read: 2
Exception in thread "main" java.util.concurrent.TimeoutException
at java.util.concurrent.FutureTask$Sync.innerGet(FutureTask.java:228)
at java.util.concurrent.FutureTask.get(FutureTask.java:91)
at test.InputStreamWithTimeoutTest.main(InputStreamWithTimeoutTest.java:74)
I can catch the TimeoutException and do whatever cleanup I want.
How to add elements to an empty array in PHP?
When one wants elements to be added with zero-based element indexing, I guess this will work as well:
// adding elements to an array with zero-based index
$matrix= array();
$matrix[count($matrix)]= 'element 1';
$matrix[count($matrix)]= 'element 2';
...
$matrix[count($matrix)]= 'element N';
Increase max_execution_time in PHP?
For increasing execution time and file size, you need to mention below values in your .htaccess file. It will work.
php_value upload_max_filesize 80M
php_value post_max_size 80M
php_value max_input_time 18000
php_value max_execution_time 18000
Convert columns to string in Pandas
Using .apply()
with a lambda
conversion function also works in this case:
total_rows['ColumnID'] = total_rows['ColumnID'].apply(lambda x: str(x))
For entire dataframes you can use .applymap()
.
(but in any case probably .astype()
is faster)
Do we need type="text/css" for <link> in HTML5
The HTML5 spec says that the type
attribute is purely advisory and explains in detail how browsers should act if it's omitted (too much to quote here). It doesn't explicitly say that an omitted type attribute is either valid or invalid, but you can safely omit it knowing that browsers will still react as you expect.
How can I get the MAC and the IP address of a connected client in PHP?
You can do this easily using openWRT. If yo use a captive portal you can mix php and openWRT and make a relation between the IP and the mac.
You can write a simple PHP code using:
$localIP = getHostByName(getHostName());
Later, using openWRT you can go to /tmp/dhcp.leases
, you will get something with the form:
e4:a7:a0:29:xx:xx 10.239.3.XXX DESKTOP-XXX
There, you have the mac, the IP address and the hostname.
Reference list item by index within Django template?
A better way: custom template filter: https://docs.djangoproject.com/en/dev/howto/custom-template-tags/
such as get my_list[x] in templates:
in template
{% load index %}
{{ my_list|index:x }}
templatetags/index.py
from django import template
register = template.Library()
@register.filter
def index(indexable, i):
return indexable[i]
if my_list = [['a','b','c'], ['d','e','f']]
, you can use {{ my_list|index:x|index:y }}
in template to get my_list[x][y]
It works fine with "for"
{{ my_list|index:forloop.counter0 }}
Tested and works well ^_^
android get all contacts
Get all contacts in less than a second and without any load in your activity.
Follow my steps works like a charm.
ArrayList<Contact> contactList = new ArrayList<>();
private static final String[] PROJECTION = new String[]{
ContactsContract.CommonDataKinds.Phone.CONTACT_ID,
ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.NUMBER
};
private void getContactList() {
ContentResolver cr = getContentResolver();
Cursor cursor = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, PROJECTION, null, null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC");
if (cursor != null) {
HashSet<String> mobileNoSet = new HashSet<String>();
try {
final int nameIndex = cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
final int numberIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
String name, number;
while (cursor.moveToNext()) {
name = cursor.getString(nameIndex);
number = cursor.getString(numberIndex);
number = number.replace(" ", "");
if (!mobileNoSet.contains(number)) {
contactList.add(new Contact(name, number));
mobileNoSet.add(number);
Log.d("hvy", "onCreaterrView Phone Number: name = " + name
+ " No = " + number);
}
}
} finally {
cursor.close();
}
}
}
Contacts
public class Contact {
public String name;
public String phoneNumber;
public Contact() {
}
public Contact(String name, String phoneNumber ) {
this.name = name;
this.phoneNumber = phoneNumber;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
}
Benefits
- less than a second
- without load
- ascending order
- without duplicate contacts
How can I change image source on click with jQuery?
You should consider using a button for this. Links generally should be use for linking. Buttons can be used for other functionality you wish to add. Neals solution works, but its a workaround.
If you use a <button>
instead of a <a>
, your original code should work as expected.
Logging with Retrofit 2
Most of the answer here covers almost everything except this tool, one of the coolest ways to see the log.
It is Facebook's Stetho. This is the superb tool to monitor/log your app's network traffic on google chrome. You can also find here on Github.
Using SimpleXML to create an XML object from scratch
In PHP5, you should use the Document Object Model class instead.
Example:
$domDoc = new DOMDocument;
$rootElt = $domDoc->createElement('root');
$rootNode = $domDoc->appendChild($rootElt);
$subElt = $domDoc->createElement('foo');
$attr = $domDoc->createAttribute('ah');
$attrVal = $domDoc->createTextNode('OK');
$attr->appendChild($attrVal);
$subElt->appendChild($attr);
$subNode = $rootNode->appendChild($subElt);
$textNode = $domDoc->createTextNode('Wow, it works!');
$subNode->appendChild($textNode);
echo htmlentities($domDoc->saveXML());
Find row in datatable with specific id
DataRow dataRow = dataTable.AsEnumerable().FirstOrDefault(r => Convert.ToInt32(r["ID"]) == 5);
if (dataRow != null)
{
// code
}
If it is a typed DataSet:
MyDatasetType.MyDataTableRow dataRow = dataSet.MyDataTable.FirstOrDefault(r => r.ID == 5);
if (dataRow != null)
{
// code
}
Getting The ASCII Value of a character in a C# string
This example might help you. by using simple casting you can get code behind urdu character.
string str = "?????";
char ch = ' ';
int number = 0;
for (int i = 0; i < str.Length; i++)
{
ch = str[i];
number = (int)ch;
Console.WriteLine(number);
}
SCRIPT5: Access is denied in IE9 on xmlhttprequest
I had faced similar issue on IE10. I had a workaround by using the jQuery ajax request to retrieve data:
$.ajax({
url: YOUR_XML_FILE
aync: false,
success: function (data) {
// Store data into a variable
},
dataType: YOUR_DATA_TYPE,
complete: ON_COMPLETE_FUNCTION_CALL
});
Make Axios send cookies in its requests automatically
For anyone where none of these solutions are working, make sure that your request origin equals your request target, see this github issue.
I short, if you visit your website on 127.0.0.1:8000, then make sure that the requests you send are targeting your server on 127.0.0.1:8001 and not localhost:8001, although it might be the same target theoretically.
array filter in python?
>>> A = [6, 7, 8, 9, 10, 11, 12]
>>> subset_of_A = [6, 9, 12];
>>> set(A) - set(subset_of_A)
set([8, 10, 11, 7])
>>>
How to select into a variable in PL/SQL when the result might be null?
You can simply handle the NO_DATA_FOUND
exception by setting your variable to NULL
. This way, only one query is required.
v_column my_table.column%TYPE;
BEGIN
BEGIN
select column into v_column from my_table where ...;
EXCEPTION
WHEN NO_DATA_FOUND THEN
v_column := NULL;
END;
... use v_column here
END;
Best way to get application folder path
In my experience, the best way is a combination of these.
System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase
Will give you the bin folder
Directory.GetCurrentDirectory()
Works fine on .Net Core but not .Net and will give you the root directory of the project
System.AppContext.BaseDirectory
and AppDomain.CurrentDomain.BaseDirectory
Works fine in .Net but not .Net core and will give you the root directory of the project
In a class library that is supposed to target.Net and .Net core I check which framework is hosting the library and pick one or the other.
How to convert QString to std::string?
QString data;
data.toStdString().c_str();
could even throw exception on VS2017 compiler in xstring
~basic_string() _NOEXCEPT
{ // destroy the string
_Tidy_deallocate();
}
the right way ( secure - no exception) is how is explained above from Artyom
QString qs;
// Either this if you use UTF-8 anywhere
std::string utf8_text = qs.toUtf8().constData();
// or this if you're on Windows :-)
std::string current_locale_text = qs.toLocal8Bit().constData();
AngularJS Multiple ng-app within a page
You can define a Root ng-App and in this ng-App you can define multiple nd-Controler. Like this
<!DOCTYPE html>
<html>
<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.3/angular.min.js"></script>
<style>
table, th , td {
border: 1px solid grey;
border-collapse: collapse;
padding: 5px;
}
table tr:nth-child(odd) {
background-color: #f2f2f2;
}
table tr:nth-child(even) {
background-color: #ffffff;
}
</style>
<script>
var mainApp = angular.module("mainApp", []);
mainApp.controller('studentController1', function ($scope) {
$scope.student = {
firstName: "MUKESH",
lastName: "Paswan",
fullName: function () {
var studentObject;
studentObject = $scope.student;
return studentObject.firstName + " " + studentObject.lastName;
}
};
});
mainApp.controller('studentController2', function ($scope) {
$scope.student = {
firstName: "Mahesh",
lastName: "Parashar",
fees: 500,
subjects: [
{ name: 'Physics', marks: 70 },
{ name: 'Chemistry', marks: 80 },
{ name: 'Math', marks: 65 },
{ name: 'English', marks: 75 },
{ name: 'Hindi', marks: 67 }
],
fullName: function () {
var studentObject;
studentObject = $scope.student;
return studentObject.firstName + " " + studentObject.lastName;
}
};
});
</script>
<body>
<div ng-app = "mainApp">
<div id="dv1" ng-controller = "studentController1">
Enter first name: <input type = "text" ng-model = "student.firstName"><br/><br/> Enter last name: <input type = "text" ng-model = "student.lastName"><br/>
<br/>
You are entering: {{student.fullName()}}
</div>
<div id="dv2" ng-controller = "studentController2">
<table border = "0">
<tr>
<td>Enter first name:</td>
<td><input type = "text" ng-model = "student.firstName"></td>
</tr>
<tr>
<td>Enter last name: </td>
<td>
<input type = "text" ng-model = "student.lastName">
</td>
</tr>
<tr>
<td>Name: </td>
<td>{{student.fullName()}}</td>
</tr>
<tr>
<td>Subject:</td>
<td>
<table>
<tr>
<th>Name</th>.
<th>Marks</th>
</tr>
<tr ng-repeat = "subject in student.subjects">
<td>{{ subject.name }}</td>
<td>{{ subject.marks }}</td>
</tr>
</table>
</td>
</tr>
</table>
</div>
</div>
</body>
</html>
Check if file exists and whether it contains a specific string
You should use the grep
-q
flag for quiet output. See the man pages below:
man grep output :
General Output Control
-q, --quiet, --silent
Quiet; do not write anything to standard output. Exit immediately with zero status
if any match is found, even if an error was detected. Also see the -s or
--no-messages option. (-q is specified by POSIX.)
This KornShell (ksh) script demos the grep
quiet output and is a solution to your question.
grepUtil.ksh :
#!/bin/ksh
#Initialize Variables
file=poet.txt
var=""
dir=tempDir
dirPath="/"${dir}"/"
searchString="poet"
#Function to initialize variables
initialize(){
echo "Entering initialize"
echo "Exiting initialize"
}
#Function to create File with Input
#Params: 1}Directory 2}File 3}String to write to FileName
createFileWithInput(){
echo "Entering createFileWithInput"
orgDirectory=${PWD}
cd ${1}
> ${2}
print ${3} >> ${2}
cd ${orgDirectory}
echo "Exiting createFileWithInput"
}
#Function to create File with Input
#Params: 1}directoryName
createDir(){
echo "Entering createDir"
mkdir -p ${1}
echo "Exiting createDir"
}
#Params: 1}FileName
readLine(){
echo "Entering readLine"
file=${1}
while read line
do
#assign last line to var
var="$line"
done <"$file"
echo "Exiting readLine"
}
#Check if file exists
#Params: 1}File
doesFileExit(){
echo "Entering doesFileExit"
orgDirectory=${PWD}
cd ${PWD}${dirPath}
#echo ${PWD}
if [[ -e "${1}" ]]; then
echo "${1} exists"
else
echo "${1} does not exist"
fi
cd ${orgDirectory}
echo "Exiting doesFileExit"
}
#Check if file contains a string quietly
#Params: 1}Directory Path 2}File 3}String to seach for in File
doesFileContainStringQuiet(){
echo "Entering doesFileContainStringQuiet"
orgDirectory=${PWD}
cd ${PWD}${1}
#echo ${PWD}
grep -q ${3} ${2}
if [ ${?} -eq 0 ];then
echo "${3} found in ${2}"
else
echo "${3} not found in ${2}"
fi
cd ${orgDirectory}
echo "Exiting doesFileContainStringQuiet"
}
#Check if file contains a string with output
#Params: 1}Directory Path 2}File 3}String to seach for in File
doesFileContainString(){
echo "Entering doesFileContainString"
orgDirectory=${PWD}
cd ${PWD}${1}
#echo ${PWD}
grep ${3} ${2}
if [ ${?} -eq 0 ];then
echo "${3} found in ${2}"
else
echo "${3} not found in ${2}"
fi
cd ${orgDirectory}
echo "Exiting doesFileContainString"
}
#-----------
#---Main----
#-----------
echo "Starting: ${PWD}/${0} with Input Parameters: {1: ${1} {2: ${2} {3: ${3}"
#initialize #function call#
createDir ${dir} #function call#
createFileWithInput ${dir} ${file} ${searchString} #function call#
doesFileExit ${file} #function call#
if [ ${?} -eq 0 ];then
doesFileContainStringQuiet ${dirPath} ${file} ${searchString} #function call#
doesFileContainString ${dirPath} ${file} ${searchString} #function call#
fi
echo "Exiting: ${PWD}/${0}"
grepUtil.ksh Output :
user@foo /tmp
$ ksh grepUtil.ksh
Starting: /tmp/grepUtil.ksh with Input Parameters: {1: {2: {3:
Entering createDir
Exiting createDir
Entering createFileWithInput
Exiting createFileWithInput
Entering doesFileExit
poet.txt exists
Exiting doesFileExit
Entering doesFileContainStringQuiet
poet found in poet.txt
Exiting doesFileContainStringQuiet
Entering doesFileContainString
poet
poet found in poet.txt
Exiting doesFileContainString
Exiting: /tmp/grepUtil.ksh
Detect Route Change with react-router
import React from 'react';
import { BrowserRouter as Router, Switch, Route } from 'react-router-dom';
import Sidebar from './Sidebar';
import Chat from './Chat';
<Router>
<Sidebar />
<Switch>
<Route path="/rooms/:roomId" component={Chat}>
</Route>
</Switch>
</Router>
import { useHistory } from 'react-router-dom';
function SidebarChat(props) {
**const history = useHistory();**
var openChat = function (id) {
**//To navigate**
history.push("/rooms/" + id);
}
}
**//To Detect the navigation change or param change**
import { useParams } from 'react-router-dom';
function Chat(props) {
var { roomId } = useParams();
var roomId = props.match.params.roomId;
useEffect(() => {
//Detect the paramter change
}, [roomId])
useEffect(() => {
//Detect the location/url change
}, [location])
}
Send value of submit button when form gets posted
The button names are not submit, so the php $_POST['submit']
value is not set. As in isset($_POST['submit'])
evaluates to false.
<html>
<form action="" method="post">
<input type="hidden" name="action" value="submit" />
<select name="name">
<option>John</option>
<option>Henry</option>
<select>
<!--
make sure all html elements that have an ID are unique and name the buttons submit
-->
<input id="tea-submit" type="submit" name="submit" value="Tea">
<input id="coffee-submit" type="submit" name="submit" value="Coffee">
</form>
</html>
<?php
if (isset($_POST['action'])) {
echo '<br />The ' . $_POST['submit'] . ' submit button was pressed<br />';
}
?>
What's the difference between 'r+' and 'a+' when open file in python?
If you have used them in C
, then they are almost same as were in C.
From the manpage of fopen()
function : -
r+
: - Open for reading and writing. The stream is positioned at
the
beginning of the file.
a+
: - Open for reading and writing. The file is created if it does
not
exist. The stream is positioned at the end of the file. Subse-
quent writes to the file will always end up at the then current
end of file, irrespective of any intervening fseek(3) or similar.
How to check whether Kafka Server is running?
Paul's answer is very good and it is actually how Kafka & Zk work together from a broker point of view.
I would say that another easy option to check if a Kafka server is running is to create a simple KafkaConsumer pointing to the cluste and try some action, for example, listTopics(). If kafka server is not running, you will get a TimeoutException and then you can use a try-catch
sentence.
def validateKafkaConnection(kafkaParams : mutable.Map[String, Object]) : Unit = {
val props = new Properties()
props.put("bootstrap.servers", kafkaParams.get("bootstrap.servers").get.toString)
props.put("group.id", kafkaParams.get("group.id").get.toString)
props.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer")
props.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer")
val simpleConsumer = new KafkaConsumer[String, String](props)
simpleConsumer.listTopics()
}
How can I replace every occurrence of a String in a file with PowerShell?
If You Need to Replace Strings in Multiple Files:
It should be noted that the different methods posted here can be wildly different with regard to the time it takes to complete. For me, I regularly have large numbers of small files. To test what is most performant, I extracted 5.52 GB (5,933,604,999 bytes) of XML in 40,693 separate files and ran through three of the answers I found here:
## 5.52 GB (5,933,604,999 bytes) of XML files (40,693 files)
#### Test 1 - Plain Replace
$start = get-date
$xmls = (Get-ChildItem -Path "I:\TestseT\All_XML" -Recurse -Filter *.xml).FullName
foreach ($xml in $xmls)
{
(Get-Content $xml).replace("'", " ") | Set-Content $xml
}
$end = get-date
NEW-TIMESPAN –Start $Start –End $End
<#
TotalMinutes: 103.725113128333
#>
#### Test 2 - Replace with -Raw
$start = get-date
$xmls = (Get-ChildItem -Path "I:\TestseT\All_XML" -Recurse -Filter *.xml).FullName
foreach ($xml in $xmls)
{
(Get-Content $xml -Raw).replace("'", " ") | Set-Content $xml
}
$end = get-date
NEW-TIMESPAN –Start $Start –End $End
<#
TotalMinutes: 10.1600227983333
#>
#### Test 3 - .NET, System.IO
$start = get-date
$xmls = (Get-ChildItem -Path "I:\TestseT\All_XML" -Recurse -Filter *.xml).FullName
foreach ($xml in $xmls)
{
$txt = [System.IO.File]::ReadAllText("$xml").Replace("'"," ")
[System.IO.File]::WriteAllText("$xml", $txt)
}
$end = get-date
NEW-TIMESPAN –Start $Start –End $End
<#
TotalMinutes: 5.83619516833333
#>
How do I send a file in Android from a mobile device to server using http?
Easy, you can use a Post request and submit your file as binary (byte array).
String url = "http://yourserver";
File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath(),
"yourfile");
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
InputStreamEntity reqEntity = new InputStreamEntity(
new FileInputStream(file), -1);
reqEntity.setContentType("binary/octet-stream");
reqEntity.setChunked(true); // Send in multiple parts if needed
httppost.setEntity(reqEntity);
HttpResponse response = httpclient.execute(httppost);
//Do something with response...
} catch (Exception e) {
// show error
}
Show/hide forms using buttons and JavaScript
Use the following code fragment to hide the form on button click.
document.getElementById("your form id").style.display="none";
And the following code to display it:
document.getElementById("your form id").style.display="block";
Or you can use the same function for both purposes:
function asd(a)
{
if(a==1)
document.getElementById("asd").style.display="none";
else
document.getElementById("asd").style.display="block";
}
And the HTML:
<form id="asd">form </form>
<button onclick="asd(1)">Hide</button>
<button onclick="asd(2)">Show</button>
How to close a Java Swing application from the code
I guess a EXIT_ON_CLOSE
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
before System.exit(0)
is better since you can write a Window Listener to make some cleaning operations before actually leaving the app.
That window listener allows you to defined:
public void windowClosing(WindowEvent e) {
displayMessage("WindowListener method called: windowClosing.");
//A pause so user can see the message before
//the window actually closes.
ActionListener task = new ActionListener() {
boolean alreadyDisposed = false;
public void actionPerformed(ActionEvent e) {
if (frame.isDisplayable()) {
alreadyDisposed = true;
frame.dispose();
}
}
};
Timer timer = new Timer(500, task); //fire every half second
timer.setInitialDelay(2000); //first delay 2 seconds
timer.setRepeats(false);
timer.start();
}
public void windowClosed(WindowEvent e) {
//This will only be seen on standard output.
displayMessage("WindowListener method called: windowClosed.");
}
Add missing dates to pandas dataframe
A quicker workaround is to use .asfreq()
. This doesn't require creation of a new index to call within .reindex()
.
# "broken" (staggered) dates
dates = pd.Index([pd.Timestamp('2012-05-01'),
pd.Timestamp('2012-05-04'),
pd.Timestamp('2012-05-06')])
s = pd.Series([1, 2, 3], dates)
print(s.asfreq('D'))
2012-05-01 1.0
2012-05-02 NaN
2012-05-03 NaN
2012-05-04 2.0
2012-05-05 NaN
2012-05-06 3.0
Freq: D, dtype: float64
How do I create HTML table using jQuery dynamically?
I understand you want to create stuff dynamically. That does not mean you have to actually construct DOM elements to do it. You can just make use of html
to achieve what you want .
Look at the code below :
HTML:
<table border="0" cellpadding="0" width="100%" id='providersFormElementsTable'></table>
JS :
createFormElement("Nickname","nickname")
function createFormElement(labelText, id) {
$("#providersFormElementsTable").html("<tr><td>Nickname</td><td><input type='text' id='"+id+"' name='nickname'></td><lable id='"+labelText+"'></lable></td></tr>");
$('#providersFormElementsTable').append('<br />');
}
This one does what you want dynamically, it just needs the id and labelText to make it work, which actually must be the only dynamic variables as only they will be changing. Your DOM structure will always remain the same .
WORKING DEMO:
Moreover, when you use the process you mentioned in your post you get only [object Object]
. That is because when you call createProviderFormFields
, it is a function call and hence it's returning an object for you. You will not be seeing the text box as it needs to be added . For that you need to strip individual content form the object
, then construct the html from it.
It's much easier to construct just the html and change the id
s of the label and input according to your needs.
Vuejs and Vue.set(), update array
VueJS can't pickup your changes to the state if you manipulate arrays like this.
As explained in Common Beginner Gotchas, you should use array methods like push, splice or whatever and never modify the indexes like this a[2] = 2
nor the .length property of an array.
_x000D_
_x000D_
new Vue({_x000D_
el: '#app',_x000D_
data: {_x000D_
f: 'DD-MM-YYYY',_x000D_
items: [_x000D_
"10-03-2017",_x000D_
"12-03-2017"_x000D_
]_x000D_
},_x000D_
methods: {_x000D_
_x000D_
cha: function(index, item, what, count) {_x000D_
console.log(item + " index > " + index);_x000D_
val = moment(this.items[index], this.f).add(count, what).format(this.f);_x000D_
_x000D_
this.items.$set(index, val)_x000D_
console.log("arr length: " + this.items.length);_x000D_
}_x000D_
}_x000D_
})
_x000D_
ul {_x000D_
list-style-type: none;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/1.0.11/vue.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.6/moment.min.js"></script>_x000D_
<div id="app">_x000D_
<ul>_x000D_
<li v-for="(index, item) in items">_x000D_
<br><br>_x000D_
<button v-on:click="cha(index, item, 'day', -1)">_x000D_
- day</button> {{ item }}_x000D_
<button v-on:click="cha(index, item, 'day', 1)">_x000D_
+ day</button>_x000D_
<br><br>_x000D_
</li>_x000D_
</ul>_x000D_
</div>
_x000D_
_x000D_
_x000D_
Rotate label text in seaborn factorplot
Aman is correct that you can use normal matplotlib commands, but this is also built into the FacetGrid
:
import seaborn as sns
planets = sns.load_dataset("planets")
g = sns.factorplot("year", data=planets, aspect=1.5, kind="count", color="b")
g.set_xticklabels(rotation=30)
There are some comments and another answer claiming this "doesn't work", however, anyone can run the code as written here and see that it does work. The other answer does not provide a reproducible example of what isn't working, making it very difficult to address, but my guess is that people are trying to apply this solution to the output of functions that return an Axes
object instead of a Facet Grid
. These are different things, and the Axes.set_xticklabels()
method does indeed require a list of labels and cannot simply change the properties of the existing labels on the Axes
. The lesson is that it's important to pay attention to what kind of objects you are working with.
How do I set log4j level on the command line?
Based on Thorbjørn Ravn Andersens suggestion I wrote some code that makes this work
Add the following early in the main method and it is now possible to set the log level from the comand line. This have been tested in a project of mine but I'm new to log4j and might have made some mistake. If so please correct me.
Logger.getRootLogger().setLevel(Level.WARN);
HashMap<String,Level> logLevels=new HashMap<String,Level>();
logLevels.put("ALL",Level.ALL);
logLevels.put("TRACE",Level.TRACE);
logLevels.put("DEBUG",Level.DEBUG);
logLevels.put("INFO",Level.INFO);
logLevels.put("WARN",Level.WARN);
logLevels.put("ERROR",Level.ERROR);
logLevels.put("FATAL",Level.FATAL);
logLevels.put("OFF",Level.OFF);
for(String name:System.getProperties().stringPropertyNames()){
String logger="log4j.logger.";
if(name.startsWith(logger)){
String loggerName=name.substring(logger.length());
String loggerValue=System.getProperty(name);
if(logLevels.containsKey(loggerValue))
Logger.getLogger(loggerName).setLevel(logLevels.get(loggerValue));
else
Logger.getRootLogger().warn("unknown log4j logg level on comand line: "+loggerValue);
}
}
Android read text raw resource file
Here is a simple method to read the text file from the raw folder:
public static String readTextFile(Context context,@RawRes int id){
InputStream inputStream = context.getResources().openRawResource(id);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
byte buffer[] = new byte[1024];
int size;
try {
while ((size = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, size);
}
outputStream.close();
inputStream.close();
} catch (IOException e) {
}
return outputStream.toString();
}
How to start and stop android service from a adb shell?
For anyone still confused about how to define the service name parameter, the forward slash goes immediately after the application package name in the fully qualified class name.
So given an application package name of: app.package.name
And a full path to the service of: app.package.name.example.package.path.MyServiceClass
Then the command would look like this:
adb shell am startservice app.package.name/.example.package.path.MyServiceClass
How to make an anchor tag refer to nothing?
I encountered this issue on a WordPress site. The headers on dropdown menus always had the attribute href=""
and the header plugin being used only allowed standard urls. The easiest solution there was just to run this code in the footer:
jQuery('[href=""]').click(function(e){
e.preventDefault();
});
This will prevent blank anchors from doing anything.
Lua - Current time in milliseconds
I made a suitable solution for lua on Windows. I basically did what Kevlar suggested, but with a shared library rather than a DLL. This has been tested using cygwin.
I wrote some lua compatible C code, compiled it to a shared library (.so file via gcc in cygwin), and then loaded it up in lua using package.cpath and require" ". Wrote an adapter script for convenience. Here is all of the source:
first the C code, HighResTimer.c
////////////////////////////////////////////////////////////////
//HighResTimer.c by Cody Duncan
//
//compile with: gcc -o Timer.so -shared HighResTimer.c -llua5.1
//compiled in cygwin after installing lua (cant remember if I
// installed via setup or if I downloaded and compiled lua,
// probably the former)
////////////////////////////////////////////////////////////////
#include <windows.h>
typedef unsigned __int64 u64;
double mNanoSecondsPerCount;
#include "lua.h"
#include "lualib.h"
#include "lauxlib.h"
int prevInit = 0;
int currInit = 0;
u64 prevTime = 0;
u64 currTime = 0;
u64 FrequencyCountPerSec;
LARGE_INTEGER frequencyTemp;
static int readHiResTimerFrequency(lua_State *L)
{
QueryPerformanceFrequency(&frequencyTemp);
FrequencyCountPerSec = frequencyTemp.QuadPart;
lua_pushnumber(L, frequencyTemp.QuadPart);
return 1;
}
LARGE_INTEGER timerTemp;
static int storeTime(lua_State *L)
{
QueryPerformanceCounter(&timerTemp);
if(!prevInit)
{
prevInit = 1;
prevTime = timerTemp.QuadPart;
}
else if (!currInit)
{
currInit = 1;
currTime = timerTemp.QuadPart;
}
else
{
prevTime = currTime;
currTime = timerTemp.QuadPart;
}
lua_pushnumber(L, timerTemp.QuadPart);
return 1;
}
static int getNanoElapsed(lua_State *L)
{
double mNanoSecondsPerCount = 1000000000/(double)FrequencyCountPerSec;
double elapsedNano = (currTime - prevTime)*mNanoSecondsPerCount;
lua_pushnumber(L, elapsedNano);
return 1;
}
int luaopen_HighResolutionTimer (lua_State *L) {
static const luaL_reg mylib [] =
{
{"readHiResTimerFrequency", readHiResTimerFrequency},
{"storeTime", storeTime},
{"getNanoElapsed", getNanoElapsed},
{NULL, NULL} /* sentinel */
};
luaL_register(L,"timer",mylib);
return 1;
}
--
--
Now lets get it loaded up in a lua script, HighResTimer.lua .
Note: I compiled the HighResTimer.c to a shared library, Timer.so
#!/bin/lua
------------------------------------
---HighResTimer.lua by Cody Duncan
---Wraps the High Resolution Timer Functions in
--- Timer.so
------------------------------------
package.cpath = "./Timer.so" --assuming Timer.so is in the same directory
require "HighResolutionTimer" --load up the module
timer.readHiResTimerFrequency(); --stores the tickFrequency
--call this before code that is being measured for execution time
function start()
timer.storeTime();
end
--call this after code that is being measured for execution time
function stop()
timer.storeTime();
end
--once the prior two functions have been called, call this to get the
--time elapsed between them in nanoseconds
function getNanosElapsed()
return timer.getNanoElapsed();
end
--
--
and Finally, utilize the timer, TimerTest.lua .
#!/bin/lua
------------------------------------
---TimerTest.lua by Cody Duncan
---
---HighResTimer.lua and Timer.so must
--- be in the same directory as
--- this script.
------------------------------------
require './HighResTimer'
start();
for i = 0, 3000000 do io.write("") end --do essentially nothing 3million times.
stop();
--divide nanoseconds by 1 million to get milliseconds
executionTime = getNanosElapsed()/1000000;
io.write("execution time: ", executionTime, "ms\n");
Note: Any comments were written after pasting the source code into the post editor, so technically this is untested, but hopefully the comments didn't befuddle anything. I will be sure to come back and provide a fix if it does.
Force an SVN checkout command to overwrite current files
I did not have 1.5 available to me, because I am not in control of the computer. The file that was causing me a problem happened to be a .jar file in the lib directory. Here is what I did to solve the problem:
rm -rf lib
svn up
This builds on Ned's answer. That is: I just removed the sub directory that was causing me a problem rather than the entire repository.
Unsigned values in C
In the hexadecimal it can't get a negative value. So it shows it like ffffffff.
The advantage to using the unsigned version (when you know the values contained will be non-negative) is that sometimes the computer will spot errors for you (the program will "crash" when a negative value is assigned to the variable).
Postman: sending nested JSON object
In the Params I have added model.Email and model.Password, work for me well. Thanks for the question. I tried the same thing in headers did not work. But it worked on Body with form-data and x-www-form-urlencoded.
Postman version 6.4.4
RecyclerView - How to smooth scroll to top of item on a certain position?
RecyclerView
is designed to be extensible, so there is no need to subclass the LayoutManager
(as droidev suggested) just to perform the scrolling.
Instead, just create a SmoothScroller
with the preference SNAP_TO_START
:
RecyclerView.SmoothScroller smoothScroller = new LinearSmoothScroller(context) {
@Override protected int getVerticalSnapPreference() {
return LinearSmoothScroller.SNAP_TO_START;
}
};
Now you set the position where you want to scroll to:
smoothScroller.setTargetPosition(position);
and pass that SmoothScroller to the LayoutManager:
layoutManager.startSmoothScroll(smoothScroller);
How can I run a PHP script inside a HTML file?
I'm not sure if this is what you wanted, but this is a very hackish way to include php. What you do is you put the php you want to run in another file, and then you include that file in an image. For example:
RunFromHTML.php
<?php
$file = fopen("file.txt", "w");
//This will create a file called file.txt,
//provided that it has write access to your filesystem
fwrite($file, "Hello World!");
//This will write "Hello World!" into file.txt
fclose($file);
//Always remember to close your files!
?>
RunPhp.html
<html>
<!--head should be here, but isn't for demonstration's sake-->
<body>
<img style="display: none;" src="RunFromHTML.php">
<!--This will run RunFromHTML.php-->
</body>
</html>
Now, after visiting RunPhp.html, you should find a file called file.txt in the same directory that you created the above two files, and the file should contain "Hello World!" inside of it.
How to change color of Android ListView separator line?
XML version for @Asher Aslan cool effect.
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
<gradient
android:angle="180"
android:startColor="#00000000"
android:centerColor="#FFFF0000"
android:endColor="#00000000"/>
</shape>
Name for that shape as: list_driver.xml under drawable folder
<ListView
android:id="@+id/category_list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:divider="@drawable/list_driver"
android:dividerHeight="5sp" />
Insert data into table with result from another select query
Below is an example of such a query:
INSERT INTO [93275].[93276].[93277].[93278] ( [Mobile Number], [Mobile Series], [Full Name], [Full Address], [Active Date], company ) IN 'I:\For Test\90-Mobile Series.accdb
SELECT [1].[Mobile Number], [1].[Mobile Series], [1].[Full Name], [1].[Full Address], [1].[Active Date], [1].[Company Name]
FROM 1
WHERE ((([1].[Mobile Series])="93275" Or ([1].[Mobile Series])="93276")) OR ((([1].[Mobile Series])="93277"));OR ((([1].[Mobile Series])="93278"));
Converting Symbols, Accent Letters to English Alphabet
If the need is to convert "òéisöç->oeisoc", you can use this a starting point :
public class AsciiUtils {
private static final String PLAIN_ASCII =
"AaEeIiOoUu" // grave
+ "AaEeIiOoUuYy" // acute
+ "AaEeIiOoUuYy" // circumflex
+ "AaOoNn" // tilde
+ "AaEeIiOoUuYy" // umlaut
+ "Aa" // ring
+ "Cc" // cedilla
+ "OoUu" // double acute
;
private static final String UNICODE =
"\u00C0\u00E0\u00C8\u00E8\u00CC\u00EC\u00D2\u00F2\u00D9\u00F9"
+ "\u00C1\u00E1\u00C9\u00E9\u00CD\u00ED\u00D3\u00F3\u00DA\u00FA\u00DD\u00FD"
+ "\u00C2\u00E2\u00CA\u00EA\u00CE\u00EE\u00D4\u00F4\u00DB\u00FB\u0176\u0177"
+ "\u00C3\u00E3\u00D5\u00F5\u00D1\u00F1"
+ "\u00C4\u00E4\u00CB\u00EB\u00CF\u00EF\u00D6\u00F6\u00DC\u00FC\u0178\u00FF"
+ "\u00C5\u00E5"
+ "\u00C7\u00E7"
+ "\u0150\u0151\u0170\u0171"
;
// private constructor, can't be instanciated!
private AsciiUtils() { }
// remove accentued from a string and replace with ascii equivalent
public static String convertNonAscii(String s) {
if (s == null) return null;
StringBuilder sb = new StringBuilder();
int n = s.length();
for (int i = 0; i < n; i++) {
char c = s.charAt(i);
int pos = UNICODE.indexOf(c);
if (pos > -1){
sb.append(PLAIN_ASCII.charAt(pos));
}
else {
sb.append(c);
}
}
return sb.toString();
}
public static void main(String args[]) {
String s =
"The result : È,É,Ê,Ë,Û,Ù,Ï,Î,À,Â,Ô,è,é,ê,ë,û,ù,ï,î,à,â,ô,ç";
System.out.println(AsciiUtils.convertNonAscii(s));
// output :
// The result : E,E,E,E,U,U,I,I,A,A,O,e,e,e,e,u,u,i,i,a,a,o,c
}
}
The JDK 1.6 provides the java.text.Normalizer class that can be used for this task.
See an example here
How to view/delete local storage in Firefox?
As 'localStorage' is just another object, you can: create, view, and edit it in the 'Console'. Simply enter 'localStorage' as a command and press enter, it'll display a string containing the key-value pairs of localStorage (Tip: Click on that string for formatted output, i.e. to display each key-value pair in each line).
how to prevent this error : Warning: mysql_fetch_assoc() expects parameter 1 to be resource, boolean given in ... on line 11
You don't need to prevent this error message!
Error messages are your friends!
Without error message you'd never know what is happened.
It's all right! Any working code supposed to throw out error messages.
Though error messages needs proper handling.
Usually you don't have to to take any special actions to avoid such an error messages. Just leave your code intact.
But if you don't want this error message to be shown to the user, just turn it off. Not error message itself but daislaying it to the user.
ini_set('display_errors',0);
ini_set('log_errors',1);
or even better at .htaccess/php.ini level
And user will never see any error messages. While you will be able still see it in the error log.
Please note that error_reporting should be at max in both cases.
To prevent this message you can check mysql_query result and run fetch_assoc only on success.
But usually nobody uses it as it may require too many nested if's.
But there can be solution too - exceptions!
But it is still not necessary. You can leave your code as is, because it is supposed to work without errors when done.
Using return
is another method to avoid nested error messages. Here is a snippet from my database handling function:
$res = mysql_query($query);
if (!$res) {
trigger_error("dbget: ".mysql_error()." in ".$query);
return false;
}
if (!mysql_num_rows($res)) return NULL;
//fetching goes here
//if there was no errors only
How do I get the day of week given a date?
datetime library sometimes gives errors with strptime() so I switched to dateutil library. Here's an example of how you can use it :
from dateutil import parser
parser.parse('January 11, 2010').strftime("%a")
The output that you get from this is 'Mon'
. If you want the output as 'Monday', use the following :
parser.parse('January 11, 2010').strftime("%A")
This worked for me pretty quickly. I was having problems while using the datetime library because I wanted to store the weekday name instead of weekday number and the format from using the datetime library was causing problems. If you're not having problems with this, great! If you are, you cand efinitely go for this as it has a simpler syntax as well. Hope this helps.
How to generate UML diagrams (especially sequence diagrams) from Java code?
EDIT:
If you're a designer then Papyrus is your best choice it's very advanced and full of features, but if you just want to sketch out some UML diagrams and easy installation then ObjectAid is pretty cool and it doesn't require any plugins I just installed it over Eclipse-Java EE and works great !.
UPDATE Oct 11th, 2013
My original post was in June 2012 a lot of things have changed many tools has grown and others didn't. Since I'm going back to do some modeling and also getting some replies to the post I decided to install papyrus again and will investigate other possible UML modeling solutions again. UML generation (with synchronization feature) is really important not to software designer but to the average developer.
I wish papyrus had straightforward way to Reverse Engineer classes into UML class diagram and It would be super cool if that reverse engineering had a synchronization feature, but unfortunately papyrus project is full of features and I think developers there have already much at hand since also many actions you do over papyrus might not give you any response and just nothing happens but that's out of this question scope anyway.
The Answer (Oct 11th, 2013)
Tools
- Download Papyrus
- Go to Help -> Install New Software...
- In the Work with: drop-down, select --All Available Sites--
- In the filter, type in Papyrus
- After installation finishes restart Eclipse
- Repeat steps 1-3 and this time, install Modisco
Steps
- In your java project (assume it's called MyProject) create a folder e.g UML
- Right click over the project name -> Discovery -> Discoverer -> Discover Java and inventory model from java project, a file called MyProject_kdm.xmi will be generated.
- Right click project name file --> new --> papyrus model -> and call it MyProject.
- Move the three generated files MyProject.di , MyProject.notation, MyProject.uml to the UML folder
Right click on MyProject_kdm.xmi -> Discovery -> Discoverer -> Discover UML model from KDM code again you'll get a property dialog set the serialization prop to TRUE to generate a file named MyProject.uml
Move generated MyProject.uml which was generated at root, to UML folder, Eclipse will ask you If you wanted to replace it click yes. What we did in here was that we replaced an empty model with a generated one.
ALT+W -> show view -> papyrus -> model explorer
In that view, you'll find your classes like in the picture
In the view Right click root model -> New diagram
Then start grabbing classes to the diagram from the view
Some features
To show the class elements (variables, functions etc) Right click on any class -> Filters -> show/hide contents Voila !!
You can have default friendly color settings from Window -> pereferences -> papyrus -> class diagram
one very important setting is Arrange when you drop the classes they get a cramped right click on any empty space at a class diagram and click Arrange All
Arrows in the model explorer view can be grabbed to the diagram to show generalization, realization etc
After all of that your settings will show diagrams like
Synchronization isn't available as far as I know you'll need to manually import any new classes.
That's all, And don't buy commercial products unless you really need it, papyrus is actually great and sophisticated instead donate or something.
Disclaimer: I've no relation to the papyrus people, in fact, I didn't like papyrus at first until I did lots of research and experienced it with some patience. And will get back to this post again when I try other free tools.
Replace multiple strings with multiple other strings
Just in case someone is wondering why the original poster's solution is not working:
var str = "I have a cat, a dog, and a goat.";
str = str.replace(/cat/gi, "dog");
// now str = "I have a dog, a dog, and a goat."
str = str.replace(/dog/gi, "goat");
// now str = "I have a goat, a goat, and a goat."
str = str.replace(/goat/gi, "cat");
// now str = "I have a cat, a cat, and a cat."
Append to the end of a Char array in C++
If you are not allowed to use C++'s string class (which is terrible teaching C++ imho), a raw, safe array version would look something like this.
#include <cstring>
#include <iostream>
int main()
{
char array1[] ="The dog jumps ";
char array2[] = "over the log";
char * newArray = new char[std::strlen(array1)+std::strlen(array2)+1];
std::strcpy(newArray,array1);
std::strcat(newArray,array2);
std::cout << newArray << std::endl;
delete [] newArray;
return 0;
}
This assures you have enough space in the array you're doing the concatenation to, without assuming some predefined MAX_SIZE
. The only requirement is that your strings are null-terminated, which is usually the case unless you're doing some weird fixed-size string hacking.
Edit, a safe version with the "enough buffer space" assumption:
#include <cstring>
#include <iostream>
int main()
{
const unsigned BUFFER_SIZE = 50;
char array1[BUFFER_SIZE];
std::strncpy(array1, "The dog jumps ", BUFFER_SIZE-1); //-1 for null-termination
char array2[] = "over the log";
std::strncat(array1,array2,BUFFER_SIZE-strlen(array1)-1); //-1 for null-termination
std::cout << array1 << std::endl;
return 0;
}
Must JDBC Resultsets and Statements be closed separately although the Connection is closed afterwards?
From the javadocs:
When a Statement
object is closed, its
current ResultSet
object, if one
exists, is also closed.
However, the javadocs are not very clear on whether the Statement
and ResultSet
are closed when you close the underlying Connection
. They simply state that closing a Connection:
Releases this Connection
object's
database and JDBC resources
immediately instead of waiting for
them to be automatically released.
In my opinion, always explicitly close ResultSets
, Statements
and Connections
when you are finished with them as the implementation of close
could vary between database drivers.
You can save yourself a lot of boiler-plate code by using methods such as closeQuietly
in DBUtils from Apache.
JQuery create new select option
How about
$('#county').append(
$('<option />')
.text('Select a city / town in Sweden')
.val(''),
$('<option />')
.text('Melbourne')
.val('Melbourne')
);
How to change DataTable columns order
Try to use the DataColumn.SetOrdinal method. For example:
dataTable.Columns["Qty"].SetOrdinal(0);
dataTable.Columns["Unit"].SetOrdinal(1);
UPDATE: This answer received much more attention than I expected. To avoid confusion and make it easier to use I decided to create an extension method for column ordering in DataTable:
Extension method:
public static class DataTableExtensions
{
public static void SetColumnsOrder(this DataTable table, params String[] columnNames)
{
int columnIndex = 0;
foreach(var columnName in columnNames)
{
table.Columns[columnName].SetOrdinal(columnIndex);
columnIndex++;
}
}
}
Usage:
table.SetColumnsOrder("Qty", "Unit", "Id");
or
table.SetColumnsOrder(new string[]{"Qty", "Unit", "Id"});
Is it possible to send a variable number of arguments to a JavaScript function?
For those who were redirected here from Passing variable number of arguments from one function to another (which should not be marked as a duplicate of this question):
If you're trying to pass a variable number of arguments from one function to another, since JavaScript 1.8.5 you can simply call apply()
on the second function and pass in the arguments
parameter:
var caller = function()
{
callee.apply( null, arguments );
}
var callee = function()
{
alert( arguments.length );
}
caller( "Hello", "World!", 88 ); // Shows "3".
Note: The first argument is the this
parameter to use. Passing null
will call the function from the global context, i.e. as a global function instead of the method of some object.
According to this document, the ECMAScript 5 specification redefined the apply()
method to take any "generic array-like object", instead of strictly an Array. Thus, you can directly pass the arguments
list into the second function.
Tested in Chrome 28.0, Safari 6.0.5, and IE 10. Try it out with this JSFiddle.
Is the size of C "int" 2 bytes or 4 bytes?
This depends on implementation, but usually on x86 and other popular architectures like ARM int
s take 4 bytes. You can always check at compile time using sizeof(int)
or whatever other type you want to check.
If you want to make sure you use a type of a specific size, use the types in <stdint.h>
What is the meaning of 'No bundle URL present' in react-native?
I've tried all solutions below, but nothing work:
sudo xcodebuild -license
or
- Remove the build folder with
rm -r build
and run react-native run-ios
or
npm start
and run react-native run-ios
- Add
NSAppTransportSecurity
to `
I solved by do this:
- Open host file
sudo vi /private/etc/hosts
(if you use VSCode, use this sudo code /private/etc/hosts
)
- Add three line if it's not exist
127.0.0.1 localhost
255.255.255.255 broadcasthost
::1 localhost
- Run
react-native run-ios
again.
ggplot2 line chart gives "geom_path: Each group consist of only one observation. Do you need to adjust the group aesthetic?"
Start up R in a fresh session and paste this in:
library(ggplot2)
df <- structure(list(year = c(1, 2, 3, 4), pollution = structure(c(346.82,
134.308821199349, 130.430379885892, 88.275457392443), .Dim = 4L, .Dimnames = list(
c("1999", "2002", "2005", "2008")))), .Names = c("year",
"pollution"), row.names = c(NA, -4L), class = "data.frame")
df[] <- lapply(df, as.numeric) # make all columns numeric
ggplot(df, aes(year, pollution)) +
geom_point() +
geom_line() +
labs(x = "Year",
y = "Particulate matter emissions (tons)",
title = "Motor vehicle emissions in Baltimore")
API vs. Webservice
API is code based integration while web service is message based integration with interoperable standards having a contract such as WSDL.
RequestDispatcher.forward() vs HttpServletResponse.sendRedirect()
requestDispatcher - forward() method
When we use the forward
method, the request is transferred to another resource within the same server for further processing.
In the case of forward
, the web container handles all processing internally and the client or browser is not involved.
When forward
is called on the requestDispatcher
object, we pass the request and response objects, so our old request object is present on the new resource which is going to process our request.
Visually, we are not able to see the forwarded address, it is transparent.
Using the forward()
method is faster than sendRedirect
.
When we redirect using forward, and we want to use the same data in a new resource, we can use request.setAttribute()
as we have a request object available.
SendRedirect
In case of sendRedirect
, the request is transferred to another resource, to a different domain, or to a
different server for further processing.
When you use sendRedirect
, the container transfers the request to the client or browser, so the URL given inside the sendRedirect
method is visible as a new request to the client.
In case of sendRedirect
call, the old request and response objects are lost because it’s treated as new request by the browser.
In the address bar, we are able to see the new redirected address. It’s not transparent.
sendRedirect
is slower because one extra round trip is required, because a completely new request is created and the old request object is lost. Two browser request are required.
But in sendRedirect
, if we want to use the same data for a new resource we have to store the data in session or pass along with the URL.
Which one is good?
Its depends upon the scenario for which method is more useful.
If you want control is transfer to new server or context, and it is treated as completely new task, then we go for sendRedirect
.
Generally, a forward should be used if the operation can be safely repeated upon a browser reload of the web page and will not affect the result.
Source
PHP reindex array?
This might not be the simplest answer as compared to using array_values().
Try this
$array = array( 0 => 'string1', 2 => 'string2', 4 => 'string3', 5 => 'string4');
$arrays =$array;
print_r($array);
$array=array();
$i=0;
foreach($arrays as $k => $item)
{
$array[$i]=$item;
unset($arrays[$k]);
$i++;
}
print_r($array);
Demo
How to fix: "HAX is not working and emulator runs in emulation mode"
The way I solved it is by setting the AVD memory limit and HAXM memory to be equal in size which is 1 GB = 1024 MB. The AVD cannot have higher memory limit than the HAXM.
1. Setting the HAXM memory to be 1024 M
The only way to change the HAXM memory is by installing it again. I did it using the terminal. Locate Hardware_Accelerated_Execution_Manager in your machine. Then change directory that folder to run the installation script.
cd ~/Library/Android/sdk/extras/intel/Hardware_Accelerated_Execution_Manager
-OR-
cd ~/Library/Developer/Xamarin/android-sdk-macosx/extras/intel/Hardware_Accelerated_Execution_Manager
May need to change permissions:
sudo chmod 755 "HAXM installation"
Then:
./HAXM\ installation -m 1024
-OR-
sudo ./"HAXM installation" -m 1024
2. Setting the virtual device the same size with HAXM memory limit
This works for me. Good luck!
How do I list all tables in all databases in SQL Server in a single result set?
declare @sql nvarchar(max);
set @sql = N'select cast(''master'' as sysname) as db_name, name collate Latin1_General_CI_AI, object_id, schema_id, cast(1 as int) as database_id from master.sys.tables ';
select @sql = @sql + N' union all select ' + quotename(name,'''')+ ', name collate Latin1_General_CI_AI, object_id, schema_id, ' + cast(database_id as nvarchar(10)) + N' from ' + quotename(name) + N'.sys.tables'
from sys.databases where database_id > 1
and state = 0
and user_access = 0;
exec sp_executesql @sql;
Saving excel worksheet to CSV files with filename+worksheet name using VB
I had a similar problem. Data in a worksheet I needed to save as a separate CSV file.
Here's my code behind a command button
Private Sub cmdSave()
Dim sFileName As String
Dim WB As Workbook
Application.DisplayAlerts = False
sFileName = "MyFileName.csv"
'Copy the contents of required sheet ready to paste into the new CSV
Sheets(1).Range("A1:T85").Copy 'Define your own range
'Open a new XLS workbook, save it as the file name
Set WB = Workbooks.Add
With WB
.Title = "MyTitle"
.Subject = "MySubject"
.Sheets(1).Select
ActiveSheet.Paste
.SaveAs "MyDirectory\" & sFileName, xlCSV
.Close
End With
Application.DisplayAlerts = True
End Sub
This works for me :-)
How to add Android Support Repository to Android Studio?
Found a solution.
1) Go to where your SDK is located that android studio/eclipse is using.
If you are using Android studio, go to extras\android\m2repository\com\android\support\
.
If you are using eclipse, go to \extras\android\support\
2) See what folders you have, for me I had gridlayout-v7, support-v4 and support-v13.
3) click into support-v4 and see what number the following folder is, mine was named 13.0
Since you are using "com.android.support:support-v4:18.0.+", change this to reflect what version you have, for example I have support-v4 so first part v4 stays the same. Since the next path is 13.0, change your 18.0 to:
"com.android.support:support-v4:13.0.+"
This worked for me, hope it helps!
Update:
I noticed I had android studio set up with the wrong SDK which is why originally had difficulty updating! The path should be C:\Users\Username\AppData\Local\Android\android-sdk\extras\
Also note, if your SDK is up to date, the code will be:
"com.android.support:support-v4:19.0.+"
How to specify the bottom border of a <tr>?
What I want to say here is like some kind of add-on on @Suciu Lucian's answer.
The weird situation I ran into is that when I apply the solution of @Suciu Lucian in my file, it works in Chrome but not in Safari (and did not try in Firefox). After I studied the guide of styling table border published by w3.org, I found something alternative:
table.myTable{
border-spacing: 0;
}
table.myTable td{
border-bottom:1px solid red;
}
Yes you have to style the td
instead of the tr
.
Enable UTF-8 encoding for JavaScript
I too had this issue, I would copy the whole piece of code and put in Notepad, before pasting in Notepad, make sure you save the file type as ALL files and save the doc as utf-8 format. then you can paste your code and run, It should work. ?????? obiviously means unreadable characters.
AttributeError: 'datetime' module has no attribute 'strptime'
I got the same problem and it is not the solution that you told. So I changed the "from datetime import datetime" to "import datetime". After that with
the help of "datetime.datetime" I can get the whole modules correctly. I guess this is the correct answer to that question.
putting datepicker() on dynamically created elements - JQuery/JQueryUI
You need to run the .datepicker();
again after you've dynamically created the other textbox elements.
I would recommend doing so in the callback method of the call that is adding the elements to the DOM.
So lets say you're using the JQuery Load method to pull the elements from a source and load them into the DOM, you would do something like this:
$('#id_of_div_youre_dynamically_adding_to').load('ajax/get_textbox', function() {
$(".datepicker_recurring_start" ).datepicker();
});