I use this class for Audio play. If your audio location is raw folder.
Call method for play:
new AudioPlayer().play(mContext, getResources().getIdentifier(alphabetItemList.get(mPosition)
.getDetail().get(0).getAudio(),"raw", getPackageName()));
AudioPlayer.java class:
public class AudioPlayer {
private MediaPlayer mMediaPlayer;
public void stop() {
if (mMediaPlayer != null) {
mMediaPlayer.release();
mMediaPlayer = null;
}
}
// mothod for raw folder (R.raw.fileName)
public void play(Context context, int rid){
stop();
mMediaPlayer = MediaPlayer.create(context, rid);
mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mediaPlayer) {
stop();
}
});
mMediaPlayer.start();
}
// mothod for other folder
public void play(Context context, String name) {
stop();
//mMediaPlayer = MediaPlayer.create(c, rid);
mMediaPlayer = MediaPlayer.create(context, Uri.parse("android.resource://"+ context.getPackageName()+"/your_file/"+name+".mp3"));
mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mediaPlayer) {
stop();
}
});
mMediaPlayer.start();
}
}
Android recommends that you call Environment.getExternalStorageDirectory.getPath()
instead of hardcoding /sdcard/
in path name. This returns the primary shared/external storage directory. So, if storage is emulated, this will return /storage/emulated/0
. If you explore the device storage with a file explorer, the said directory will be /mnt/sdcard
(confirmed on Xperia Z2 running Android 6).
Labeeb is right about why you need to set image using path if your resources are already laying inside the resource folder ,
This kind of path is needed only when your images are stored in SD-Card .
And try the below code to set Bitmap images from a file stored inside a SD-Card .
File imgFile = new File("/sdcard/Images/test_image.jpg");
if(imgFile.exists()){
Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
ImageView myImage = (ImageView) findViewById(R.id.imageviewTest);
myImage.setImageBitmap(myBitmap);
}
And include this permission in the manifest file:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
ivmage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE_ADD);
}
});`
You need an appropriate permission in manifest.xml
:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
out.flush()
check the out
is not null..
String file_path = Environment.getExternalStorageDirectory().getAbsolutePath() +
"/PhysicsSketchpad";
File dir = new File(file_path);
if(!dir.exists())
dir.mkdirs();
File file = new File(dir, "sketchpad" + pad.t_id + ".png");
FileOutputStream fOut = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.PNG, 85, fOut);
fOut.flush();
fOut.close();
I spent almost a day trying to figure out why I was getting this exception. After lots of struggle, this config worked perfectly (Kotlin):
AndroidManifest.xml
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="com.lomza.moviesroom.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths" />
</provider>
file_paths.xml
<?xml version="1.0" encoding="utf-8"?>
<paths>
<files-path name="movies_csv_files" path="."/>
</paths>
Intent itself
fun goToFileIntent(context: Context, file: File): Intent {
val intent = Intent(Intent.ACTION_VIEW)
val contentUri = FileProvider.getUriForFile(context, "${context.packageName}.fileprovider", file)
val mimeType = context.contentResolver.getType(contentUri)
intent.setDataAndType(contentUri, mimeType)
intent.flags = Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION
return intent
}
I explain the whole process here.
mkdirs()
will create the specified directory path in its entirety where mkdir()
will only create the bottom most directory, failing if it can't find the parent directory of the directory it is trying to create.
In other words mkdir()
is like mkdir
and mkdirs()
is like mkdir -p
.
For example, imagine we have an empty /tmp
directory. The following code
new File("/tmp/one/two/three").mkdirs();
would create the following directories:
/tmp/one
/tmp/one/two
/tmp/one/two/three
Where this code:
new File("/tmp/one/two/three").mkdir();
would not create any directories - as it wouldn't find /tmp/one/two
- and would return false
.
If anyone getting this in unit/instrumentation testing, make sure you call getFilesDir()
on the app context, not the test context. i.e. use:
Context appContext = getInstrumentation().getTargetContext().getApplicationContext();
not
Context appContext = InstrumentationRegistry.getContext;
The best source of information and updates on this issue I could find is in the TechNet Blogs » The Microsoft Excel Support Team Blog (as mentioned):
Form Controls stop working after December 2014 Updates (Updated March 10, 2015)
On March 2015 a hotfix was released in addition to the automated fix-it and manual instructions, and it's available on Windows Update as well.
The latest update and fix from Microsoft: 3025036 "Cannot insert object" error in an ActiveX custom Office solution after you install the MS14-082 security update
STATUS: Update March 10, 2015:
Hotfixes for this issue have been released in the March 2015 Updates for Office 2007, 2010 & 2013.
For some users, Form Controls (FM20.dll) are no longer working as expected after installing MS14-082 Microsoft Office Security Updates for December 2014. Issues are experienced at times such as when they open files with existing VBA projects using forms controls, try to insert a forms control in to a new worksheet or run third party software that may use these components.
https://technet.microsoft.com/en-us/library/security/ms14-082.aspx
You may receive errors such as: "Cannot insert object"; "Object library invalid or contains references to object definitions that could not be found"; "The program used to create this object is Forms. That program is either not installed on your computer or it is not responding. To edit this object, install Forms or ensure that any dialog boxes in Forms are closed." [...] Additionally, you may be unable to use or change properties of an ActiveX control on a worksheet or receive an error when trying to refer to an ActiveX control as a member of a worksheet via code.
Scripting solution:
Because this problem may affect more than one machine, it is also possible to create a scripting solution to delete the EXD files and run the script as part of the logon process using a policy. The script you would need should contain the following lines and would need to be run for each USER as the .exd files are USER specific.
del %temp%\vbe\*.exd
del %temp%\excel8.0\*.exd
del %appdata%\microsoft\forms\*.exd
del %appdata%\microsoft\local\*.exd
del %temp%\word8.0\*.exd
del %temp%\PPT11.0\*.exd
Additional step:
If the steps above do not resolve your issue, another step that can be tested (see warning below):
On a fully updated machine and after removing the .exd files, open the file in Excel with edit permissions.
Open Visual Basic for Applications > modify the project by adding a comment or edit of some kind to any code module > Debug > Compile VBAProject.
Save and reopen the file. Test for resolution.
If resolved, provide this updated project to additional users.
Warning: If this step resolves your issue, be aware that after deploying this updated project to the other users, these users will also need to have the updates applied on their systems and .exd files removed as well.
I would like to mention the key before writing the code for your consideration.
//Key
temp= address of new node allocated by malloc function (member od alloc.h library in C )
prev= address of last node of existing link list.
next = contains address of next node
struct node {
int data;
struct node *next;
} *head;
void addnode_end(int a) {
struct node *temp, *prev;
temp = (struct node*) malloc(sizeof(node));
if (temp == NULL) {
cout << "Not enough memory";
} else {
node->data = a;
node->next = NULL;
prev = head;
while (prev->next != NULL) {
prev = prev->next;
}
prev->next = temp;
}
}
String can be as large as 2GB.
Source
setInterval
or setTimeout
You should pass a reference to a function as the first argument for setTimeout
or setInterval
. This reference may be in the form of:
An anonymous function
setTimeout(function(){/* Look mah! No name! */},2000);
A name of an existing function
function foo(){...}
setTimeout(foo, 2000);
A variable that points to an existing function
var foo = function(){...};
setTimeout(foo, 2000);
Do note that I set "variable in a function" separately from "function name". It's not apparent that variables and function names occupy the same namespace and can clobber each other.
To call a function and pass parameters, you can call the function inside the callback assigned to the timer:
setTimeout(function(){
foo(arg1, arg2, ...argN);
}, 1000);
There is another method to pass in arguments into the handler, however it's not cross-browser compatible.
setTimeout(foo, 2000, arg1, arg2, ...argN);
By default, the context of the callback (the value of this
inside the function called by the timer) when executed is the global object window
. Should you want to change it, use bind
.
setTimeout(function(){
this === YOUR_CONTEXT; // true
}.bind(YOUR_CONTEXT), 2000);
Although it's possible, you should not pass a string to setTimeout
or setInterval
. Passing a string makes setTimeout()
or setInterval()
use a functionality similar to eval()
that executes strings as scripts, making arbitrary and potentially harmful script execution possible.
As new line can be delimited by \n
, \r
and \r\n
, first we’ll replace \r
and \r\n
with \n
, and only then split data string.
The following lines should go to the parseCSV
method:
function parseCSV(data) {
//alert(data);
//replace UNIX new lines
data = data.replace(/\r\n/g, "\n");
//replace MAC new lines
data = data.replace(/\r/g, "\n");
//split into rows
var rows = data.split("\n");
}
To bind a UDP socket when receiving multicast means to specify an address and port from which to receive data (NOT a local interface, as is the case for TCP acceptor bind). The address specified in this case has a filtering role, i.e. the socket will only receive datagrams sent to that multicast address & port, no matter what groups are subsequently joined by the socket. This explains why when binding to INADDR_ANY (0.0.0.0) I received datagrams sent to my multicast group, whereas when binding to any of the local interfaces I did not receive anything, even though the datagrams were being sent on the network to which that interface corresponded.
Quoting from UNIX® Network Programming Volume 1, Third Edition: The Sockets Networking API by W.R Stevens. 21.10. Sending and Receiving
[...] We want the receiving socket to bind the multicast group and port, say 239.255.1.2 port 8888. (Recall that we could just bind the wildcard IP address and port 8888, but binding the multicast address prevents the socket from receiving any other datagrams that might arrive destined for port 8888.) We then want the receiving socket to join the multicast group. The sending socket will send datagrams to this same multicast address and port, say 239.255.1.2 port 8888.
function greet(name, greeting) {_x000D_
name = (typeof name !== 'undefined') ? name : 'Student';_x000D_
greeting = (typeof greeting !== 'undefined') ? greeting : 'Welcome';_x000D_
_x000D_
console.log(greeting,name);_x000D_
}_x000D_
_x000D_
greet(); // Welcome Student!_x000D_
greet('James'); // Welcome James!_x000D_
greet('Richard', 'Howdy'); // Howdy Richard!_x000D_
_x000D_
//ES6 provides new ways of introducing default function parameters this way:_x000D_
_x000D_
function greet2(name = 'Student', greeting = 'Welcome') {_x000D_
// return '${greeting} ${name}!';_x000D_
console.log(greeting,name);_x000D_
}_x000D_
_x000D_
greet2(); // Welcome Student!_x000D_
greet2('James'); // Welcome James!_x000D_
greet2('Richard', 'Howdy'); // Howdy Richard!
_x000D_
Try using:
SELECT * FROM <tablename> WITH ROWLOCK XLOCK HOLDLOCK
This should make the lock exclusive and hold it for the duration of the transaction.
I will be answering this in general terms, and very thankful to the above contributers.
I am using MySQL on MySQL Workbench. I had a similar issue trying to concatenate a char
and an int
together using the GROUP_CONCAT
method.
In summary, what has worked for me is this:
let's say your char
is 'c' and int
is 'i', so, the query becomes:
...GROUP_CONCAT(CONCAT(c,' ', CAST(i AS CHAR))...
*&
signifies the receiving the pointer by reference. It means it is an alias for the passing parameter. So, it affects the passing parameter.
#include <iostream>
using namespace std;
void foo(int *ptr)
{
ptr = new int(50); // Modifying the pointer to point to a different location
cout << "In foo:\t" << *ptr << "\n";
delete ptr ;
}
void bar(int *& ptr)
{
ptr = new int(80); // Modifying the pointer to point to a different location
cout << "In bar:\t" << *ptr << "\n";
// Deleting the pointer will result the actual passed parameter dangling
}
int main()
{
int temp = 100 ;
int *p = &temp ;
cout << "Before foo:\t" << *p << "\n";
foo(p) ;
cout << "After foo:\t" << *p << "\n";
cout << "Before bar:\t" << *p << "\n";
bar(p) ;
cout << "After bar:\t" << *p << "\n";
delete p;
return 0;
}
Output:
Before foo: 100
In foo: 50
After foo: 100
Before bar: 100
In bar: 80
After bar: 80
This is taken from the Python docs:
Identifiers (also referred to as names) are described by the following lexical definitions:
identifier ::= (letter|"_") (letter | digit | "_")*
letter ::= lowercase | uppercase
lowercase ::= "a"..."z"
uppercase ::= "A"..."Z"
digit ::= "0"..."9"
Identifiers are unlimited in length. Case is significant.
That should explain how to name your variables.
A recursive algorithm that parses through an XmlDocument
Here is an example - Recursively reading an xml document and using regex to get contents
Here is another recursive example - http://www.java2s.com/Tutorial/CSharp/0540__XML/LoopThroughXmlDocumentRecursively.html
I found that "@RequestMapping produces=" and other configuration changes didn't help me. By the time you do resp.getWriter(), it is also too late to set the encoding on the writer.
Adding a header to the HttpServletResponse works.
@RequestMapping(value="/test", method=RequestMethod.POST)
public void test(HttpServletResponse resp) {
try {
resp.addHeader("content-type", "application/json; charset=utf-8");
PrintWriter w = resp.getWriter();
w.write("{\"name\" : \"µr µicron\"}");
w.flush();
w.close();
} catch (Exception e) {
e.printStackTrace();
}
}
In SQL Server 2008,2012,2014 you can insert multiple rows using a single SQL INSERT statement.
INSERT INTO TableName ( Column1, Column2 ) VALUES
( Value1, Value2 ), ( Value1, Value2 )
Another way
INSERT INTO TableName (Column1, Column2 )
SELECT Value1 ,Value2
UNION ALL
SELECT Value1 ,Value2
UNION ALL
SELECT Value1 ,Value2
UNION ALL
SELECT Value1 ,Value2
UNION ALL
SELECT Value1 ,Value2
Short answer: classmaps are static while PSR autoloading is dynamic.
If you don't want to use classmaps, use PSR autoloading instead.
You can use a custom style:
<!-- Alert Dialog -->
<style name="ThemeOverlay.MaterialComponents.MaterialAlertDialog_Background" parent="@style/ThemeOverlay.MaterialComponents.MaterialAlertDialog">
<!-- Background Color-->
<item name="android:background">@color/.....</item>
<!-- Text Color for title and message -->
<item name="colorOnSurface">@color/......</item>
<!-- Style for positive button -->
<item name="buttonBarPositiveButtonStyle">@style/PositiveButtonStyle</item>
<!-- Style for negative button -->
<item name="buttonBarNegativeButtonStyle">@style/NegativeButtonStyle</item>
</style>
<style name="PositiveButtonStyle" parent="@style/Widget.MaterialComponents.Button">
<!-- text color for the button -->
<item name="android:textColor">@color/.....</item>
<!-- Background tint for the button -->
<item name="backgroundTint">@color/primaryDarkColor</item>
</style>
And just use the default MaterialAlertDialogBuilder
:
new MaterialAlertDialogBuilder(AlertDialogActivity.this,
R.style.ThemeOverlay_MaterialComponents_MaterialAlertDialog_Background)
.setTitle("Dialog")
.setMessage("Message... ....")
.setPositiveButton("Ok", /* listener = */ null)
.show();
If you're just quickly looking to keep a cmd instance open instead of exiting immediately, simply doing the following is enough
set /p asd="Hit enter to continue"
at the end of your script and it'll keep the window open.
Note that this'll set asd
as an environment variable, and can be replaced with anything else.
First of all, from __future__ import print_function
needs to be the first line of code in your script (aside from some exceptions mentioned below). Second of all, as other answers have said, you have to use print
as a function now. That's the whole point of from __future__ import print_function
; to bring the print
function from Python 3 into Python 2.6+.
from __future__ import print_function
import sys, os, time
for x in range(0,10):
print(x, sep=' ', end='') # No need for sep here, but okay :)
time.sleep(1)
__future__
statements need to be near the top of the file because they change fundamental things about the language, and so the compiler needs to know about them from the beginning. From the documentation:
A future statement is recognized and treated specially at compile time: Changes to the semantics of core constructs are often implemented by generating different code. It may even be the case that a new feature introduces new incompatible syntax (such as a new reserved word), in which case the compiler may need to parse the module differently. Such decisions cannot be pushed off until runtime.
The documentation also mentions that the only things that can precede a __future__
statement are the module docstring, comments, blank lines, and other future statements.
You have to look at the bigger problem. How to write the directives that solve one problem. You should try directive use-form-error. Would it help to solve this problem, and many others.
<form name="ExampleForm">
<label>Password</label>
<input ng-model="password" required />
<br>
<label>Confirm password</label>
<input ng-model="confirmPassword" required />
<div use-form-error="isSame" use-error-expression="password && confirmPassword && password!=confirmPassword" ng-show="ExampleForm.$error.isSame">Passwords Do Not Match!</div>
</form>
Live example jsfiddle
Url.Action("Evil", model)
will generate a get query string but your ajax method is post and it will throw error status of 500(Internal Server Error). – Fereydoon Barikzehy Feb 14 at 9:51
Just Add "JsonRequestBehavior.AllowGet" on your Json object.
Another way to address the timezone issue if you want to set the default timezone for the entire script to a certian timezone is to use
date_default_timezone_set()
then use one of the supported timezones.
The problem here are PHP namespaces. You need to learn how to use them. As your controller are in App\Http\Controllers
namespace, if you refer any other class, you need to add leading backslash (or proper namespace) or add use
statement at the beginning of file (before class definition).
So in your case you could use:
$headquote = \DB::table('quotation_texts')->find(176);
$headquote = \App\Quotation::find(176);
or add in your controller class use
statement so the beginning of your controller class could look like this:
<?php
namespace App\Http\Controllers;
use DB;
use App\Quotation;
For more information about namespaces you could look at How to use objects from other namespaces and how to import namespaces in PHP or namespaces in PHP manual
The quick possible answer: When you first successfully clone an empty git repository, the origin has no master branch. So the first time you have a commit to push you must do:
git push origin master
Which will create this new master branch for you. Little things like this are very confusing with git.
If this didn't fix your issue then it's probably a gitolite-related issue:
Your conf file looks strange. There should have been an example conf file that came with your gitolite. Mine looks like this:
repo phonegap
RW+ = myusername otherusername
repo gitolite-admin
RW+ = myusername
Please make sure you're setting your conf file correctly.
Gitolite actually replaces the gitolite user's account with a modified shell that doesn't accept interactive terminal sessions. You can see if gitolite is working by trying to ssh into your box using the gitolite user account. If it knows who you are it will say something like "Hi XYZ, you have access to the following repositories: X, Y, Z" and then close the connection. If it doesn't know you, it will just close the connection.
Lastly, after your first git push failed on your local machine you should never resort to creating the repo manually on the server. We need to know why your git push failed initially. You can cause yourself and gitolite more confusion when you don't use gitolite exclusively once you've set it up.
To remove the commas, you'll need to use replace
on the string. To convert to a float so you can do the maths, you'll need parseFloat
:
var total = parseFloat('100,000.00'.replace(/,/g, '')) +
parseFloat('500,000.00'.replace(/,/g, ''));
Use the pandas.DataFrame.round() method like this:
df = df.round({'value1': 0})
Any columns not included will be left as is.
It seems many regex given miss one thing or another. This has been working for me so far:
(?i)^\s*[+-]?(?:inf(inity)?|nan|(?:\d+\.?\d*|\.\d+)(?:e[+-]?\d+)?)\s*$
It allows for infinity (or inf) with sign, nan, no digit before the
decimal, and leading/trailing spaces (if desired). The ^
and $
are
needed to keep from partially matching something like 1.2f-2
as 1.2
.
You could use [ed]
instead of just e
if you need to parse some files
where D
is used for double-precision scientific notation. You would
want to replace it afterward or just replace them before checking since
the float()
function won't allow it.
Which whitespace character? The most common is the normal space, which is between each word in my sentences. This is just " "
.
Based on Amith Koujalgi's answer, here's a simple module you can use for logging -
transcript.py:
"""
Transcript - direct print output to a file, in addition to terminal.
Usage:
import transcript
transcript.start('logfile.log')
print("inside file")
transcript.stop()
print("outside file")
"""
import sys
class Transcript(object):
def __init__(self, filename):
self.terminal = sys.stdout
self.logfile = open(filename, "a")
def write(self, message):
self.terminal.write(message)
self.logfile.write(message)
def flush(self):
# this flush method is needed for python 3 compatibility.
# this handles the flush command by doing nothing.
# you might want to specify some extra behavior here.
pass
def start(filename):
"""Start transcript, appending print output to given filename"""
sys.stdout = Transcript(filename)
def stop():
"""Stop transcript and return print functionality to normal"""
sys.stdout.logfile.close()
sys.stdout = sys.stdout.terminal
In Perl 5.14 (it works in now in Perl 5.13), we'll be able to just use keys on the hash reference
use v5.13.7;
foreach my $key (keys $ad_grp_ref) {
...
}
PROPS
A React component should use props to store information that can be changed, but can only be changed by a different component.
STATE
A React component should use state to store information that the component itself can change.
A good example is already provided by Valéry.
You can use semicolons to separate statements:
$ while [ 1 ]; do foo; sleep 2; done
Really stupid question: Are you sure the string is being truncated, and not just broken at the linebreak you specify (and possibly not showing in your interface)? Ie, do you expect the field to show as
This will be inserted \n This will not be
or
This will be inserted
This will not be
Also, what interface are you using? Is it possible that something along the way is eating your backslashes?
I am using Primefaces with glassfish and SQL Server.
in my case i created the Webfilter, in back-end, to get every request and convert to UTF-8, like this:
package br.com.teste.filter;
import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
@WebFilter(servletNames={"Faces Servlet"})
public class Filter implements javax.servlet.Filter {
@Override
public void destroy() {
// TODO Auto-generated method stub
}
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
request.setCharacterEncoding("UTF-8");
chain.doFilter(request, response);
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
// TODO Auto-generated method stub
}
}
In the View (.xhtml) i need to set the enctype paremeter's form to UTF-8 like @Kevin Rahe:
<h:form id="frmt" enctype="multipart/form-data;charset=UTF-8" >
<!-- your code here -->
</h:form>
Dim myStringArray() As String
*code*
redim myStringArray(size_of_your_array)
Then you can do something static like this:
myStringArray = { item_1, item_2, ... }
Or something iterative like this:
Dim x
For x = 0 To size_of_your_array
myStringArray(x) = data_source(x).Name
Next x
var string = string.split(",");
jQuery UI Touch Punch just solves it all.
It's a Touch Event Support for jQuery UI. Basically, it just wires touch event back to jQuery UI. Tested on iPad, iPhone, Android and other touch-enabled mobile devices. I used jQuery UI sortable and it works like a charm.
The "common knowledge" of programming is that x += y
is an equivalent shorthand notation of x = x + y
. As long as x
and y
are of the same type (for example, both are int
s), you may consider the two statements equivalent.
However, in Java, x += y
is not identical to x = x + y
in general.
If x
and y
are of different types, the behavior of the two statements differs due to the rules of the language. For example, let's have x == 0
(int) and y == 1.1
(double):
int x = 0;
x += 1.1; // just fine; hidden cast, x == 1 after assignment
x = x + 1.1; // won't compile! 'cannot convert from double to int'
+=
performs an implicit cast, whereas for +
you need to explicitly cast the second operand, otherwise you'd get a compiler error.
Quote from Joshua Bloch's Java Puzzlers:
(...) compound assignment expressions automatically cast the result of the computation they perform to the type of the variable on their left-hand side. If the type of the result is identical to the type of the variable, the cast has no effect. If, however, the type of the result is wider than that of the variable, the compound assignment operator performs a silent narrowing primitive conversion [JLS 5.1.3].
You can add a new property of type IFormFile
to your view model
public class CreatePost
{
public string ImageCaption { set;get; }
public string ImageDescription { set;get; }
public IFormFile MyImage { set; get; }
}
and in your GET action method, we will create an object of this view model and send to the view.
public IActionResult Create()
{
return View(new CreatePost());
}
Now in your Create view which is strongly typed to our view model, have a form
tag which has the enctype
attribute set to "multipart/form-data"
@model CreatePost
<form asp-action="Create" enctype="multipart/form-data">
<input asp-for="ImageCaption"/>
<input asp-for="ImageDescription"/>
<input asp-for="MyImage"/>
<input type="submit"/>
</form>
And your HttpPost action to handle the form posting
[HttpPost]
public IActionResult Create(CreatePost model)
{
var img = model.MyImage;
var imgCaption = model.ImageCaption;
//Getting file meta data
var fileName = Path.GetFileName(model.MyImage.FileName);
var contentType = model.MyImage.ContentType;
// do something with the above data
// to do : return something
}
If you want to upload the file to some directory in your app, you should use IHostingEnvironment
to get the webroot path. Here is a working sample.
public class HomeController : Controller
{
private readonly IHostingEnvironment hostingEnvironment;
public HomeController(IHostingEnvironment environment)
{
hostingEnvironment = environment;
}
[HttpPost]
public IActionResult Create(CreatePost model)
{
// do other validations on your model as needed
if (model.MyImage != null)
{
var uniqueFileName = GetUniqueFileName(model.MyImage.FileName);
var uploads = Path.Combine(hostingEnvironment.WebRootPath, "uploads");
var filePath = Path.Combine(uploads,uniqueFileName);
model.MyImage.CopyTo(new FileStream(filePath, FileMode.Create));
//to do : Save uniqueFileName to your db table
}
// to do : Return something
return RedirectToAction("Index","Home");
}
private string GetUniqueFileName(string fileName)
{
fileName = Path.GetFileName(fileName);
return Path.GetFileNameWithoutExtension(fileName)
+ "_"
+ Guid.NewGuid().ToString().Substring(0, 4)
+ Path.GetExtension(fileName);
}
}
This will save the file to uploads
folder inside wwwwroot
directory of your app with a random file name generated using Guids ( to prevent overwriting of files with same name)
Here we are using a very simple GetUniqueName
method which will add 4 chars from a guid to the end of the file name to make it somewhat unique. You can update the method to make it more sophisticated as needed.
Should you be storing the full url to the uploaded image in the database ?
No. Do not store the full url to the image in the database. What if tomorrow your business decides to change your company/product name from www.thefacebook.com
to www.facebook.com
? Now you have to fix all the urls in the table!
What should you store ?
You should store the unique filename which you generated above(the uniqueFileName
varibale we used above) to store the file name. When you want to display the image back, you can use this value (the filename) and build the url to the image.
For example, you can do this in your view.
@{
var imgFileName = "cats_46df.png";
}
<img src="~/uploads/@imgFileName" alt="my img"/>
I just hardcoded an image name to imgFileName
variable and used that. But you may read the stored file name from your database and set to your view model property and use that. Something like
<img src="~/uploads/@Model.FileName" alt="my img"/>
Storing the image to table
If you want to save the file as bytearray/varbinary to your database, you may convert the IFormFile
object to byte array like this
private byte[] GetByteArrayFromImage(IFormFile file)
{
using (var target = new MemoryStream())
{
file.CopyTo(target);
return target.ToArray();
}
}
Now in your http post action method, you can call this method to generate the byte array from IFormFile
and use that to save to your table. the below example is trying to save a Post entity object using entity framework.
[HttpPost]
public IActionResult Create(CreatePost model)
{
//Create an object of your entity class and map property values
var post=new Post() { ImageCaption = model.ImageCaption };
if (model.MyImage != null)
{
post.Image = GetByteArrayFromImage(model.MyImage);
}
_context.Posts.Add(post);
_context.SaveChanges();
return RedirectToAction("Index","Home");
}
If we want to add custom HTTP headers to a POST request, we must pass them through a dictionary to the headers
parameter.
Here is an example with a non-empty body and headers:
import requests
import json
url = 'https://somedomain.com'
body = {'name': 'Maryja'}
headers = {'content-type': 'application/json'}
r = requests.post(url, data=json.dumps(body), headers=headers)
The quote PASV
command is not a command to the ftp.exe
program, it is a command to the FTP server requesting a high order port for data transfer. A passive transfer is one in which the FTP data over these high order ports while control is maintained in the lower ports.
The windows ftp.exe
program can be used to send the FTP server commands to make a passive data transfer between two FTP servers. A standard windows installation will not, and probably should not, have FTP server service running as an endpoint for passive transfers. So if passive transfers are needed with a standard windows box, a solution other than ftp.exe
is necessary as FTPing to localhost as one of the connections won't work in most windows environments.
You can effect a passive FTP transfer between two different hosts (but not two connections on the same host) as follows:
Open up two prompts, use one to ftp.exe
connect to your source FTP server and one to ftp.exe
connect to your destination FTP server.
Now establish a passive connection between the servers using the raw commands PASV and PORT. The quote PASV
command will respond with an IP/port in ellipsis. Use that data for the quote PORT <data>
command. Your passive link is now established assuming that firewalls haven't blocked one or more of the four ports (2 for FTP control, 2 for FTP data)
Next start receive of data with the quote STOR <filename>
command to the receiving FTP server then send the control command quote RETR <filename>
to the source FTP server.
so for me:
client 1
> ftp.exe server1
ftp> quote PASV
227 Entering Passive Mode (10,0,3,1,54,161)
client 2
> ftp.exe server2
ftp> quote PORT 10,0,3,1,54,54,161
ftp> quote STOR myFile
client 1
ftp> quote RETR myFile
Cavet: I'm connecting to some old FTP servers YMMV
Apache Commons Collections 4 has a partition method in the ListUtils
class. Here’s how it works:
import org.apache.commons.collections4.ListUtils;
...
int targetSize = 100;
List<Integer> largeList = ...
List<List<Integer>> output = ListUtils.partition(largeList, targetSize);
File.WriteAllText(file,content)
create write close
File.WriteAllBytes-- type binary
:)
If you only want to allow specific characters, you could also do it like this:
function randomString(length, chars) {
var result = '';
for (var i = length; i > 0; --i) result += chars[Math.floor(Math.random() * chars.length)];
return result;
}
var rString = randomString(32, '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ');
Here's a jsfiddle to demonstrate: http://jsfiddle.net/wSQBx/
Another way to do it could be to use a special string that tells the function what types of characters to use. You could do that like this:
function randomString(length, chars) {
var mask = '';
if (chars.indexOf('a') > -1) mask += 'abcdefghijklmnopqrstuvwxyz';
if (chars.indexOf('A') > -1) mask += 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
if (chars.indexOf('#') > -1) mask += '0123456789';
if (chars.indexOf('!') > -1) mask += '~`!@#$%^&*()_+-={}[]:";\'<>?,./|\\';
var result = '';
for (var i = length; i > 0; --i) result += mask[Math.floor(Math.random() * mask.length)];
return result;
}
console.log(randomString(16, 'aA'));
console.log(randomString(32, '#aA'));
console.log(randomString(64, '#A!'));
Fiddle: http://jsfiddle.net/wSQBx/2/
Alternatively, to use the base36 method as described below you could do something like this:
function randomString(length) {
return Math.round((Math.pow(36, length + 1) - Math.random() * Math.pow(36, length))).toString(36).slice(1);
}
If you run the server in normal mode you can recover the log by restarting the main project in debug mode. It seems that NB opens a new server log when the server run mode changes.
Twisted can help you with what you are doing, check out their documentation, there are plenty of examples. Also it is a mature product with a big developer/user community behind it.
A more elegant way is to assign the whole array at once:
Sub PrintArray(Data, SheetName, StartRow, StartCol)
Dim Rng As Range
With Sheets(SheetName)
Set Rng = .Range(.Cells(StartRow, StartCol), _
.Cells(UBound(Data, 1) - LBound(Data, 1) + StartRow, _
UBound(Data, 2) - LBound(Data, 2) + StartCol))
End With
Rng.Value2 = Data
End Sub
But watch out: it only works up to a size of about 8,000 cells. Then Excel throws a strange error. The maximum size isn't fixed and differs very much from Excel installation to Excel installation.
If you're using the Maps API v3, this has changed.
In version 3, you essentially want to set up a listener for the bounds_changed
event, which will trigger upon map load. Once that has triggered, remove the listener as you don't want to be informed every time the viewport bounds change.
This may change in the future as the V3 API is evolving :-)
According to the docs you can set the parse_mode
field to:
Markdown still works but it's now considered a legacy mode.
You can pass the parse_mode
parameter like this:
https://api.telegram.org/bot[yourBotKey]/sendMessage?chat_id=[yourChatId]&parse_mode=MarkdownV2&text=[yourMessage]
For bold and italic using MarkdownV2:
*bold text*
_italic text_
And for HTML:
<b>bold</b> or <strong>bold</strong>
<i>italic</I> or <em>italic</em>
Make sure to encode your query-string parameters regardless the format you pick. For example:
val message = "*bold text*";
val encodedMsg = URLEncoder.encode(message, "UTF-8");
var message = "*bold text*"
var encodedMsg = encodeURIComponent(message)
$message = "*bold text*";
$encodedMsg = urlencode($message);
From the spring boot docs https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html
YAML lists are represented as property keys with [index] dereferencers, for example this YAML:
my:
servers:
- dev.bar.com
- foo.bar.com
Would be transformed into these properties:
my.servers[0]=dev.bar.com
my.servers[1]=foo.bar.com
To bind to properties like that using the Spring DataBinder utilities (which is what @ConfigurationProperties
does) you need to have a property in the target bean of type java.util.List
and you either need to provide a setter, or initialize it with a mutable value, e.g. this will bind to the properties above. Here is what the question's code would look like.
@ConfigurationProperties(prefix="ignore")
public class Filenames {
private List<String> ignoredFilenames = new ArrayList<String>();
public List<String> getFilenames() {
return this.ignoredFilenames;
}
}
You have to use square bracket notation when -
The property name is number.
var ob = {
1: 'One',
7 : 'Seven'
}
ob.7 // SyntaxError
ob[7] // "Seven"
The property name has special character.
var ob = {
'This is one': 1,
'This is seven': 7,
}
ob.'This is one' // SyntaxError
ob['This is one'] // 1
The property name is assigned to a variable and you want to access the property value by this variable.
var ob = {
'One': 1,
'Seven': 7,
}
var _Seven = 'Seven';
ob._Seven // undefined
ob[_Seven] // 7
Best not to mess with msysObjects (IMHO).
CurrentDB.TableDefs
CurrentDB.QueryDefs
CurrentProject.AllForms
CurrentProject.AllReports
CurrentProject.AllMacros
You can set the style using jQuery's css
method:
$('something:visible').css('display', 'none');
var htmlText = System.IO.File.ReadAllText(@"C:/filename.html");
And if file in at application root, user below
var htmlText = System.IO.File.ReadAllText(HttpContext.Current.Server.MapPath(@"~/filename.html"));
It's important to make the difference between the App language and the device locale language (The code below is in Swift 3)
Will return the Device language:
let locale = NSLocale.current.languageCode
Will return the App language:
let pre = Locale.preferredLanguages[0]
One other possibility is, if you want to ignore all unknown properties, you can configure the mapper as follows:
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
find $HOME -name "hello.c" -print
This will search the whole $HOME
(i.e. /home/username/
) system for any files named “hello.c” and display their pathnames:
/Users/user/Downloads/hello.c
/Users/user/hello.c
However, it will not match HELLO.C
or HellO.C
. To match is case insensitive pass the -iname
option as follows:
find $HOME -iname "hello.c" -print
Sample outputs:
/Users/user/Downloads/hello.c
/Users/user/Downloads/Y/Hello.C
/Users/user/Downloads/Z/HELLO.c
/Users/user/hello.c
Pass the -type f
option to only search for files:
find /dir/to/search -type f -iname "fooBar.conf.sample" -print
find $HOME -type f -iname "fooBar.conf.sample" -print
The -iname
works either on GNU or BSD (including OS X) version find command. If your version of find command does not supports -iname
, try the following syntax using grep
command:
find $HOME | grep -i "hello.c"
find $HOME -name "*" -print | grep -i "hello.c"
OR try
find $HOME -name '[hH][eE][lL][lL][oO].[cC]' -print
Sample outputs:
/Users/user/Downloads/Z/HELLO.C
/Users/user/Downloads/Z/HEllO.c
/Users/user/Downloads/hello.c
/Users/user/hello.c
Button inputs don't have a submit event. Try attaching the event handler to the form instead:
<script type="text/javascript">
$('#login_form').submit(function() {
$('#gif').show();
return true;
});
</script>
What you've done doesn't work because you're binding an event to a function. As such, it's the event which defines the parameters that will be called when the event is raised (i.e. JavaScript doesn't know about your parameter in the function you've bound to onclick so can't pass anything into it).
You could do this however:
<input type="button" value="Click me" id="myButton"/>
<script type="text/javascript">
var myButton = document.getElementById("myButton");
var myMessage = "it's working";
var myDelegate = function(message) {
alert(message);
}
myButton.onclick = function() {
myDelegate(myMessage);
};
</script>
So you want to fire Ajax calls to the servlet? For that you need the XMLHttpRequest
object in JavaScript. Here's a Firefox compatible example:
<script>
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
var data = xhr.responseText;
alert(data);
}
}
xhr.open('GET', '${pageContext.request.contextPath}/myservlet', true);
xhr.send(null);
</script>
This is however very verbose and not really crossbrowser compatible. For the best crossbrowser compatible way of firing ajaxical requests and traversing the HTML DOM tree, I recommend to grab jQuery. Here's a rewrite of the above in jQuery:
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$.get('${pageContext.request.contextPath}/myservlet', function(data) {
alert(data);
});
</script>
Either way, the Servlet on the server should be mapped on an url-pattern
of /myservlet
(you can change this to your taste) and have at least doGet()
implemented and write the data to the response as follows:
String data = "Hello World!";
response.setContentType("text/plain");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(data);
This should show Hello World!
in the JavaScript alert.
You can of course also use doPost()
, but then you should use 'POST'
in xhr.open()
or use $.post()
instead of $.get()
in jQuery.
Then, to show the data in the HTML page, you need to manipulate the HTML DOM. For example, you have a
<div id="data"></div>
in the HTML where you'd like to display the response data, then you can do so instead of alert(data)
of the 1st example:
document.getElementById("data").firstChild.nodeValue = data;
In the jQuery example you could do this in a more concise and nice way:
$('#data').text(data);
To go some steps further, you'd like to have an easy accessible data format to transfer more complex data. Common formats are XML and JSON. For more elaborate examples on them, head to How to use Servlets and Ajax?
Communication between a browser and a webserver takes place at so many levels that is close to impossible to answer this question. HTTP plays a role, but HTTP is meaningless without TCP which is meaningless without IP which is meaningless without a physical network on which it sent. Then, there are POST vs GET requests which are similar but enough different to warrant a special dicussion. Sometimes an HTTP request needs to be authenticated, sometimes, it needs not. Mime types should be mentioned. Then, a browser sends a different request if there is a proxy. And then also encodings play a role. So, I guess, the most concise answer to this kind of question is: the browser asks the server for data and the server gives the requested data to the browser.
Here is some production code that sends the file to an ftp (may be a good solution for you):
// This is the entire file that was uploaded to a temp location.
$localFile = $_FILES[$fileKey]['tmp_name'];
$fp = fopen($localFile, 'r');
// Connecting to website.
$ch = curl_init();
curl_setopt($ch, CURLOPT_USERPWD, "[email protected]:password");
curl_setopt($ch, CURLOPT_URL, 'ftp://@ftp.website.net/audio/' . $strFileName);
curl_setopt($ch, CURLOPT_UPLOAD, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 86400); // 1 Day Timeout
curl_setopt($ch, CURLOPT_INFILE, $fp);
curl_setopt($ch, CURLOPT_NOPROGRESS, false);
curl_setopt($ch, CURLOPT_PROGRESSFUNCTION, 'CURL_callback');
curl_setopt($ch, CURLOPT_BUFFERSIZE, 128);
curl_setopt($ch, CURLOPT_INFILESIZE, filesize($localFile));
curl_exec ($ch);
if (curl_errno($ch)) {
$msg = curl_error($ch);
}
else {
$msg = 'File uploaded successfully.';
}
curl_close ($ch);
$return = array('msg' => $msg);
echo json_encode($return);
It seems that in VBA macro code for an ActiveX checkbox control you use
If (ActiveSheet.OLEObjects("CheckBox1").Object.Value = True)
and for a Form checkbox control you use
If (ActiveSheet.Shapes("CheckBox1").OLEFormat.Object.Value = 1)
I can give an example commonly seen in project.
Here, option --no-ff
(i.e. true merge) creates a new commit with multiple parents, and provides a better history tracking. Otherwise, --ff
(i.e. fast-forward merge) is by default.
$ git checkout master
$ git checkout -b newFeature
$ ...
$ git commit -m 'work from day 1'
$ ...
$ git commit -m 'work from day 2'
$ ...
$ git commit -m 'finish the feature'
$ git checkout master
$ git merge --no-ff newFeature -m 'add new feature'
$ git log
// something like below
commit 'add new feature' // => commit created at merge with proper message
commit 'finish the feature'
commit 'work from day 2'
commit 'work from day 1'
$ gitk // => see details with graph
$ git checkout -b anotherFeature // => create a new branch (*)
$ ...
$ git commit -m 'work from day 3'
$ ...
$ git commit -m 'work from day 4'
$ ...
$ git commit -m 'finish another feature'
$ git checkout master
$ git merge anotherFeature // --ff is by default, message will be ignored
$ git log
// something like below
commit 'work from day 4'
commit 'work from day 3'
commit 'add new feature'
commit 'finish the feature'
commit ...
$ gitk // => see details with graph
(*) Note that here if the newFeature
branch is re-used, instead of creating a new branch, git will have to do a --no-ff
merge anyway. This means fast forward merge is not always eligible.
I think that this is an old error that you tried to fix by importing random things in your module and now the code does not compile anymore. while you don't pay attention to the shell output, the browser reload, and you still get the same error.
Your module should be :
@NgModule({
imports: [
CommonModule,
FormsModule,
ReactiveFormsModule
],
declarations: [
ContactComponent
]
})
export class ContactModule {}
I believe you can only make it readonly.
Try this code, maybe useful.
1.Create New C# Project and add follows code to Form1:
using System;
using System.Windows.Forms;
using System.Security.Cryptography;
namespace ExampleCrypto
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
string strOriginalData = string.Empty;
string strEncryptedData = string.Empty;
string strDecryptedData = string.Empty;
strOriginalData = "this is original data 1234567890"; // your original data in here
MessageBox.Show("ORIGINAL DATA:\r\n" + strOriginalData);
clsCrypto aes = new clsCrypto();
aes.IV = "this is your IV"; // your IV
aes.KEY = "this is your KEY"; // your KEY
strEncryptedData = aes.Encrypt(strOriginalData, CipherMode.CBC); // your cipher mode
MessageBox.Show("ENCRYPTED DATA:\r\n" + strEncryptedData);
strDecryptedData = aes.Decrypt(strEncryptedData, CipherMode.CBC);
MessageBox.Show("DECRYPTED DATA:\r\n" + strDecryptedData);
}
}
}
2.Create clsCrypto.cs and copy paste follows code in your class and run your code. I used MD5 to generated Initial Vector(IV) and KEY of AES.
using System;
using System.Security.Cryptography;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Runtime.Remoting.Metadata.W3cXsd2001;
namespace ExampleCrypto
{
public class clsCrypto
{
private string _KEY = string.Empty;
protected internal string KEY
{
get
{
return _KEY;
}
set
{
if (!string.IsNullOrEmpty(value))
{
_KEY = value;
}
}
}
private string _IV = string.Empty;
protected internal string IV
{
get
{
return _IV;
}
set
{
if (!string.IsNullOrEmpty(value))
{
_IV = value;
}
}
}
private string CalcMD5(string strInput)
{
string strOutput = string.Empty;
if (!string.IsNullOrEmpty(strInput))
{
try
{
StringBuilder strHex = new StringBuilder();
using (MD5 md5 = MD5.Create())
{
byte[] bytArText = Encoding.Default.GetBytes(strInput);
byte[] bytArHash = md5.ComputeHash(bytArText);
for (int i = 0; i < bytArHash.Length; i++)
{
strHex.Append(bytArHash[i].ToString("X2"));
}
strOutput = strHex.ToString();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
return strOutput;
}
private byte[] GetBytesFromHexString(string strInput)
{
byte[] bytArOutput = new byte[] { };
if ((!string.IsNullOrEmpty(strInput)) && strInput.Length % 2 == 0)
{
SoapHexBinary hexBinary = null;
try
{
hexBinary = SoapHexBinary.Parse(strInput);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
bytArOutput = hexBinary.Value;
}
return bytArOutput;
}
private byte[] GenerateIV()
{
byte[] bytArOutput = new byte[] { };
try
{
string strIV = CalcMD5(IV);
bytArOutput = GetBytesFromHexString(strIV);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
return bytArOutput;
}
private byte[] GenerateKey()
{
byte[] bytArOutput = new byte[] { };
try
{
string strKey = CalcMD5(KEY);
bytArOutput = GetBytesFromHexString(strKey);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
return bytArOutput;
}
protected internal string Encrypt(string strInput, CipherMode cipherMode)
{
string strOutput = string.Empty;
if (!string.IsNullOrEmpty(strInput))
{
try
{
byte[] bytePlainText = Encoding.Default.GetBytes(strInput);
using (RijndaelManaged rijManaged = new RijndaelManaged())
{
rijManaged.Mode = cipherMode;
rijManaged.BlockSize = 128;
rijManaged.KeySize = 128;
rijManaged.IV = GenerateIV();
rijManaged.Key = GenerateKey();
rijManaged.Padding = PaddingMode.Zeros;
ICryptoTransform icpoTransform = rijManaged.CreateEncryptor(rijManaged.Key, rijManaged.IV);
using (MemoryStream memStream = new MemoryStream())
{
using (CryptoStream cpoStream = new CryptoStream(memStream, icpoTransform, CryptoStreamMode.Write))
{
cpoStream.Write(bytePlainText, 0, bytePlainText.Length);
cpoStream.FlushFinalBlock();
}
strOutput = Encoding.Default.GetString(memStream.ToArray());
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
return strOutput;
}
protected internal string Decrypt(string strInput, CipherMode cipherMode)
{
string strOutput = string.Empty;
if (!string.IsNullOrEmpty(strInput))
{
try
{
byte[] byteCipherText = Encoding.Default.GetBytes(strInput);
byte[] byteBuffer = new byte[strInput.Length];
using (RijndaelManaged rijManaged = new RijndaelManaged())
{
rijManaged.Mode = cipherMode;
rijManaged.BlockSize = 128;
rijManaged.KeySize = 128;
rijManaged.IV = GenerateIV();
rijManaged.Key = GenerateKey();
rijManaged.Padding = PaddingMode.Zeros;
ICryptoTransform icpoTransform = rijManaged.CreateDecryptor(rijManaged.Key, rijManaged.IV);
using (MemoryStream memStream = new MemoryStream(byteCipherText))
{
using (CryptoStream cpoStream = new CryptoStream(memStream, icpoTransform, CryptoStreamMode.Read))
{
cpoStream.Read(byteBuffer, 0, byteBuffer.Length);
}
strOutput = Encoding.Default.GetString(byteBuffer);
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
return strOutput;
}
}
}
if (StartDate>=EndDate)
{
throw new InvalidOperationException("Ack! StartDate is not before EndDate!");
}
public static IEnumerable<T> GetRandom<T>(this IList<T> list, int count, Random random)
{
// Probably you should throw exception if count > list.Count
count = Math.Min(list.Count, count);
var selectedIndices = new SortedSet<int>();
// Random upper bound
int randomMax = list.Count - 1;
while (selectedIndices.Count < count)
{
int randomIndex = random.Next(0, randomMax);
// skip over already selected indeces
foreach (var selectedIndex in selectedIndices)
if (selectedIndex <= randomIndex)
++randomIndex;
else
break;
yield return list[randomIndex];
selectedIndices.Add(randomIndex);
--randomMax;
}
}
Memory: ~count
Complexity: O(count2)
On @Sorin's suggestion of the Java Pattern docs, it looks like chars to escape are at least:
\.[{(*+?^$|
There is also this tool you can use. It supports multi-events .ics file creation. It also supports timezone as well.
The Mockito javadoc seems to tell why use doReturn()
instead of when()
Use doReturn() in those rare occasions when you cannot use Mockito.when(Object).
Beware that Mockito.when(Object) is always recommended for stubbing because it is argument type-safe and more readable (especially when stubbing consecutive calls).
Here are those rare occasions when doReturn() comes handy:
1. When spying real objects and calling real methods on a spy brings side effects
List list = new LinkedList(); List spy = spy(list);
//Impossible: real method is called so spy.get(0) throws IndexOutOfBoundsException (the list is yet empty)
when(spy.get(0)).thenReturn("foo");
//You have to use doReturn() for stubbing:
doReturn("foo").when(spy).get(0);
2. Overriding a previous exception-stubbing:
when(mock.foo()).thenThrow(new RuntimeException());
//Impossible: the exception-stubbed foo() method is called so RuntimeException is thrown.
when(mock.foo()).thenReturn("bar");
//You have to use doReturn() for stubbing:
doReturn("bar").when(mock).foo();
Above scenarios shows a tradeoff of Mockito's elegant syntax. Note that the scenarios are very rare, though. Spying should be sporadic and overriding exception-stubbing is very rare. Not to mention that in general overridding stubbing is a potential code smell that points out too much stubbing.
simple way to do this... here are the example
cd program files
cd poweriso
piso mount D:\<Filename.iso> <Virtual Drive>
Pause
this will mount the ISO image to the specific drive...use
$('#message').val('');
Explanation (from @BalusC):
textarea
is an input
element with a value. You actually want to "empty" the value. So as for every other input
element (input
, select
, textarea
) you need to use element.val('');
.
Also see docs
Checkout And Run The Following Code. It will help you...
$( function() {_x000D_
$.widget( "custom.iconselectmenu", $.ui.selectmenu, {_x000D_
_renderItem: function( ul, item ) {_x000D_
var li = $( "<li>" ),_x000D_
wrapper = $( "<div>", { text: item.label } );_x000D_
_x000D_
if ( item.disabled ) {_x000D_
li.addClass( "ui-state-disabled" );_x000D_
}_x000D_
_x000D_
$( "<span>", {_x000D_
style: item.element.attr( "data-style" ),_x000D_
"class": "ui-icon " + item.element.attr( "data-class" )_x000D_
})_x000D_
.appendTo( wrapper );_x000D_
_x000D_
return li.append( wrapper ).appendTo( ul );_x000D_
}_x000D_
});_x000D_
_x000D_
$( "#filesA" )_x000D_
.iconselectmenu()_x000D_
.iconselectmenu( "menuWidget" )_x000D_
.addClass( "ui-menu-icons" );_x000D_
_x000D_
$( "#filesB" )_x000D_
.iconselectmenu()_x000D_
.iconselectmenu( "menuWidget" )_x000D_
.addClass( "ui-menu-icons customicons" );_x000D_
_x000D_
$( "#people" )_x000D_
.iconselectmenu()_x000D_
.iconselectmenu( "menuWidget")_x000D_
.addClass( "ui-menu-icons avatar" );_x000D_
} );_x000D_
</script>_x000D_
<style>_x000D_
h2 {_x000D_
margin: 30px 0 0 0;_x000D_
}_x000D_
fieldset {_x000D_
border: 0;_x000D_
}_x000D_
label
_x000D_
{_x000D_
display: block;_x000D_
}_x000D_
_x000D_
/* select with custom icons */_x000D_
.ui-selectmenu-menu .ui-menu.customicons .ui-menu-item-wrapper {_x000D_
padding: 0.5em 0 0.5em 3em;_x000D_
}_x000D_
.ui-selectmenu-menu .ui-menu.customicons .ui-menu-item .ui-icon {_x000D_
height: 24px;_x000D_
width: 24px;_x000D_
top: 0.1em;_x000D_
}_x000D_
.ui-icon.video {_x000D_
background: url("images/24-video-square.png") 0 0 no-repeat;_x000D_
}_x000D_
.ui-icon.podcast {_x000D_
background: url("images/24-podcast-square.png") 0 0 no-repeat;_x000D_
}_x000D_
.ui-icon.rss {_x000D_
background: url("images/24-rss-square.png") 0 0 no-repeat;_x000D_
}_x000D_
_x000D_
/* select with CSS avatar icons */_x000D_
option.avatar {_x000D_
background-repeat: no-repeat !important;_x000D_
padding-left: 20px;_x000D_
}_x000D_
.avatar .ui-icon {_x000D_
background-position: left top;_x000D_
}
_x000D_
<link href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" rel="stylesheet"/>_x000D_
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>_x000D_
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>_x000D_
<!doctype html>_x000D_
<html lang="en">_x000D_
<head>_x000D_
<meta charset="utf-8">_x000D_
<meta name="viewport" content="width=device-width, initial-scale=1">_x000D_
<title>jQuery UI Selectmenu - Custom Rendering</title>_x000D_
_x000D_
</head>_x000D_
<body>_x000D_
_x000D_
<div class="demo">_x000D_
_x000D_
<form action="#">_x000D_
<h2>Selectmenu with framework icons</h2>_x000D_
<fieldset>_x000D_
<label for="filesA">Select a File:</label>_x000D_
<select name="filesA" id="filesA">_x000D_
<option value="jquery" data-class="ui-icon-script">jQuery.js</option>_x000D_
<option value="jquerylogo" data-class="ui-icon-image">jQuery Logo</option>_x000D_
<option value="jqueryui" data-class="ui-icon-script">ui.jQuery.js</option>_x000D_
<option value="jqueryuilogo" selected="selected" data-class="ui-icon-image">jQuery UI Logo</option>_x000D_
<option value="somefile" disabled="disabled" data-class="ui-icon-help">Some unknown file</option>_x000D_
</select>_x000D_
</fieldset>_x000D_
_x000D_
<h2>Selectmenu with custom icon images</h2>_x000D_
<fieldset>_x000D_
<label for="filesB">Select a podcast:</label>_x000D_
<select name="filesB" id="filesB">_x000D_
<option value="mypodcast" data-class="podcast">John Resig Podcast</option>_x000D_
<option value="myvideo" data-class="video">Scott González Video</option>_x000D_
<option value="myrss" data-class="rss">jQuery RSS XML</option>_x000D_
</select>_x000D_
</fieldset>_x000D_
_x000D_
<h2>Selectmenu with custom avatar 16x16 images as CSS background</h2>_x000D_
<fieldset>_x000D_
<label for="people">Select a Person:</label>_x000D_
<select name="people" id="people">_x000D_
<option value="1" data-class="avatar" data-style="background-image: url('http://www.gravatar.com/avatar/b3e04a46e85ad3e165d66f5d927eb609?d=monsterid&r=g&s=16');">John Resig</option>_x000D_
<option value="2" data-class="avatar" data-style="background-image: url('http://www.gravatar.com/avatar/e42b1e5c7cfd2be0933e696e292a4d5f?d=monsterid&r=g&s=16');">Tauren Mills</option>_x000D_
<option value="3" data-class="avatar" data-style="background-image: url('http://www.gravatar.com/avatar/bdeaec11dd663f26fa58ced0eb7facc8?d=monsterid&r=g&s=16');">Jane Doe</option>_x000D_
</select>_x000D_
</fieldset>_x000D_
</form>_x000D_
_x000D_
</div>_x000D_
_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
I got the same error message before. in my case, it was caused by type casting. check if siteID is a string, if it is you must add simple quotes.
hope it will help you.
For folks that have programmed in nodeJs before, particularly using expressJS. I think of .ashx
as a middleware that calls the next
function. While .aspx
will be the controller that actually responds to the request either around res.redirect
, res.send
or whatever.
I think PHP is a good solution. It's simple to set up, free and there is plenty of documentation on how to create a database management app. Ruby on Rails is faster to code but a bit more difficult to set up.
Follow this steps:
-Build
-Generate Signed Apk
-Create new
Then fill up "New Key Store" form. If you wand to change .jnk file destination then chick on destination and give a name to get Ok button. After finishing it you will get "Key store password", "Key alias", "Key password" Press next and change your the destination folder. Then press finish, thats all. :)
From Wikipedia Media type,
A media type is composed of a type, a subtype, and optional parameters. As an example, an HTML file might be designated text/html; charset=UTF-8.
Media type consists of top-level type name and sub-type name, which is further structured into so-called "trees".
top-level type name / subtype name [ ; parameters ]
top-level type name / [ tree. ] subtype name [ +suffix ] [ ; parameters ]
All media types should be registered using the IANA registration procedures. Currently the following trees are created: standard
, vendor
, personal
or vanity
, unregistered x.
Standard:
Media types in the standards tree do not use any tree facet (prefix).
type / media type name [+suffix]
Examples: "application/xhtml+xml", "image/png"
Vendor:
Vendor tree is used for media types associated with publicly available products. It uses
vnd.
facet.
type / vnd. media type name [+suffix] - used in the case of well-known producer
type / vnd. producer's name followed by media type name [+suffix] - producer's name must be approved by IANA
type / vnd. producer's name followed by product's name [+suffix] - producer's name must be approved by IANA
Personal or Vanity tree:
Personal or Vanity tree includes media types created experimentally or as part of products that are not distributed commercially. It uses
prs.
facet.
type / prs. media type name [+suffix]
Unregistered x. tree:
The "x." tree may be used for media types intended exclusively for use in private, local environments and only with the active agreement of the parties exchanging them. Types in this tree cannot be registered.
According to the previous version of RFC 6838 - obsoleted RFC 2048 (published in November 1996) it should rarely, if ever, be necessary to use unregistered experimental types, and as such use of both "x-" and "x." forms is discouraged. Previous versions of that RFC - RFC 1590 and RFC 1521 stated that the use of "x-" notation for the sub-type name may be used for unregistered and private sub-types, but this recommendation was obsoleted in November 1996.
type / x. media type name [+suffix]
So its clear that the standard type MIME type application/pdf
is the appropriate one to use while you should avoid using the obsolete and unregistered x-
media type as stated in RFC 2048 and RFC 6838.
Yet another approach is ISNULL().
UPDATE [DATABASE].[dbo].[TABLE_NAME]
SET
[ABC] = ISNULL(@ABC, [ABC]),
[ABCD] = ISNULL(@ABCD, [ABCD])
The difference between ISNULL and COALESCE is the return type. COALESCE can also take more than 2 arguments, and use the first that is not null. I.e.
select COALESCE(null, null, 1, 'two') --returns 1
select COALESCE(null, null, null, 'two') --returns 'two'
If you had MyPhoneExplorer installed and connected (not sure this is a must, happened to be my setup already), you could use it to control the screen with your computer mouse. It connects via ADB, for which your normal USB cable is enough.
Another solution I found that even worked without a reboot is updating tables in settings.db and locksettings.db I had to switch to root to open the settings.db though:
adb shell
su
sqlite3 /data/data/com.android.providers.settings/databases/settings.db
update secure set value=1 where name='lockscreen.disabled';
.quit
sqlite3 /data/system/locksettings.db
update locksettings set value=0 where name='lock_pattern_autlock';
update locksettings set value=1 where name='lockscreen.disabled';
.quit
System.setProperty is not working for applets. Because JVM already running before applet start. In this case we use applet parameters like this:
deployJava.runApplet({
id: 'MyApplet',
code: 'com.mkysoft.myapplet.SomeClass',
archive: 'com.mkysoft.myapplet.jar'
}, {
java_version: "1.6*", // Target version
cache_option: "no",
cache_archive: "",
codebase_lookup: true,
java_arguments: "-Djava.net.preferIPv4Stack=true"
},
"1.6" // Minimum version
);
You can find deployJava.js at https://www.java.com/js/deployJava.js
DFS(analysis):
O(1)
timeO(n + m)
time provided the graph is represented by the adjacency list structureSv deg(v) = 2m
BFS(analysis):
Li
O(n + m)
time provided the graph is represented by the adjacency list structureSv deg(v) = 2m
Big thanks to Mike and Robertc for their helpful posts!
If you have two elements in your HTML and you want to :hover
over one and target a style change in the other the two elements must be directly related--parents, children or siblings. This means that the two elements either must be one inside the other or must both be contained within the same larger element.
I wanted to display definitions in a box on the right side of the browser as my users read through my site and :hover
over highlighted terms; therefore, I did not want the 'definition' element to be displayed inside the 'text' element.
I almost gave up and just added javascript to my page, but this is the future dang it! We should not have to put up with back sass from CSS and HTML telling us where we have to place our elements to achieve the effects we want! In the end we compromised.
While the actual HTML elements in the file must be either nested or contained in a single element to be valid :hover
targets to each other, the css position
attribute can be used to display any element where ever you want. I used position:fixed to place the target of my :hover
action where I wanted it on the user's screen regardless to its location in the HTML document.
The html:
<div id="explainBox" class="explainBox"> /*Common parent*/
<a class="defP" id="light" href="http://en.wikipedia.or/wiki/Light">Light /*highlighted term in text*/
</a> is as ubiquitous as it is mysterious. /*plain text*/
<div id="definitions"> /*Container for :hover-displayed definitions*/
<p class="def" id="light"> /*example definition entry*/ Light:
<br/>Short Answer: The type of energy you see
</p>
</div>
</div>
The css:
/*read: "when user hovers over #light somewhere inside #explainBox
set display to inline-block for #light directly inside of #definitions.*/
#explainBox #light:hover~#definitions>#light {
display: inline-block;
}
.def {
display: none;
}
#definitions {
background-color: black;
position: fixed;
/*position attribute*/
top: 5em;
/*position attribute*/
right: 2em;
/*position attribute*/
width: 20em;
height: 30em;
border: 1px solid orange;
border-radius: 12px;
padding: 10px;
}
In this example the target of a :hover
command from an element within #explainBox
must either be #explainBox
or also within #explainBox
. The position attributes assigned to #definitions force it to appear in the desired location (outside #explainBox
) even though it is technically located in an unwanted position within the HTML document.
I understand it is considered bad form to use the same #id
for more than one HTML element; however, in this case the instances of #light
can be described independently due to their respective positions in uniquely #id
'd elements. Is there any reason not to repeat the id
#light
in this case?
You can use groupBy of angular.filter module.
so you can do something like this:
JS:
$scope.players = [
{name: 'Gene', team: 'alpha'},
{name: 'George', team: 'beta'},
{name: 'Steve', team: 'gamma'},
{name: 'Paula', team: 'beta'},
{name: 'Scruath', team: 'gamma'}
];
HTML:
<ul ng-repeat="(key, value) in players | groupBy: 'team'">
Group name: {{ key }}
<li ng-repeat="player in value">
player: {{ player.name }}
</li>
</ul>
RESULT:
Group name: alpha
* player: Gene
Group name: beta
* player: George
* player: Paula
Group name: gamma
* player: Steve
* player: Scruath
UPDATE: jsbin Remember the basic requirements to use angular.filter
, specifically note you must add it to your module's dependencies:
(1) You can install angular-filter using 4 different methods:
- clone & build this repository
- via Bower: by running $ bower install angular-filter from your terminal
- via npm: by running $ npm install angular-filter from your terminal
- via cdnjs http://www.cdnjs.com/libraries/angular-filter
(2) Include angular-filter.js (or angular-filter.min.js) in your index.html, after including Angular itself.
(3) Add 'angular.filter' to your main module's list of dependencies.
You are looking for this solution :
StaticDataTableViewController 2.0
https://github.com/xelvenone/StaticDataTableViewController
which can show/hide/reload any static cell(s) with or without animation!
[self cell:self.outletToMyStaticCell1 setHidden:hide];
[self cell:self.outletToMyStaticCell2 setHidden:hide];
[self reloadDataAnimated:YES];
Note to always use only (reloadDataAnimated:YES/NO) (dont call [self.tableView reloadData] directly)
This doesn't use the hacky solution with setting height to 0 and allows you to animate the change and hide whole sections
Perhaps the easiest way would be to add an image, scale it, and set it to the JFrame/JPanel (in my case JPanel) but remember to "add" it to the container only after you've added the other children components.
ImageIcon background=new ImageIcon("D:\\FeedbackSystem\\src\\images\\background.jpg");
Image img=background.getImage();
Image temp=img.getScaledInstance(500,600,Image.SCALE_SMOOTH);
background=new ImageIcon(temp);
JLabel back=new JLabel(background);
back.setLayout(null);
back.setBounds(0,0,500,600);
All modern browsers (tested with Chrome 4, Firefox 3.5, IE8, Opera 10 and Safari 4) will always request a favicon.ico
unless you've specified a shortcut icon via <link>
. So if you don't explicitly specify one, it's best to always have a favicon.ico
file, to avoid a 404. Yahoo! suggests you make it small and cacheable.
And you don't have to go for a PNG just for the alpha transparency either. ICO files support alpha transparency just fine (i.e. 32-bit color), though hardly any tools allow you to create them. I regularly use Dynamic Drive's FavIcon Generator to create favicon.ico
files with alpha transparency. It's the only online tool I know of that can do it.
There's also a free Photoshop plug-in that can create them.
Something like:
DateTime today = DateTime.Today;
DateTime endOfMonth = new DateTime(today.Year, today.Month, 1).AddMonths(1).AddDays(-1);
Which is to say that you get the first day of next month, then subtract a day. The framework code will handle month length, leap years and such things.
folks who use notepad++(6.8.1) to ship shell scripts from windows to linux.
set the following in notepad ++ Edit -> EOL Conversion -> Unix/OSX format
As of Jackson 1.6, you can use:
JsonNode node = mapper.valueToTree(map);
or
JsonNode node = mapper.convertValue(object, JsonNode.class);
Source: is there a way to serialize pojo's directly to treemodel?
The following solution worked well for me. Navigate to the command prompt shortcut in the start menu:
C:\Users\ your username \AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Accessories\Command Prompt
Right click on the shortcut file to open the properties dialog. Inside the "Start in:" textbox you should see %HOMEDRIVE%%HOMEPATH%. If you want the prompt to start in C:\ just replace the variables with "C:\" (without quotes).
update
It appears that Microsoft has changed this behavior recently and so now an additional step is required. After performing the steps above copy the modified shortcut "Command Prompt" and rename it to "cmd". Then when typing "cmd" in the start menu it should once again work.
Running the app on a virtual device with system image, 'Google Play API' instead of 'Google API' will solve your issue smoothly..
Virtual devices Nexus 5x and Nexus 5 supports 'Google Play API' image.
Google Play API comes with Nougat 7.1.1 and O 8.0.
Just follow the below simple steps and make sure your pc is connected to internet.
Create a new virtual device by selecting Create Virtual Device(left-bottom corner) from Android Virtual Devices Manager.
Select the Hardware 'Nexus 5x' or 'Nexus 5'.
Download the system image 'Nougat' with Google Play or 'O' with Google Play. 'O' is the latest Android 8.0 version.
Click on Next and Finish.
Run your app again on the new virtual device and click on the 'Upgrade now ' option that shows along with the warning message.
You will be directed to the Play Store and you can update your Google Play services easily.
See your app runs smoothly!
Similar answer, but more idiomatic for ES6 perhaps:
const a = Promise.resolve(1);_x000D_
const b = Promise.reject(new Error(2));_x000D_
const c = Promise.resolve(3);_x000D_
_x000D_
Promise.all([a, b, c].map(p => p.catch(e => e)))_x000D_
.then(results => console.log(results)) // 1,Error: 2,3_x000D_
.catch(e => console.log(e));_x000D_
_x000D_
_x000D_
const console = { log: msg => div.innerHTML += msg + "<br>"};
_x000D_
<div id="div"></div>
_x000D_
Depending on the type(s) of values returned, errors can often be distinguished easily enough (e.g. use undefined
for "don't care", typeof
for plain non-object values, result.message
, result.toString().startsWith("Error:")
etc.)
This solved it for me.
from selenium import webdriver
driver = webdriver.Firefox(executable_path=r'your\path\geckodriver.exe')
driver.get('http://inventwithpython.com')
This worked for me, including recursively into submodules (perhaps that's why your -f didn't work, cause you changed a submodule inside the submodule):
git submodule update -f --recursive
I use many times the ImageMagic convert
command to convert *.tif
files to *.pdf
files.
I don't know why but today I began to receive the following error:
convert: not authorized `a.pdf' @ error/constitute.c/WriteImage/1028.
After issuing the command:
convert a.tif a.pdf
After reading the above answers I edited the file /etc/ImageMagick-6/policy.xml
and changed the line:
policy domain="coder" rights="none" pattern="PDF"
to
policy domain="coder" rights="read|write" pattern="PDF"
and now everything works fine.
I have "ImageMagick 6.8.9-9 Q16 x86_64 2018-09-28" on "Ubuntu 16.04.5 LTS".
A simpler way, if you are using .NET 3.5, is to use XDocument
and XmlSchemaSet
validation.
XmlSchemaSet schemas = new XmlSchemaSet();
schemas.Add(schemaNamespace, schemaFileName);
XDocument doc = XDocument.Load(filename);
string msg = "";
doc.Validate(schemas, (o, e) => {
msg += e.Message + Environment.NewLine;
});
Console.WriteLine(msg == "" ? "Document is valid" : "Document invalid: " + msg);
See the MSDN documentation for more assistance.
What i did to solve this problem in the terminal(Ubuntu 18.04):
openssl s_client -showcerts -servername www.github.com -connect www.github.com:443
I got two chunks of certificate chunks. And i copied the certificate chunks to my certificate file to /etc/ssl/certs/ca-certificates.crt
.
Signing the third party assembly worked for me:
http://www.codeproject.com/Tips/341645/Referenced-assembly-does-not-have-a-strong-name
EDIT: I've learned that it's helpful to post steps in case the linked article is no longer valid. All credit goes to Hiren Khirsaria:
Run visual studio command prompt and go to directory where your DLL located.
For Example my DLL is located in
D:/hiren/Test.dll
Now create the IL file using the command below.
D:/hiren> ildasm /all /out=Test.il Test.dll
(this command generates the code library)
Generate new key to sign your project.
D:/hiren> sn -k mykey.snk
Now sign your library using ilasm
command.
D:/hiren> ilasm /dll /key=mykey.snk Test.il
In Visual Studio Express 2013 for web it's hidden away in View > Other Windows > Toolbox.
No need to use a macro. Supposing your first string is in A1.
=RIGHT(A1, 4)
Drag this down and you will get your four last characters.
Edit: To be sure, if you ever have sequences like 'ABC DEF' and want the last four LETTERS and not CHARACTERS you might want to use trimspaces()
=RIGHT(TRIMSPACES(A1), 4)
Edit: As per brettdj's suggestion, you may want to check that your string is actually 4-character long or more:
=IF(TRIMSPACES(A1)>=4, RIGHT(TRIMSPACES(A1), 4), TRIMSPACES(A1))
It seems that you want to use step parameter of range function. From documentation:
range(start, stop[, step]) This is a versatile function to create lists containing arithmetic progressions. It is most often used in for loops. The arguments must be plain integers. If the step argument is omitted, it defaults to 1. If the start argument is omitted, it defaults to 0. The full form returns a list of plain integers [start, start + step, start + 2 * step, ...]. If step is positive, the last element is the largest start + i * step less than stop; if step is negative, the last element is the smallest start + i * step greater than stop. step must not be zero (or else ValueError is raised). Example:
>>> range(10) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> range(1, 11) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> range(0, 30, 5) [0, 5, 10, 15, 20, 25]
>>> range(0, 10, 3) [0, 3, 6, 9]
>>> range(0, -10, -1) [0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
>>> range(0) []
>>> range(1, 0) []
In your case to get [0,2,4] you can use:
range(0,6,2)
OR in your case when is a var:
idx = None
for i in range(len(str1)):
if idx and i < idx:
continue
for j in range(len(str2)):
if str1[i+j] != str2[j]:
break
else:
idx = i+j
what's wrong with:
int myInt = myFloat;
bear in mind this'll use the default rounding rule, which is towards zero (i.e. -3.9f becomes -3)
If you have Guava on your classpath, the following is a pretty readable alternative. Guava even has a fairly sensible custom List implementation for this case, so this shouldn't be inefficient.
for(char c : Lists.charactersOf(yourString)) {
// Do whatever you want
}
UPDATE: As @Alex noted, with Java 8 there's also CharSequence#chars
to use. Even the type is IntStream, so it can be mapped to chars like:
yourString.chars()
.mapToObj(c -> Character.valueOf((char) c))
.forEach(c -> System.out.println(c)); // Or whatever you want
It is just called the eyedropper tool. There is no shortcut key for it that I'm aware of. The only way you can use it now is by clicking on the color picker box in styles sidebar and then clicking on the page as you have already been doing.
I assume you want to pass the Order ID in. So:
CREATE PROCEDURE [dbo].[Procedure_Name]
(
@OrderID INT
) AS
BEGIN
Declare @OrderItemID AS INT
DECLARE @AppointmentID AS INT
DECLARE @PurchaseOrderID AS INT
DECLARE @PurchaseOrderItemID AS INT
DECLARE @SalesOrderID AS INT
DECLARE @SalesOrderItemID AS INT
SET @OrderItemID = (SELECT OrderItemID FROM [OrderItem] WHERE OrderID = @OrderID)
SET @AppointmentID = (SELECT AppoinmentID FROM [Appointment] WHERE OrderID = @OrderID)
SET @PurchaseOrderID = (SELECT PurchaseOrderID FROM [PurchaseOrder] WHERE OrderID = @OrderID)
END
shape()
consists of array having two arguments rows and columns.
if you search shape[0]
then it will gave you the number of rows.
shape[1]
will gave you number of columns.
this can happen when one of the projects referenced is a higher version of the .NET framework than your current project.
in addition,if you try to use CustomActionBarTheme,make sure there is
<application android:theme="@style/CustomActionBarTheme" ... />
in AndroidManifest.xml
not
<application android:theme="@android:style/CustomActionBarTheme" ... />
If you are a Vi user, you may open the file and remove the carriage return with:
:%s/\r//g
or with
:1,$ s/^M//
Note that you should type ^M by pressing ctrl-v and then ctrl-m.
Please refer the below-detailed explanation.
I have used Built-in data frame in R, called mtcars.
> mtcars
mpg cyl disp hp drat wt ...
Mazda RX4 21.0 6 160 110 3.90 2.62 ...
Mazda RX4 Wag 21.0 6 160 110 3.90 2.88 ...
Datsun 710 22.8 4 108 93 3.85 2.32 ...
............
The top line of the table is called the header which contains the column names. Each horizontal line afterward denotes a data row, which begins with the name of the row, and then followed by the actual data. Each data member of a row is called a cell.
To retrieve data in a cell, we would enter its row and column coordinates in the single square bracket "[]" operator. The two coordinates are separated by a comma. In other words, the coordinates begin with row position, then followed by a comma, and ends with the column position. The order is important.
Eg 1:- Here is the cell value from the first row, second column of mtcars.
> mtcars[1, 2]
[1] 6
Eg 2:- Furthermore, we can use the row and column names instead of the numeric coordinates.
> mtcars["Mazda RX4", "cyl"]
[1] 6
We reference a data frame column with the double square bracket "[[]]" operator.
Eg 1:- To retrieve the ninth column vector of the built-in data set mtcars, we write mtcars[[9]].
mtcars[[9]] [1] 1 1 1 0 0 0 0 0 0 0 0 ...
Eg 2:- We can retrieve the same column vector by its name.
mtcars[["am"]] [1] 1 1 1 0 0 0 0 0 0 0 0 ...
I had the same problem after I upgraded my macOS
to version 10.13.6
. I can't run composer
and php
commands. After researching for a while and trying various solutions posted online, reinstalling php using homebrew
worked.
brew reinstall [email protected]
Added on March 14th based on Ryan's comment
get the version you are currently using by running php -v
and get the right formulae (which you can find here: https://formulae.brew.sh/formula/php) to replace @7.1
in the above command.
The accepted answer by @DavidMills is quite good, but I think it can be improved upon. For one, there is no need to define the ComparisonComparer<T>
class when the framework already includes a static method Comparer<T>.Create(Comparison<T>)
. This method can be used to create an IComparison
on the fly.
Also, it casts IList<T>
to IList
which has the potential to be dangerous. In most cases that I have seen, List<T>
which implements IList
is used behind the scenes to implement IList<T>
, but this is not guaranteed and can lead to brittle code.
Lastly, the overloaded List<T>.Sort()
method has 4 signatures and only 2 of them are implemented.
List<T>.Sort()
List<T>.Sort(Comparison<T>)
List<T>.Sort(IComparer<T>)
List<T>.Sort(Int32, Int32, IComparer<T>)
The below class implements all 4 List<T>.Sort()
signatures for the IList<T>
interface:
using System;
using System.Collections.Generic;
public static class IListExtensions
{
public static void Sort<T>(this IList<T> list)
{
if (list is List<T>)
{
((List<T>)list).Sort();
}
else
{
List<T> copy = new List<T>(list);
copy.Sort();
Copy(copy, 0, list, 0, list.Count);
}
}
public static void Sort<T>(this IList<T> list, Comparison<T> comparison)
{
if (list is List<T>)
{
((List<T>)list).Sort(comparison);
}
else
{
List<T> copy = new List<T>(list);
copy.Sort(comparison);
Copy(copy, 0, list, 0, list.Count);
}
}
public static void Sort<T>(this IList<T> list, IComparer<T> comparer)
{
if (list is List<T>)
{
((List<T>)list).Sort(comparer);
}
else
{
List<T> copy = new List<T>(list);
copy.Sort(comparer);
Copy(copy, 0, list, 0, list.Count);
}
}
public static void Sort<T>(this IList<T> list, int index, int count,
IComparer<T> comparer)
{
if (list is List<T>)
{
((List<T>)list).Sort(index, count, comparer);
}
else
{
List<T> range = new List<T>(count);
for (int i = 0; i < count; i++)
{
range.Add(list[index + i]);
}
range.Sort(comparer);
Copy(range, 0, list, index, count);
}
}
private static void Copy<T>(IList<T> sourceList, int sourceIndex,
IList<T> destinationList, int destinationIndex, int count)
{
for (int i = 0; i < count; i++)
{
destinationList[destinationIndex + i] = sourceList[sourceIndex + i];
}
}
}
Usage:
class Foo
{
public int Bar;
public Foo(int bar) { this.Bar = bar; }
}
void TestSort()
{
IList<int> ints = new List<int>() { 1, 4, 5, 3, 2 };
IList<Foo> foos = new List<Foo>()
{
new Foo(1),
new Foo(4),
new Foo(5),
new Foo(3),
new Foo(2),
};
ints.Sort();
foos.Sort((x, y) => Comparer<int>.Default.Compare(x.Bar, y.Bar));
}
The idea here is to leverage the functionality of the underlying List<T>
to handle sorting whenever possible. Again, most IList<T>
implementations that I have seen use this. In the case when the underlying collection is a different type, fallback to creating a new instance of List<T>
with elements from the input list, use it to do the sorting, then copy the results back to the input list. This will work even if the input list does not implement the IList
interface.
The problem is that [...]
in python has two distinct meanings
expr [ index ]
means accessing an element of a list[ expr1, expr2, expr3 ]
means building a list of three elements from three expressionsIn your code you forgot the comma between the expressions for the items in the outer list:
[ [a, b, c] [d, e, f] [g, h, i] ]
therefore Python interpreted the start of second element as an index to be applied to the first and this is what the error message is saying.
The correct syntax for what you're looking for is
[ [a, b, c], [d, e, f], [g, h, i] ]
Take a look at Directory.GetFiles Method (String, String) (MSDN).
This method returns all the files as an array of filenames.
Only a slight change in Sat Code, set the layout after show()
method of AlertDialog
.
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setView(layout);
builder.setTitle("Title");
alertDialog = builder.create();
alertDialog.show();
alertDialog.getWindow().setLayout(600, 400); //Controlling width and height.
Or you can do it in my way.
alertDialog.show();
WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
lp.copyFrom(alertDialog.getWindow().getAttributes());
lp.width = 150;
lp.height = 500;
lp.x=-170;
lp.y=100;
alertDialog.getWindow().setAttributes(lp);
I'll try to provide a comprehensive answer here. Much of the points appear in other answers, but I found each answer incomplete, and some incorrect.
First and foremost, objectForKey:
is an NSDictionary
method, while valueForKey:
is a KVC protocol method required of any KVC complaint class - including NSDictionary.
Furthermore, as @dreamlax wrote, documentation hints that NSDictionary
implements its valueForKey:
method USING its objectForKey:
implementation. In other words - [NSDictionary valueForKey:]
calls on [NSDictionary objectForKey:]
.
This implies, that valueForKey:
can never be faster than objectForKey:
(on the same input key) although thorough testing I've done imply about 5% to 15% difference, over billions of random access to a huge NSDictionary. In normal situations - the difference is negligible.
Next: KVC protocol only works with NSString *
keys, hence valueForKey:
will only accept an NSString *
(or subclass) as key, whilst NSDictionary
can work with other kinds of objects as keys - so that the "lower level" objectForKey:
accepts any copy-able (NSCopying protocol compliant) object as key.
Last, NSDictionary's
implementation of valueForKey:
deviates from the standard behavior defined in KVC's documentation, and will NOT emit a NSUnknownKeyException
for a key it can't find - unless this is a "special" key - one that begins with '@' - which usually means an "aggregation" function key (e.g. @"@sum, @"@avg"
). Instead, it will simply return a nil when a key is not found in the NSDictionary - behaving the same as objectForKey:
Following is some test code to demonstrate and prove my notes.
- (void) dictionaryAccess {
NSLog(@"Value for Z:%@", [@{@"X":@(10), @"Y":@(20)} valueForKey:@"Z"]); // prints "Value for Z:(null)"
uint32_t testItemsCount = 1000000;
// create huge dictionary of numbers
NSMutableDictionary *d = [NSMutableDictionary dictionaryWithCapacity:testItemsCount];
for (long i=0; i<testItemsCount; ++i) {
// make new random key value pair:
NSString *key = [NSString stringWithFormat:@"K_%u",arc4random_uniform(testItemsCount)];
NSNumber *value = @(arc4random_uniform(testItemsCount));
[d setObject:value forKey:key];
}
// create huge set of random keys for testing.
NSMutableArray *keys = [NSMutableArray arrayWithCapacity:testItemsCount];
for (long i=0; i<testItemsCount; ++i) {
NSString *key = [NSString stringWithFormat:@"K_%u",arc4random_uniform(testItemsCount)];
[keys addObject:key];
}
NSDictionary *dict = [d copy];
NSTimeInterval vtotal = 0.0, ototal = 0.0;
NSDate *start;
NSTimeInterval elapsed;
for (int i = 0; i<10; i++) {
start = [NSDate date];
for (NSString *key in keys) {
id value = [dict valueForKey:key];
}
elapsed = [[NSDate date] timeIntervalSinceDate:start];
vtotal+=elapsed;
NSLog (@"reading %lu values off dictionary via valueForKey took: %10.4f seconds", keys.count, elapsed);
start = [NSDate date];
for (NSString *key in keys) {
id obj = [dict objectForKey:key];
}
elapsed = [[NSDate date] timeIntervalSinceDate:start];
ototal+=elapsed;
NSLog (@"reading %lu objects off dictionary via objectForKey took: %10.4f seconds", keys.count, elapsed);
}
NSString *slower = (vtotal > ototal) ? @"valueForKey" : @"objectForKey";
NSString *faster = (vtotal > ototal) ? @"objectForKey" : @"valueForKey";
NSLog (@"%@ takes %3.1f percent longer then %@", slower, 100.0 * ABS(vtotal-ototal) / MAX(ototal,vtotal), faster);
}
Visual Studio's search in folders is by far the fastest I've found.
I believe it intelligently searches only text (non-binary) files, and subsequent searches in the same folder are extremely fast, unlike with the other tools (likely the text files fit in the windows disk cache).
VS2010 on a regular hard drive, no SSD, takes 1 minute to search a 20GB folder with 26k files, source code and binaries mixed up. 15k files are searched - the rest are likely skipped due to being binary files. Subsequent searches in the same folder are on the order of seconds (until stuff gets evicted form the cache).
The next closest I've found for the same folder was grepWin. Around 3 minutes. I excluded files larger than 2000KB (default). The "Include binary files" setting seems to do nothing in terms of speeding up the search, it looks like binary files are still touched (bug?), but they don't show up in the search results. Subsequent searches all take the same 3 minutes - can't take advantage of hard drive cache. If I restrict to files smaller than 200k, the initial search is 2.5min and subsequent searches are on the order of seconds, about as fast as VS - in the cache.
Agent Ransack and FileSeek are both very slow on that folder, around 20min, due to searching through everything, including giant multi-gigabyte binary files. They search at about 10-20MB per second according to Resource Monitor.
UPDATE: Agent Ransack can be set to search files of certain sizes, and using the <200KB cutoff it's 1:15min for a fresh search and 5s for subsequent searches. Faster than grepWin and as fast as VS overall. It's actually pretty nice if you want to keep several searches in tabs and you don't want to pollute the VS recently searched folders list, and you want to keep the ability to search binaries, which VS doesn't seem to wanna do. Agent Ransack also creates an explorer context menu entry, so it's easy to launch from a folder. Same as grepWin but nicer UI and faster.
My new search setup is Agent Ransack for contents and Everything for file names (awesome tool, instant results!).
A quick, non-elegant but working standalone solution with inline CSS and no jQuery requirements. AFAIK it works from IE9 too.
<body style="overflow:hidden; margin:0">
<form id="form1" runat="server">
<div id="main" style="background-color:red">
<div id="content">
</div>
<div id="footer">
</div>
</div>
</form>
<script language="javascript">
function autoResizeDiv()
{
document.getElementById('main').style.height = window.innerHeight +'px';
}
window.onresize = autoResizeDiv;
autoResizeDiv();
</script>
</body>
If you want device ID information use TelephonyManager. Here is the link for that :
http://facinatingandroid.blogspot.in/2011/09/android-device-information.html
and also check this :
http://sree.cc/google/android/reading-phone-device-details-in-android
This is pretty easy to do using LINQ:
var match = pricePublicList.FirstOrDefault(p => p.Size == 200);
if (match == null)
{
// Element doesn't exist
}
I know this is a very old thread but I had the same problem which was due spaces in the images names.
e.g.
Image name: "hello o.jpg"
weirdly, by removing the spaces the function worked just fine.
Image name: "hello_o.jpg"
Take a look at the FluentEmail library. I've blogged about it here
You have a nice and fluent api for your needs:
Email.FromDefault()
.To("[email protected]")
.Subject("New order has arrived!")
.Body("The order details are…")
.Send();
In a .txt
file opened with Notepad++,
press Ctrl-F
go in the tab "Replace"
write the regex pattern \|.+
in the space Find what
and let the space Replace with blank
Then tick the choice matches newlines after the choice Regular expression
and press two times on the Replace button
Confirm in API documentation http://api.jquery.com/jQuery.each/ say:
We can break the $.each() loop at a particular iteration by making the callback function return false. Returning non-false is the same as a continue statement in a for loop; it will skip immediately to the next iteration.
and this is my example http://jsfiddle.net/r6jqP/
(function($){
$('#go').on('click',function(){
var i=0,
all=0;
$('li').each(function(){
all++;
if($('#mytext').val()=='continue')return true;
i++;
if($('#mytext').val()==$(this).html()){
return false;
}
});
alert('Iterazione : '+i+' to '+all);
});
}(jQuery));
JavaScript arrays are designed to hold data with numeric indexes. You can add named properties to them because an array is a type of object (and this can be useful when you want to store metadata about an array which holds normal, ordered, numerically indexed data), but that isn't what they are designed for.
The JSON array data type cannot have named keys on an array.
When you pass a JavaScript array to JSON.stringify
the named properties will be ignored.
If you want named properties, use an Object, not an Array.
const test = {}; // Object_x000D_
test.a = 'test';_x000D_
test.b = []; // Array_x000D_
test.b.push('item');_x000D_
test.b.push('item2');_x000D_
test.b.push('item3');_x000D_
test.b.item4 = "A value"; // Ignored by JSON.stringify_x000D_
const json = JSON.stringify(test);_x000D_
console.log(json);
_x000D_
If you have a unique column in your table (e.g. tableid) then try this.
SELECT EMAIL FROM TABLE WHERE TABLEID IN
(SELECT MAX(TABLEID), EMAIL FROM TABLE GROUP BY EMAIL)
Your pizza can have exactly three topping types:
So we order two pizzas and choose the following toppings:
Pizza Topping Topping Type
-------- ---------- -------------
1 mozzarella cheese
1 pepperoni meat
1 olives vegetable
2 mozzarella meat
2 sausage cheese
2 peppers vegetable
Wait a second, mozzarella can't be both a cheese and a meat! And sausage isn't a cheese!
We need to prevent these sorts of mistakes, to make mozzarella always be cheese. We should use a separate table for this, so we write down that fact in only one place.
Pizza Topping
-------- ----------
1 mozzarella
1 pepperoni
1 olives
2 mozzarella
2 sausage
2 peppers
Topping Topping Type
---------- -------------
mozzarella cheese
pepperoni meat
olives vegetable
sausage meat
peppers vegetable
That was the explanation that an 8 year-old might understand. Here is the more technical version.
BCNF acts differently from 3NF only when there are multiple overlapping candidate keys.
The reason is that the functional dependency X -> Y
is of course true if Y
is a subset of X
. So in any table that has only one candidate key and is in 3NF, it is already in BCNF because there is no column (either key or non-key) that is functionally dependent on anything besides that key.
Because each pizza must have exactly one of each topping type, we know that (Pizza, Topping Type) is a candidate key. We also know intuitively that a given topping cannot belong to different types simultaneously. So (Pizza, Topping) must be unique and therefore is also a candidate key. So we have two overlapping candidate keys.
I showed an anomaly where we marked mozarella as the wrong topping type. We know this is wrong, but the rule that makes it wrong is a dependency Topping -> Topping Type
which is not a valid dependency for BCNF for this table. It's a dependency on something other than a whole candidate key.
So to solve this, we take Topping Type out of the Pizzas table and make it a non-key attribute in a Toppings table.
Update! You can access the Android filesystem via Android Device Monitor. In Android Studio go to Tools >> Android >> Android Device Monitor.
Note that you can run your app in the simulator while using the Android Device Monitor. But you cannot debug you app while using the Android Device Monitor.
I was facing same issue. I solved it with retrofit. Let me show this...
If your error JSON structure are like
{
"error": {
"status": "The email field is required."
}
}
My ErrorRespnce.java
public class ErrorResponse {
@SerializedName("error")
@Expose
private ErrorStatus error;
public ErrorStatus getError() {
return error;
}
public void setError(ErrorStatus error) {
this.error = error;
}
}
And this my Error status class
public class ErrorStatus {
@SerializedName("status")
@Expose
private String status;
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
}
Now we need a class which can handle our json.
public class ErrorUtils {
public static ErrorResponse parseError (Response<?> response){
Converter<ResponseBody , ErrorResponse> converter = ApiClient.getClient().responseBodyConverter(ErrorResponse.class , new Annotation[0]);
ErrorResponse errorResponse;
try{
errorResponse = converter.convert(response.errorBody());
}catch (IOException e){
return new ErrorResponse();
}
return errorResponse;
}
}
Now we can check our response in retrofit api call
private void registrationRequest(String name , String email , String password , String c_password){
final Call<RegistrationResponce> registrationResponceCall = apiInterface.getRegistration(name , email , password , c_password);
registrationResponceCall.enqueue(new Callback<RegistrationResponce>() {
@Override
public void onResponse(Call<RegistrationResponce> call, Response<RegistrationResponce> response) {
if (response.code() == 200){
}else if (response.code() == 401){
ErrorResponse errorResponse = ErrorUtils.parseError(response);
Toast.makeText(MainActivity.this, ""+errorResponse.getError().getStatus(), Toast.LENGTH_SHORT).show();
}
}
@Override
public void onFailure(Call<RegistrationResponce> call, Throwable t) {
}
});
}
That's it now you can show your Toast
adjust his code:
Object.prototype.each = function(iterateFunc) {
var counter = 0,
keys = Object.keys(this),
currentKey,
len = keys.length;
var that = this;
var next = function() {
if (counter < len) {
currentKey = keys[counter++];
iterateFunc(currentKey, that[currentKey]);
next();
} else {
that = counter = keys = currentKey = len = next = undefined;
}
};
next();
};
({ property1: 'sdsfs', property2: 'chat' }).each(function(key, val) {
// do things
console.log(key);
});
In Netbeans 11(Gladle Project) follow these steps:
In the tab files>yourprojectname>
double click in the file "build.gladle"
than set in line "mainClassName:'yourpackagepath.YourMainClass'"
Hope this helps!
This worked for me:
File >> Project Structure >> Modules >> Dependency >> + (on left-side of window)
clicking the "+" sign will let you designate the directory where you have unpacked JavaFX's "lib" folder.
Scope is Compile (which is the default.) You can then edit this to call it JavaFX by double-clicking on the line.
then in:
Run >> Edit Configurations
Add this line to VM Options:
--module-path /path/to/JavaFX/lib --add-modules=javafx.controls
(oh and don't forget to set the SDK)
For multiple files; note the newer "multiple" attribute for input:
Form:
@using (Html.BeginForm("FileImport","Import",FormMethod.Post, new {enctype = "multipart/form-data"}))
{
<label for="files">Filename:</label>
<input type="file" name="files" multiple="true" id="files" />
<input type="submit" />
}
Controller:
[HttpPost]
public ActionResult FileImport(IEnumerable<HttpPostedFileBase> files)
{
return View();
}
For having a trasition effect like a highlighter just to highlight the text and fade off the bg color, we used the following:
.field-error {_x000D_
color: #f44336;_x000D_
padding: 2px 5px;_x000D_
position: absolute;_x000D_
font-size: small;_x000D_
background-color: white;_x000D_
}_x000D_
_x000D_
.highlighter {_x000D_
animation: fadeoutBg 3s; /***Transition delay 3s fadeout is class***/_x000D_
-moz-animation: fadeoutBg 3s; /* Firefox */_x000D_
-webkit-animation: fadeoutBg 3s; /* Safari and Chrome */_x000D_
-o-animation: fadeoutBg 3s; /* Opera */_x000D_
}_x000D_
_x000D_
@keyframes fadeoutBg {_x000D_
from { background-color: lightgreen; } /** from color **/_x000D_
to { background-color: white; } /** to color **/_x000D_
}_x000D_
_x000D_
@-moz-keyframes fadeoutBg { /* Firefox */_x000D_
from { background-color: lightgreen; }_x000D_
to { background-color: white; }_x000D_
}_x000D_
_x000D_
@-webkit-keyframes fadeoutBg { /* Safari and Chrome */_x000D_
from { background-color: lightgreen; }_x000D_
to { background-color: white; }_x000D_
}_x000D_
_x000D_
@-o-keyframes fadeoutBg { /* Opera */_x000D_
from { background-color: lightgreen; }_x000D_
to { background-color: white; }_x000D_
}
_x000D_
<div class="field-error highlighter">File name already exists.</div>
_x000D_
If you want to avoid innerHTML you can use the DOM methods to construct elements and append them to the page.
?var element = document.createElement('div');
var text = document.createTextNode('This is some text');
element.appendChild(text);
document.body.appendChild(element);??????
The Powershell way of enabling the features (Windows Server 2012 +) - trim as needed:
Install-WindowsFeature NET-Framework-Core
Install-WindowsFeature Web-Server -IncludeAllSubFeature
Install-WindowsFeature NET-Framework-Features -IncludeAllSubFeature
Install-WindowsFeature NET-Framework-45-ASPNET -IncludeAllSubFeature
Install-WindowsFeature Application-Server -IncludeAllSubFeature
Install-WindowsFeature MSMQ -IncludeAllSubFeature
Install-WindowsFeature WAS -IncludeAllSubFeature
Using pretty much any modern browser you need to learn the Network tab. See this SO post about How to debug AJAX calls.
Get all file item and filter them by suffix and then use PowerShell Excel VBA object to save the excel files to csv files.
$excelApp = New-Object -ComObject Excel.Application
$excelApp.DisplayAlerts = $false
$ExcelFiles | ForEach-Object {
$workbook = $excelApp.Workbooks.Open($_.FullName)
$csvFilePath = $_.FullName -replace "\.xlsx$", ".csv"
$workbook.SaveAs($csvFilePath, [Microsoft.Office.Interop.Excel.XlFileFormat]::xlCSV)
$workbook.Close()
}
You can find the complete sample here How to convert Excel xlsx file to csv file in batch by PowerShell
Providing the implementation details for the steps proposed by @CodesInChaos:
1) Check if there is a Byte Order Mark
2) Check if the file is valid UTF8
3) Use the local "ANSI" codepage (ANSI as Microsoft defines it)
Step 2 works because most non ASCII sequences in codepages other that UTF8 are not valid UTF8. https://stackoverflow.com/a/4522251/867248 explains the tactic in more details.
using System; using System.IO; using System.Text;
// Using encoding from BOM or UTF8 if no BOM found,
// check if the file is valid, by reading all lines
// If decoding fails, use the local "ANSI" codepage
public string DetectFileEncoding(Stream fileStream)
{
var Utf8EncodingVerifier = Encoding.GetEncoding("utf-8", new EncoderExceptionFallback(), new DecoderExceptionFallback());
using (var reader = new StreamReader(fileStream, Utf8EncodingVerifier,
detectEncodingFromByteOrderMarks: true, leaveOpen: true, bufferSize: 1024))
{
string detectedEncoding;
try
{
while (!reader.EndOfStream)
{
var line = reader.ReadLine();
}
detectedEncoding = reader.CurrentEncoding.BodyName;
}
catch (Exception e)
{
// Failed to decode the file using the BOM/UT8.
// Assume it's local ANSI
detectedEncoding = "ISO-8859-1";
}
// Rewind the stream
fileStream.Seek(0, SeekOrigin.Begin);
return detectedEncoding;
}
}
[Test]
public void Test1()
{
Stream fs = File.OpenRead(@".\TestData\TextFile_ansi.csv");
var detectedEncoding = DetectFileEncoding(fs);
using (var reader = new StreamReader(fs, Encoding.GetEncoding(detectedEncoding)))
{
// Consume your file
var line = reader.ReadLine();
...
You can add an conditional statement. If your array goes beyond index, then break and print the rest of the file.
Note that the OpenSSL CLI uses a weak non-standard algorithm to convert the passphrase to a key, and installing GPG results in various files added to your home directory and a gpg-agent background process running. If you want maximum portability and control with existing tools, you can use PHP or Python to access the lower-level APIs and directly pass in a full AES Key and IV.
Example PHP invocation via Bash:
IV='c2FtcGxlLWFlcy1pdjEyMw=='
KEY='Twsn8eh2w2HbVCF5zKArlY+Mv5ZwVyaGlk5QkeoSlmc='
INPUT=123456789023456
ENCRYPTED=$(php -r "print(openssl_encrypt('$INPUT','aes-256-ctr',base64_decode('$KEY'),OPENSSL_ZERO_PADDING,base64_decode('$IV')));")
echo '$ENCRYPTED='$ENCRYPTED
DECRYPTED=$(php -r "print(openssl_decrypt('$ENCRYPTED','aes-256-ctr',base64_decode('$KEY'),OPENSSL_ZERO_PADDING,base64_decode('$IV')));")
echo '$DECRYPTED='$DECRYPTED
This outputs:
$ENCRYPTED=nzRi252dayEsGXZOTPXW
$DECRYPTED=123456789023456
You could also use PHP's openssl_pbkdf2
function to convert a passphrase to a key securely.
None of the css trick worked for me (in my case the fb-like box was pulled right with "float:right"). However, what worked without any additional tricks is an IFRAME version of the button code. I.e.:
<iframe src="//www.facebook.com/plugins/like.php?href=..."
scrolling="no" frameborder="0"
style="border:none; overflow:hidden; width:71px; height:21px;"
allowTransparency="true">
</iframe>
(Note custom width in style, and no need to include additional javascript.)
With Simple Java Mail 5.0.0 (simplejavamail.org) it is very straightforward and the library will take care of all the Session properties for you.
Here's an example using Google's SMTP servers:
Email email = EmailBuilder.startingBlank()
.from("lollypop", "[email protected]")
.to("C.Cane", "[email protected]")
.withSubject("hey")
.withPlainText("We should meet up!")
.withHTMLText("<b>We should meet up!</b>")
.buildEmail();
MailerBuilder.withSMTPServer("smtp.gmail.com", 25, "user", "pass", SMTP_TLS)
.buildMailer()
.sendMail(email);
MailerBuilder.withSMTPServer("smtp.gmail.com", 587, "user", "pass", SMTP_TLS)
.buildMailer()
.sendMail(email);
MailerBuilder.withSMTPServer("smtp.gmail.com", 465, "user", "pass", SMTP_SSL)
.buildMailer()
.sendMail(email);
If you have two-factor login turned on, you need to generate an application specific password from your Google account.
First of all, most browsers has this function by default. And why do you need this at all? Why not to keep the form synced? I mean, save it on any change without waiting any submitting from user. Like Google Contacts do. Of course if only all fields in form are mandatory. Users do not like when them force to fill something up without the opportunity to go away to think if they need it. :)
datetime have comparison capability
>>> import datetime
>>> import time
>>> a = datetime.datetime.now()
>>> time.sleep(2.0)
>>> b = datetime.datetime.now()
>>> print a < b
True
>>> print a == b
False
From the dojo API documentation:
dojo.html._emptyNode(node);
I had originally asked myself the question "Do I need a PDB file deployed to my customer's machine?", and after reading this post, decided to exclude the file.
Everything worked fine, until today, when I was trying to figure out why a message box containing an Exception.StackTrace
was missing the file and line number information - necessary for troubleshooting the exception. I re-read this post and found the key nugget of information: that although the PDB is not necessary for the app to run, it is necessary for the file and line numbers to be present in the StackTrace
string. I included the PDB file in the executable folder and now all is fine.
Just adding for who might need.. Don't forget to alter the table!
ALTER TABLE table_name ADD FULLTEXT(column_name);
There is no need to flag classes as Serializable and in our tests using the Newtonsoft JsonSerializer even faster than using BinaryFormatter. With extension methods usable on every object.
Standard .NET JavascriptSerializer option:
public static T DeepCopy<T>(this T value)
{
JavaScriptSerializer js = new JavaScriptSerializer();
string json = js.Serialize(value);
return js.Deserialize<T>(json);
}
Faster option using Newtonsoft JSON:
public static T DeepCopy<T>(this T value)
{
string json = JsonConvert.SerializeObject(value);
return JsonConvert.DeserializeObject<T>(json);
}
CSRF protection
TYPES OF CSRF USAGE
IN FORM
<form>
@csrf
</form>
or
<input type="hidden" name="token" value="{{ form_token() }}" />
META TAG
<meta name="csrf-token" content="{{ csrf_token() }}">
AJAX
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
SESSION
use Illuminate\Http\Request;
Route::get('/token', function (Request $request) {
$token = $request->session()->token();
$token = csrf_token();
// ...
});
MIDDLEWARE
App\Providers\RouteServiceProvider
<?php
namespace App\Http\Middleware;
use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as Middleware;
class VerifyCsrfToken extends Middleware
{
/**
* The URIs that should be excluded from CSRF verification.
*
* @var array
*/
protected $except = [
'stripe/*',
'http://example.com/foo/bar',
'http://example.com/foo/*',
];
}
I don't think I've seen this solution yet:
boolean atLeast(int howMany, boolean[] boolValues) {
// check params for valid values
int counter = 0;
for (boolean b : boolValues) {
if (b) {
counter++;
if (counter == howMany) {
return true;
}
}
}
return false;
}
Its advantage is that once it reaches the number that you're looking for, it breaks. So if this was "at least 2 out of this 1,000,000 values are true" where the first two are actually true, then it should go faster than some of the more "normal" solutions.
Maybe try this:
<%= link_to "Add to cart",
:controller => "car",
:action => "add_to_cart",
:car => car.attributes %>
But I'd really like to see where the car object is getting setup for this page (i.e., the rest of the view).
Even if the test gurus say that we should not do it: I do. In some context it makes a lot of sense to have parameters to drive the test in the right direction, for example:
For me, the use of the environment variable is good enough for this puprose because you do not have to write dedicated code to pass your parameters around; it is supported by Python. It is clean and simple.
Of course, I'm not advocating for fully parametrizable tests. But we have to be pragmatic and, as I said, in some context you need a parameter or two. We should not abouse of it :)
import os
import unittest
class MyTest(unittest.TestCase):
def setUp(self):
self.var1 = os.environ["VAR1"]
self.var2 = os.environ["VAR2"]
def test_01(self):
print("var1: {}, var2: {}".format(self.var1, self.var2))
Then from the command line (tested on Linux)
$ export VAR1=1
$ export VAR2=2
$ python -m unittest MyTest
var1: 1, var2: 2
.
----------------------------------------------------------------------
Ran 1 test in 0.000s
OK
The subset command is not necessary. Just use data frame indexing
studentdata[studentdata$Drink == 'water',]
Read the warning from ?subset
This is a convenience function intended for use interactively. For programming it is better to use the standard subsetting functions like ‘[’, and in particular the non-standard evaluation of argument ‘subset’ can have unanticipated consequences.
On express 3 you can use directly res.json({foo:bar})
res.json({ msgId: msg.fileName })
See the documentation
I believe the author was looking for an equivalent method via the IDE that would generate the code behind and make sure all parameters were in place, etc. Found this from MS:
Creating Event Handlers on the Windows Forms Designer
Coming from a VB background myself, this is what I was looking for, here is the brief version for the click adverse:
- Click the form or control that you want to create an event handler for.
- In the Properties window, click the Events button
- In the list of available events, click the event that you want to create an event handler for.
- In the box to the right of the event name, type the name of the handler and press ENTER
First you need to ask, why you want to do this?
But it's possible via:
t = ('275', '54000', '0.0', '5000.0', '0.0')
lst = list(t)
lst[0] = '300'
t = tuple(lst)
But if you're going to need to change things, you probably are better off keeping it as a list
As far as I know, by using only Docker this is not possible. You need some DNS to map container ip:s to hostnames.
If you want out of the box solution. One solution is to use for example Kontena. It comes with network overlay technology from Weave and this technology is used to create virtual private LAN networks for each service and every service can be reached by service_name.kontena.local-address
.
Here is simple example of Wordpress application's YAML file where Wordpress service connects to MySQL server with wordpress-mysql.kontena.local address:
wordpress:
image: wordpress:4.1
stateful: true
ports:
- 80:80
links:
- mysql:wordpress-mysql
environment:
- WORDPRESS_DB_HOST=wordpress-mysql.kontena.local
- WORDPRESS_DB_PASSWORD=secret
mysql:
image: mariadb:5.5
stateful: true
environment:
- MYSQL_ROOT_PASSWORD=secret
Double equals ==
will always check based on object identity, regardless of the objects' implementation of hashCode or equals. Of course - make sure the object references you are comparing are volatile
(in a 1.5+ JVM).
If you really must have the original Object toString result (although it's not the best solution for your example use-case), the Commons Lang library has a method ObjectUtils.identityToString(Object) that will do what you want. From the JavaDoc:
public static java.lang.String identityToString(java.lang.Object object)
Gets the toString that would be produced by Object if a class did not override toString itself. null will return null.
ObjectUtils.identityToString(null) = null
ObjectUtils.identityToString("") = "java.lang.String@1e23"
ObjectUtils.identityToString(Boolean.TRUE) = "java.lang.Boolean@7fa"
Welcome to Java! This Nodes are like a blocks, they must be assembled to do amazing things! In this particular case, your nodes can represent a list, a linked list, You can see an example here:
public class ItemLinkedList {
private ItemInfoNode head;
private ItemInfoNode tail;
private int size = 0;
public int getSize() {
return size;
}
public void addBack(ItemInfo info) {
size++;
if (head == null) {
head = new ItemInfoNode(info, null, null);
tail = head;
} else {
ItemInfoNode node = new ItemInfoNode(info, null, tail);
this.tail.next =node;
this.tail = node;
}
}
public void addFront(ItemInfo info) {
size++;
if (head == null) {
head = new ItemInfoNode(info, null, null);
tail = head;
} else {
ItemInfoNode node = new ItemInfoNode(info, head, null);
this.head.prev = node;
this.head = node;
}
}
public ItemInfo removeBack() {
ItemInfo result = null;
if (head != null) {
size--;
result = tail.info;
if (tail.prev != null) {
tail.prev.next = null;
tail = tail.prev;
} else {
head = null;
tail = null;
}
}
return result;
}
public ItemInfo removeFront() {
ItemInfo result = null;
if (head != null) {
size--;
result = head.info;
if (head.next != null) {
head.next.prev = null;
head = head.next;
} else {
head = null;
tail = null;
}
}
return result;
}
public class ItemInfoNode {
private ItemInfoNode next;
private ItemInfoNode prev;
private ItemInfo info;
public ItemInfoNode(ItemInfo info, ItemInfoNode next, ItemInfoNode prev) {
this.info = info;
this.next = next;
this.prev = prev;
}
public void setInfo(ItemInfo info) {
this.info = info;
}
public void setNext(ItemInfoNode node) {
next = node;
}
public void setPrev(ItemInfoNode node) {
prev = node;
}
public ItemInfo getInfo() {
return info;
}
public ItemInfoNode getNext() {
return next;
}
public ItemInfoNode getPrev() {
return prev;
}
}
}
EDIT:
Declare ItemInfo as this:
public class ItemInfo {
private String name;
private String rfdNumber;
private double price;
private String originalPosition;
public ItemInfo(){
}
public ItemInfo(String name, String rfdNumber, double price, String originalPosition) {
this.name = name;
this.rfdNumber = rfdNumber;
this.price = price;
this.originalPosition = originalPosition;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getRfdNumber() {
return rfdNumber;
}
public void setRfdNumber(String rfdNumber) {
this.rfdNumber = rfdNumber;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public String getOriginalPosition() {
return originalPosition;
}
public void setOriginalPosition(String originalPosition) {
this.originalPosition = originalPosition;
}
}
Then, You can use your nodes inside the linked list like this:
public static void main(String[] args) {
ItemLinkedList list = new ItemLinkedList();
for (int i = 1; i <= 10; i++) {
list.addBack(new ItemInfo("name-"+i, "rfd"+i, i, String.valueOf(i)));
}
while (list.size() > 0){
System.out.println(list.removeFront().getName());
}
}
you could try this:
1. Open the "Android Virtual device Manager"
2. Select from one the listed devices there and run it.
3. Right click your Android App -> Run As -> Android Application
It worked for me. I tried this on an emulator in eclipse. It takes a while before the app is run. For me it took 33 seconds. Wait until the message in the console says "Success!"
Here are some examples:
> z$mean <- rowMeans(subset(z, select = c(x, y)), na.rm = TRUE)
> z
w x y mean
1 5 1 1 1
2 6 2 2 2
3 7 3 3 3
4 8 4 NA 4
weighted mean
> z$y <- rev(z$y)
> z
w x y mean
1 5 1 NA 1
2 6 2 3 2
3 7 3 2 3
4 8 4 1 4
>
> weight <- c(1, 2) # x * 1/3 + y * 2/3
> z$wmean <- apply(subset(z, select = c(x, y)), 1, function(d) weighted.mean(d, weight, na.rm = TRUE))
> z
w x y mean wmean
1 5 1 NA 1 1.000000
2 6 2 3 2 2.666667
3 7 3 2 3 2.333333
4 8 4 1 4 2.000000
Use an ordered broadcast. See http://android-developers.blogspot.nl/2011/01/processing-ordered-broadcasts.html
In your activity, register a receiver in onStart, unregister in onStop. Now when for example a service needs to handle something that the activity might be able to do better, send an ordered broadcast from the service (with a default handler in the service itself). You can now respond in the activity when it is running. The service can check the result data to see if the broadcast was handled, and if not take appropriate action.
There's a strong chance that the privileges to select from table1 have been granted to a role, and the role has been granted to you. Privileges granted to a role are not available to PL/SQL written by a user, even if the user has been granted the role.
You see this a lot for users that have been granted the dba role on objects owned by sys. A user with dba role will be able to, say, SELECT * from V$SESSION
, but will not be able to write a function that includes SELECT * FROM V$SESSION
.
The fix is to grant explicit permissions on the object in question to the user directly, for example, in the case above, the SYS user has to GRANT SELECT ON V_$SESSION TO MyUser;
=============UPDATE=============
Since Android Studio introduce a new build system: Gradle. Android developers can now use a simple, declarative DSL to have access to a single, authoritative build that powers both the Android Studio IDE and builds from the command-line.
Edit your build.gradle
like this:
apply plugin: 'android'
android {
compileSdkVersion 19
buildToolsVersion "19.0.3"
defaultConfig {
minSdkVersion 18
targetSdkVersion 19
versionCode 1
versionName "1.0"
}
buildTypes {
release {
runProguard false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:support-v4:21.+'
}
NOTES: Use + in compile 'com.android.support:support-v4:21.+'
so that gradle can always use the newest version.
==========DEPRECATED==========
Because Android Studio is based on IntelliJ IDEA, so the procedure is just same like on IntelliJ IDEA 12 CE
1.Open Project Structure (Press F4 on PC and Command+; on MAC) on your project).
2.Select Modules on the left pane.
3.Choose your project and you will see Dependencies TAB above the third Column.
4.Click on the plus sign in the bottom. Then a tree-based directory chooser dialog will pop up, navigate to your folder containing android-support-v4.jar, press OK.
5.Press OK.
I've just put together what you may be looking for: http://www.graphdracula.net
It's JavaScript with directed graph layouting, SVG and you can even drag the nodes around. Still needs some tweaking, but is totally usable. You create nodes and edges easily with JavaScript code like this:
var g = new Graph();
g.addEdge("strawberry", "cherry");
g.addEdge("cherry", "apple");
g.addEdge("id34", "cherry");
I used the previously mentioned Raphael JS library (the graffle example) plus some code for a force based graph layout algorithm I found on the net (everything open source, MIT license). If you have any remarks or need a certain feature, I may implement it, just ask!
You may want to have a look at other projects, too! Below are two meta-comparisons:
SocialCompare has an extensive list of libraries, and the "Node / edge graph" line will filter for graph visualization ones.
DataVisualization.ch has evaluated many libraries, including node/graph ones. Unfortunately there's no direct link so you'll have to filter for "graph":
Here's a list of similar projects (some have been already mentioned here):
vis.js supports many types of network/edge graphs, plus timelines and 2D/3D charts. Auto-layout, auto-clustering, springy physics engine, mobile-friendly, keyboard navigation, hierarchical layout, animation etc. MIT licensed and developed by a Dutch firm specializing in research on self-organizing networks.
Cytoscape.js - interactive graph analysis and visualization with mobile support, following jQuery conventions. Funded via NIH grants and developed by by @maxkfranz (see his answer below) with help from several universities and other organizations.
The JavaScript InfoVis Toolkit - Jit, an interactive, multi-purpose graph drawing and layout framework. See for example the Hyperbolic Tree. Built by Twitter dataviz architect Nicolas Garcia Belmonte and bought by Sencha in 2010.
D3.js Powerful multi-purpose JS visualization library, the successor of Protovis. See the force-directed graph example, and other graph examples in the gallery.
Plotly's JS visualization library uses D3.js with JS, Python, R, and MATLAB bindings. See a nexworkx example in IPython here, human interaction example here, and JS Embed API.
sigma.js Lightweight but powerful library for drawing graphs
jsPlumb jQuery plug-in for creating interactive connected graphs
Springy - a force-directed graph layout algorithm
Processing.js Javascript port of the Processing library by John Resig
JS Graph It - drag'n'drop boxes connected by straight lines. Minimal auto-layout of the lines.
RaphaelJS's Graffle - interactive graph example of a generic multi-purpose vector drawing library. RaphaelJS can't layout nodes automatically; you'll need another library for that.
JointJS Core - David Durman's MPL-licensed open source diagramming library. It can be used to create either static diagrams or fully interactive diagramming tools and application builders. Works in browsers supporting SVG. Layout algorithms not-included in the core package
mxGraph Previously commercial HTML 5 diagramming library, now available under Apache v2.0. mxGraph is the base library used in draw.io.
GoJS Interactive graph drawing and layout library
yFiles for HTML Commercial graph drawing and layout library
KeyLines Commercial JS network visualization toolkit
ZoomCharts Commercial multi-purpose visualization library
Syncfusion JavaScript Diagram Commercial diagram library for drawing and visualization.
Cytoscape Web Embeddable JS Network viewer (no new features planned; succeeded by Cytoscape.js)
Canviz JS renderer for Graphviz graphs. Abandoned in Sep 2013.
arbor.js Sophisticated graphing with nice physics and eye-candy. Abandoned in May 2012. Several semi-maintained forks exist.
jssvggraph "The simplest possible force directed graph layout algorithm implemented as a Javascript library that uses SVG objects". Abandoned in 2012.
jsdot Client side graph drawing application. Abandoned in 2011.
Protovis Graphical Toolkit for Visualization (JavaScript). Replaced by d3.
Moo Wheel Interactive JS representation for connections and relations (2008)
JSViz 2007-era graph visualization script
dagre Graph layout for JavaScript
Graphviz Sophisticated graph visualization language
Flare Beautiful and powerful Flash based graph drawing
NodeBox Python Graph Visualization
Simply compare the width of the documents root element (i.e. html element) against the inner portion of the window:
if ((window.innerWidth - document.documentElement.clientWidth) >0) console.log('V-scrollbar active')
If you also need to know the scrollbar width:
vScrollbarWidth = window.innerWidth - document.documentElement.clientWidth;
Machines don't understand English or any other languages, they understand only byte code, which they have to be compiled (e.g., C/C++, Java) or interpreted (e.g., Ruby, Python), the .pyc is a cached version of the byte code. https://www.geeksforgeeks.org/difference-between-compiled-and-interpreted-language/ Here is a quick read on what is the difference between compiled language vs interpreted language, TLDR is interpreted language does not require you to compile all the code before run time and thus most of the time they are not strict on typing etc.
In previous replies are drawbacks. Offers its own version with the selection in the drop down list the desired item:
private ConnectSqlForm()
{
InitializeComponent();
cmbDatabases.TextChanged += UpdateAutoCompleteComboBox;
cmbDatabases.KeyDown += AutoCompleteComboBoxKeyPress;
}
private void UpdateAutoCompleteComboBox(object sender, EventArgs e)
{
var comboBox = sender as ComboBox;
if(comboBox == null)
return;
string txt = comboBox.Text;
string foundItem = String.Empty;
foreach(string item in comboBox.Items)
if (!String.IsNullOrEmpty(txt) && item.ToLower().StartsWith(txt.ToLower()))
{
foundItem = item;
break;
}
if (!String.IsNullOrEmpty(foundItem))
{
if (String.IsNullOrEmpty(txt) || !txt.Equals(foundItem))
{
comboBox.TextChanged -= UpdateAutoCompleteComboBox;
comboBox.Text = foundItem;
comboBox.DroppedDown = true;
Cursor.Current = Cursors.Default;
comboBox.TextChanged += UpdateAutoCompleteComboBox;
}
comboBox.SelectionStart = txt.Length;
comboBox.SelectionLength = foundItem.Length - txt.Length;
}
else
comboBox.DroppedDown = false;
}
private void AutoCompleteComboBoxKeyPress(object sender, KeyEventArgs e)
{
var comboBox = sender as ComboBox;
if (comboBox != null && comboBox.DroppedDown)
{
switch (e.KeyCode)
{
case Keys.Back:
int sStart = comboBox.SelectionStart;
if (sStart > 0)
{
sStart--;
comboBox.Text = sStart == 0 ? "" : comboBox.Text.Substring(0, sStart);
}
e.SuppressKeyPress = true;
break;
}
}
}
Have you tried adding the verbose (-v
) operator when you clone?
git clone -v git://git.kernel.org/pub/scm/.../linux-2.6 my2.6
What I use for debugging purposes is running the gradle task with stacktrace directly in terminal. Then you don't affect your normal compiles.
From your project root directory, via terminal you can use:
./gradlew assembleMyBuild --stacktrace
tick_params is very useful for setting tick properties. Labels can be moved to the top with:
ax.tick_params(labelbottom=False,labeltop=True)
Here is one with IEnumerable
and a Recursive Reverse method though it is no faster than the while loop in the Reverse
method both are O(n):
public class LinkedList<T> : IEnumerable
{
private Node<T> _head = null;
public Node<T> Add(T value)
{
var node = new Node<T> {Value = value};
if (_head == null)
{
_head = node;
}
else
{
var current = _head;
while (current.Next != null)
{
current = current.Next;
}
current.Next = node; //new head
}
return node;
}
public T Remove(Node<T> node)
{
if (_head == null)
return node.Value;
if (_head == node)
{
_head = _head.Next;
node.Next = null;
return node.Value;
}
var current = _head;
while (current.Next != null)
{
if (current.Next == node)
{
current.Next = node.Next;
return node.Value;
}
current = current.Next;
}
return node.Value;
}
public void Reverse()
{
Node<T> prev = null;
var current = _head;
if (current == null)
return;
while (current != null)
{
var next = current.Next;
current.Next = prev;
prev = current;
current = next;
}
_head = prev;
}
public void ReverseRecurisve()
{
reverseRecurive(_head, null);
}
private void reverseRecurive(Node<T> current, Node<T> prev)
{
if (current.Next == null)
{
_head = current;
_head.Next = prev;
return;
}
var next = current.Next;
current.Next = prev;
reverseRecurive(next, current);
}
public IEnumerator<T> Enumerator()
{
var current = _head;
while (current != null)
{
yield return current.Value;
current = current.Next;
}
}
public IEnumerator GetEnumerator()
{
return Enumerator();
}
}
public class Node<T>
{
public T Value { get; set; }
public Node<T> Next { get; set; }
}
extern tells the compiler that this data is defined somewhere and will be connected with the linker.
With the help of the responses here and talking to a few friends here is the practical example of a use of extern.
Example 1 - to show a pitfall:
File stdio.h:
int errno;
/* other stuff...*/
myCFile1.c:
#include <stdio.h>
Code...
myCFile2.c:
#include <stdio.h>
Code...
If myCFile1.o and myCFile2.o are linked, each of the c files have separate copies of errno. This is a problem as the same errno is supposed to be available in all linked files.
Example 2 - The fix.
File stdio.h:
extern int errno;
/* other stuff...*/
File stdio.c
int errno;
myCFile1.c:
#include <stdio.h>
Code...
myCFile2.c:
#include <stdio.h>
Code...
Now if both myCFile1.o and MyCFile2.o are linked by the linker they will both point to the same errno. Thus, solving the implementation with extern.
In JDK 8 source can be found in /src.zip. Now in some intermediate releases this zip was missing but again it is available.
make sure that you select source as well from installation wizard.
Use the built-in Javascript function called map. .map() will do the exact thing you're looking for!
In addition to @Khanetor's answer, for those who are working with cross-origin requests: credentials: 'include'
Sample JSON fetch request:
fetch(url, {
method: 'GET',
credentials: 'include'
})
.then((response) => response.json())
.then((json) => {
console.log('Gotcha');
}).catch((err) => {
console.log(err);
});
https://developer.mozilla.org/en-US/docs/Web/API/Request/credentials
To add controls dynamically to the form, do the following code. Here we are creating textbox controls to add dynamically.
Public Class Form1
Private m_TextBoxes() As TextBox = {}
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles Button1.Click
' Get the index for the new control.
Dim i As Integer = m_TextBoxes.Length
' Make room.
ReDim Preserve m_TextBoxes(i)
' Create and initialize the control.
m_TextBoxes(i) = New TextBox
With m_TextBoxes(i)
.Name = "TextBox" & i.ToString()
If m_TextBoxes.Length < 2 Then
' Position the first one.
.SetBounds(8, 8, 100, 20)
Else
' Position subsequent controls.
.Left = m_TextBoxes(i - 1).Left
.Top = m_TextBoxes(i - 1).Top + m_TextBoxes(i - _
1).Height + 4
.Size = m_TextBoxes(i - 1).Size
End If
' Save the control's index in the Tag property.
' (Or you can get this from the Name.)
.Tag = i
End With
' Give the control an event handler.
AddHandler m_TextBoxes(i).TextChanged, AddressOf TextBox_TextChanged
' Add the control to the form.
Me.Controls.Add(m_TextBoxes(i))
End Sub
'When you enter text in one of the TextBoxes, the TextBox_TextChanged event
'handler displays the control's name and its current text.
Private Sub TextBox_TextChanged(ByVal sender As _
System.Object, ByVal e As System.EventArgs)
' Display the current text.
Dim txt As TextBox = DirectCast(sender, TextBox)
Debug.WriteLine(txt.Name & ": [" & txt.Text & "]")
End Sub
End Class
You can find answer in depth here.
But in general with float
you need to be aware and take care of the surrounding elements and inline-block
simple way to line elements.
Thanks
textTitle.replace(/ /g, '%20');
String url = "jdbc:mysql://localhost:3306/dbname";
String user = "user";
String pass = "pass";
Class.forName ("com.mysql.jdbc.Driver").newInstance ();
Connection conn = DriverManager.getConnection (url, user, pass);
3306
is the default port for mysql.
If you are using Java 7 then there is no need to even add the Class.forName("com.mysql.jdbc.Driver").newInstance ();
statement.Automatic Resource Management (ARM) is added in JDBC 4.1 which comes by default in Java 7.
The general format for a JDBC URL for connecting to a MySQL server is as follows, with items in square brackets ([ ]) being optional:
jdbc:mysql://[host1][:port1][,[host2][:port2]]...[/[database]] »
[?propertyName1=propertyValue1[&propertyName2=propertyValue2]...]
For me, select2.min.js
file worked instead of select2.full.min.js
. I have manually define files which I have copied from dist folder that I got from github page. Also make sure that you have one jQuery(document).ready(...)
definition and jquery file imported before select2 file.
This is indeed rather odd.
If aSourceDictionary
were a dictionary, I don't believe it is possible for your code to fail in the manner you describe.
This leads to two hypotheses:
The code you're actually running is not identical to the code in your question (perhaps an earlier or later version?)
aSourceDictionary
is in fact not a dictionary, but is some other structure (for example, a list).
FragmentActivity
is part of the support library, while Activity
is the framework's default class. They are functionally equivalent.
You should always use FragmentActivity
and android.support.v4.app.Fragment
instead of the platform default Activity
and android.app.Fragment
classes. Using the platform defaults mean that you are relying on whatever implementation of fragments is used in the device you are running on. These are often multiple years old, and contain bugs that have since been fixed in the support library.
If you use Robert Harder's Base64 utility, then you can do:
InputStream is = new Base64.InputStream(cph);
Or with sun's JRE, you can do:
InputStream is = new
com.sun.xml.internal.messaging.saaj.packaging.mime.util.BASE64DecoderStream(cph)
However don't rely on that class continuing to be a part of the JRE, or even continuing to do what it seems to do today. Sun say not to use it.
There are other Stack Overflow questions about Base64 decoding, such as this one.
when we use the
php artisan serve
it will start with the default HTTP-server port mostly it will be 8000
when we want to run the more site in the localhost we have to change the port. Just add the --port argument:
php artisan serve --port=8081
Abstraction and Encapsulation are confusing terms and dependent on each other. Let's take it by an example:
public class Person
{
private int Id { get; set; }
private string Name { get; set; }
private string CustomName()
{
return "Name:- " + Name + " and Id is:- " + Id;
}
}
When you created Person class, you did encapsulation by writing properties and functions together(Id, Name, CustomName). You perform abstraction when you expose this class to client as
Person p = new Person();
p.CustomName();
Your client doesn't know anything about Id and Name in this function. Now if, your client wants to know the last name as well without disturbing the function call. You do encapsulation by adding one more property into Person class like this.
public class Person
{
private int Id { get; set; }
private string Name { get; set; }
private string LastName {get; set;}
public string CustomName()
{
return "Name:- " + Name + " and Id is:- " + Id + "last name:- " + LastName;
}
}
Look, even after addding an extra property in class, your client doesn't know what you did to your code. This is where you did abstraction.
I had a similar problem with another library and the reason why it didn't found it, was that I didn't run the make install (after running ./configure and make) for that library. The make install may require root privileges (in this case use: sudo make install). After running the make install you should have the so files in the correct folder, i.e. here /usr/local/lib and not in the folder mentioned by you.
I had the same issue when I was using GIT bash to merge master branch in to my feature branch. I followed the following steps to overcome this.
If you want a command-line solution, you can use the ImageMagick convert
utility:
convert input.png -transparent red output.png
At least the way I've done this is as follows:
If you have a nested src tree (say com.test.myclass.MyClass) and you are compiling from a root directory you need to do the following:
1) when you create the jar (usually put this in a script): jar -cvfm my.jar com/test/myclass/manifest.txt com/test/myclass/MyClass.class
2) The manifest should look like:
Mainfest-version: 1.0 Main-Class: com.test.myclass.MyClass Class-Path: . my.jar
3) Now you can run the jar from anywhere like this:
java -jar my.jar
Hope this helps someone
Because the act of acquiring the position and getting the element from the given position naturally requires some locking (you can't have the list have structural changes between those two operations).
The very idea of a concurrent collection is that each operation on its own is atomic and can be done without explicit locking/synchronization.
Therefore getting the element at position n
from a given List
as an atomic operation doesn't make too much sense in a situation where concurrent access is anticipated.
I would do it in the simplest way, so anyone can understand what happens, even if there are smarter ways:
my $text = "";
while (my $line = <FILE>) {
$text .= $line;
}
Another solution (but it requires jQueryUI as pointed out by Richard Neil Ilagan in comments) :-
addClass, removeClass and toggleClass also accepts a second argument; the time duration to go from one state to the other.
$(this).addClass('abc',1000);
See jsfiddle:- http://jsfiddle.net/6hvZT/1/
Try following command sequence on Ubuntu terminal:
sudo apt-get install software-properties-common
sudo apt-add-repository universe
sudo apt-get update
sudo apt-get install python-pip
Whithout JavaScript, the only way I could play without errors:
<!--[if lte IE 9]>
<!-- PUT HERE A FLASH PLAYER WITH video.flv -->
<![endif]-->
<!--[if gt IE 9]><!-->
<video controls class="video">
<source src="video.mp4" type="video/mp4">
<!-- REPEAT FLASH PLAYER CODE HERE -->
</video>
<!--<![endif]-->