Check this out: http://qrdroid.com/web-masters.php
You can create a link in your web form, something like:
http://qrdroid.com/scan?q=http://www.your-site.com/your-form.php?code={CODE}
When somebody clicks that link, an app to scan the code will be opened. After the user scans the code, http://www.your-site.com/your-form.php?code={CODE} will be automatically called. You can then make your-form.php read the parameter code to prepopulate the field.
You can use this quick start guide http://shyyko.wordpress.com/2013/07/30/zxing-with-android-quick-start/ with simple example project to build android app without IntentIntegrator.
Step by step to setup zxing 3.2.1 in eclipse
There are two parts in building barcode scanning feature, one capturing barcode image using camera and second extracting barcode value from the image.
Barcode image can be captured from your app using camera app and barcode value can be extracted using Firebase Machine Learning Kit barcode scanning API.
Here is an example app https://www.zoftino.com/android-barcode-scanning-example
If you want to create a li
element for each input/name, then you have to create it, with document.createElement
[MDN].
Give the list the ID:
<ol id="demo"></ol>
and get a reference to it:
var list = document.getElementById('demo');
In your event handler, create a new list element with the input value as content and append to the list with Node.appendChild
[MDN]:
var firstname = document.getElementById('firstname').value;
var entry = document.createElement('li');
entry.appendChild(document.createTextNode(firstname));
list.appendChild(entry);
You can do this with interfaces in Java 8.
This is the official documentation about it:
https://docs.oracle.com/javase/tutorial/java/IandI/defaultmethods.html
I would simply do it with :
DELETE FROM mytest.instance;
ALTER TABLE mytest.instance AUTO_INCREMENT = 1;
There is Java Plugin to use string interpolation in Java (like in Kotlin, JavaScript). Supports Java 8, 9, 10, 11…? https://github.com/antkorwin/better-strings
Using variables in string literals:
int a = 3;
int b = 4;
System.out.println("${a} + ${b} = ${a+b}");
Using expressions:
int a = 3;
int b = 4;
System.out.println("pow = ${a * a}");
System.out.println("flag = ${a > b ? true : false}");
Using functions:
@Test
void functionCall() {
System.out.println("fact(5) = ${factorial(5)}");
}
long factorial(int n) {
long fact = 1;
for (int i = 2; i <= n; i++) {
fact = fact * i;
}
return fact;
}
For more info, please read the project README.
Late to the game, but here's a powerful HOC pattern for overriding a component by providing it as a prop. It's simple and elegant.
Suppose MyComponent
renders a fictional A
component but you want to allow for a custom override of A
, in this example B
, which wraps A
in a <div>...</div>
and also appends "!" to the text prop:
import A from 'fictional-tooltip';
const MyComponent = props => (
<props.A text="World">Hello</props.A>
);
MyComponent.defaultProps = { A };
const B = props => (
<div><A {...props} text={props.text + '!'}></div>
);
ReactDOM.render(<MyComponent A={B}/>);
As an alternative that doesn't require elevation or netsh you could also use TcpListener for instance.
The following is a modified excerpt of this sample: https://github.com/googlesamples/oauth-apps-for-windows/tree/master/OAuthDesktopApp
// Generates state and PKCE values.
string state = randomDataBase64url(32);
string code_verifier = randomDataBase64url(32);
string code_challenge = base64urlencodeNoPadding(sha256(code_verifier));
const string code_challenge_method = "S256";
// Creates a redirect URI using an available port on the loopback address.
var listener = new TcpListener(IPAddress.Loopback, 0);
listener.Start();
string redirectURI = string.Format("http://{0}:{1}/", IPAddress.Loopback, ((IPEndPoint)listener.LocalEndpoint).Port);
output("redirect URI: " + redirectURI);
// Creates the OAuth 2.0 authorization request.
string authorizationRequest = string.Format("{0}?response_type=code&scope=openid%20profile&redirect_uri={1}&client_id={2}&state={3}&code_challenge={4}&code_challenge_method={5}",
authorizationEndpoint,
System.Uri.EscapeDataString(redirectURI),
clientID,
state,
code_challenge,
code_challenge_method);
// Opens request in the browser.
System.Diagnostics.Process.Start(authorizationRequest);
// Waits for the OAuth authorization response.
var client = await listener.AcceptTcpClientAsync();
// Read response.
var response = ReadString(client);
// Brings this app back to the foreground.
this.Activate();
// Sends an HTTP response to the browser.
WriteStringAsync(client, "<html><head><meta http-equiv='refresh' content='10;url=https://google.com'></head><body>Please close this window and return to the app.</body></html>").ContinueWith(t =>
{
client.Dispose();
listener.Stop();
Console.WriteLine("HTTP server stopped.");
});
// TODO: Check the response here to get the authorization code and verify the code challenge
The read and write methods being:
private string ReadString(TcpClient client)
{
var readBuffer = new byte[client.ReceiveBufferSize];
string fullServerReply = null;
using (var inStream = new MemoryStream())
{
var stream = client.GetStream();
while (stream.DataAvailable)
{
var numberOfBytesRead = stream.Read(readBuffer, 0, readBuffer.Length);
if (numberOfBytesRead <= 0)
break;
inStream.Write(readBuffer, 0, numberOfBytesRead);
}
fullServerReply = Encoding.UTF8.GetString(inStream.ToArray());
}
return fullServerReply;
}
private Task WriteStringAsync(TcpClient client, string str)
{
return Task.Run(() =>
{
using (var writer = new StreamWriter(client.GetStream(), new UTF8Encoding(false)))
{
writer.Write("HTTP/1.0 200 OK");
writer.Write(Environment.NewLine);
writer.Write("Content-Type: text/html; charset=UTF-8");
writer.Write(Environment.NewLine);
writer.Write("Content-Length: " + str.Length);
writer.Write(Environment.NewLine);
writer.Write(Environment.NewLine);
writer.Write(str);
}
});
}
"Converting a varbinary
to a varchar
" can mean different things.
If the varbinary is the binary representation of a string in SQL Server (for example returned by casting to varbinary
directly or from the DecryptByPassPhrase
or DECOMPRESS
functions) you can just CAST
it
declare @b varbinary(max)
set @b = 0x5468697320697320612074657374
select cast(@b as varchar(max)) /*Returns "This is a test"*/
This is the equivalent of using CONVERT
with a style parameter of 0
.
CONVERT(varchar(max), @b, 0)
Other style parameters are available with CONVERT
for different requirements as noted in other answers.
$(document).ready(function(){_x000D_
$("#left").on('click', function (e) {_x000D_
e.stopPropagation();_x000D_
e.preventDefault();_x000D_
$('#left').hide("slide", { direction: "left" }, 500, function () {_x000D_
$('#right').show("slide", { direction: "right" }, 500);_x000D_
});_x000D_
});_x000D_
$("#right").on('click', function (e) {_x000D_
e.stopPropagation();_x000D_
e.preventDefault();_x000D_
$('#right').hide("slide", { direction: "right" }, 500, function () {_x000D_
$('#left').show("slide", { direction: "left" }, 500);_x000D_
});_x000D_
});_x000D_
_x000D_
})
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>_x000D_
_x000D_
<div style="height:100%;width:100%;background:cyan" id="left">_x000D_
<h1>Hello im going left to hide and will comeback from left to show</h1>_x000D_
</div>_x000D_
<div style="height:100%;width:100%;background:blue;display:none" id="right">_x000D_
<h1>Hello im coming from right to sho and will go back to right to hide</h1>_x000D_
</div>
_x000D_
$("#btnOpenEditing").off('click');
$("#btnOpenEditing").on('click', function (e) {
e.stopPropagation();
e.preventDefault();
$('#mappingModel').hide("slide", { direction: "right" }, 500, function () {
$('#fsEditWindow').show("slide", { direction: "left" }, 500);
});
});
It will work like charm take a look at the demo.
Or ...
LayoutInflater inflater = LayoutInflater.from(context);
In my case $1 was not working, but $0 works fine for my purpose.
In this case I was trying to replace strings with the correct format to translate them in Laravel, I hope this could be useful to someone else because it took me a while to sort it out!
Search: (?<=<div>).*?(?=</div>)
Replace: {{ __('$0') }}
in laravel 5 first we need to create migration and then run the migration
Step 1.
php artisan make:migration create_users_table --create=users
Step 2.
php artisan migrate
Note that 1>&2
cannot be used interchangeably with 2>&1
.
Imagine your command depends on piping, for example:
docker logs 1b3e97c49e39 2>&1 | grep "some log"
grepping will happen across both stderr
and stdout
since stderr
is basically merged into stdout
.
However, if you try:
docker logs 1b3e97c49e39 1>&2 | grep "some log"
,
grepping will not really search anywhere at all because Unix pipe is connecting processes via connecting stdout | stdin
, and stdout
in the second case was redirected to stderr
in which Unix pipe has no interest.
Windows 7 has the arp command within it. arp -a should show you the static and dynamic type interfaces connected to your system.
I don't know if this is what you're looking for, but you can export the results to Excel like this:
In the results pane, click the top-left cell to highlight all the records, and then right-click the top-left cell and click "Save Results As". One of the export options is CSV.
You might give this a shot too:
INSERT INTO OPENROWSET
('Microsoft.Jet.OLEDB.4.0',
'Excel 8.0;Database=c:\Test.xls;','SELECT productid, price FROM dbo.product')
Lastly, you can look into using SSIS (replaced DTS) for data exports. Here is a link to a tutorial:
http://www.accelebrate.com/sql_training/ssis_2008_tutorial.htm
== Update #1 ==
To save the result as CSV file with column headers, one can follow the steps shown below:
It might be beneficial to add greedy matching to the end of the string, so you can accept strings > than 10 and the regex will only return up to the first 10 chars. /^[a-z0-9]{0,10}$?/
I have used Sphinx, Solr and Elasticsearch. Solr/Elasticsearch are built on top of Lucene. It adds many common functionality: web server api, faceting, caching, etc.
If you want to just have a simple full text search setup, Sphinx is a better choice.
If you want to customize your search at all, Elasticsearch and Solr are the better choices. They are very extensible: you can write your own plugins to adjust result scoring.
Some example usages:
The generic Returns<T>
method can handle this situation nicely.
_mock.Setup(x => x.DoSomething(It.IsAny<string>())).Returns<string>(x => x);
Or if the method requires multiple inputs, specify them like so:
_mock.Setup(x => x.DoSomething(It.IsAny<string>(), It.IsAny<int>())).Returns((string x, int y) => x);
There are so many answers here, but if you're trying to change the jks password on a Mac in Android Studio. Here are the easiest steps I could find
1) Open Terminal and cd to where your .jks is located
2) keytool -storepasswd -new NEWPASSWORD -keystore YOURKEYSTORE.jks
3) enter your current password
$(document).ready(function() {
$('#Button').click(function() {
$(this).addClass('active');
});
});
should do the trick. unless you're loading the button with ajax. In which case you could do:
$('#Button').live('click', function() {...
Also remember not to use the same id more than once in your html code.
You could put \s*
inbetween every character in your search string so if you were looking for cat you would use c\s*a\s*t\s*s\s*s
It's long but you could build the string dynamically of course.
You can see it working here: http://www.rubular.com/r/zzWwvppSpE
and if you want this anywhere... to be a helper on DataTable this assumes you want to capture the output to Log4Net but the excellent starting example I worked against just dumps to the console... This one also has editable column width variable nMaxColWidth - ultimately I will pass that from whatever context...
public static class Helpers
{
private static ILog Log = Global.Log ?? LogManager.GetLogger("MyLogger");
/// <summary>
/// Dump contents of a DataTable to the log
/// </summary>
/// <param name="table"></param>
public static void DebugTable(this DataTable table)
{
Log?.Debug("--- DebugTable(" + table.TableName + ") ---");
var nRows = table.Rows.Count;
var nCols = table.Columns.Count;
var nMaxColWidth = 32;
// Column Headers
var sColFormat = @"{0,-" + nMaxColWidth + @"} | ";
var sLogMessage = string.Empty;
for (var i = 0; i < table.Columns.Count; i++)
{
sLogMessage = string.Concat(sLogMessage, string.Format(sColFormat, table.Columns[i].ToString()));
}
//Debug.Write(Environment.NewLine);
Log?.Debug(sLogMessage);
var sUnderScore = string.Empty;
var sDashes = string.Empty;
for (var j = 0; j <= nMaxColWidth; j++)
{
sDashes = sDashes + "-";
}
for (var i = 0; i < table.Columns.Count; i++)
{
sUnderScore = string.Concat(sUnderScore, sDashes + "|-");
}
sUnderScore = sUnderScore.TrimEnd('-');
//Debug.Write(Environment.NewLine);
Log?.Debug(sUnderScore);
// Data
for (var i = 0; i < nRows; i++)
{
DataRow row = table.Rows[i];
//Debug.WriteLine("{0} {1} ", row[0], row[1]);
sLogMessage = string.Empty;
for (var j = 0; j < nCols; j++)
{
string s = row[j].ToString();
if (s.Length > nMaxColWidth) s = s.Substring(0, nMaxColWidth - 3) + "...";
sLogMessage = string.Concat(sLogMessage, string.Format(sColFormat, s));
}
Log?.Debug(sLogMessage);
//Debug.Write(Environment.NewLine);
}
Log?.Debug(sUnderScore);
}
}
302 is a response indicating change of resource location - "Found".
The url where the resource should be now located should be in the response 'Location' header.
The "jump" should be done by the requesting client (make a new request to the resource url in the response Location header field).
//Javascript_x000D_
$scope.update = function () {_x000D_
$scope.myItem;_x000D_
alert('Hello');_x000D_
}
_x000D_
<!--HTML-->_x000D_
<div class="form-group">_x000D_
<select name="name"_x000D_
id="id" _x000D_
ng-model="myItem" _x000D_
ng-options="size as size.name for size in sizes"_x000D_
class="form-control" _x000D_
ng-change="update()"_x000D_
multiple_x000D_
required>_x000D_
</select>_x000D_
</div>
_x000D_
If you want to write, name, id, class, multiple, required , You can write in this way.
There may be confusion between class privates and module privates.
A module private starts with one underscore
Such a element is not copied along when using the from <module_name> import *
form of the import command; it is however imported if using the import <moudule_name>
syntax (see Ben Wilhelm's answer)
Simply remove one underscore from the a.__num of the question's example and it won't show in modules that import a.py using the from a import *
syntax.
A class private starts with two underscores (aka dunder i.e. d-ouble under-score)
Such a variable has its name "mangled" to include the classname etc.
It can still be accessed outside of the class logic, through the mangled name.
Although the name mangling can serve as a mild prevention device against unauthorized access, its main purpose is to prevent possible name collisions with class members of the ancestor classes.
See Alex Martelli's funny but accurate reference to consenting adults as he describes the convention used in regards to these variables.
>>> class Foo(object):
... __bar = 99
... def PrintBar(self):
... print(self.__bar)
...
>>> myFoo = Foo()
>>> myFoo.__bar #direct attempt no go
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'Foo' object has no attribute '__bar'
>>> myFoo.PrintBar() # the class itself of course can access it
99
>>> dir(Foo) # yet can see it
['PrintBar', '_Foo__bar', '__class__', '__delattr__', '__dict__', '__doc__', '__
format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__',
'__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__
', '__subclasshook__', '__weakref__']
>>> myFoo._Foo__bar #and get to it by its mangled name ! (but I shouldn't!!!)
99
>>>
If you're using jQuery, you need to use the .trigger
function, so it would be something like:
element.trigger('click');
In addition for the accepted answer you'll need the following permissions into your AndroidManifest to get it working:
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
For the links which contains common url have to console in a variable. Then attempt it sequentially.
webelements allLinks=driver.findelements(By.xpath("//a[contains(@href,'http://122.11.38.214/dl/appdl/application/apk')]"));
int linkCount=allLinks.length();
for(int i=0; <linkCount;i++)
{
driver.findelement(allLinks[i]).click();
}
byte * matToBytes(Mat image)
{
int size = image.total() * image.elemSize();
byte * bytes = new byte[size]; //delete[] later
std::memcpy(bytes,image.data,size * sizeof(byte));
}
You could also use a CSS "calc" to get the same effect instead of using the negative margin or transform properties (in case you want to use those properties for anything else).
.hero:after,
.hero:after {
z-index: -1;
position: absolute;
top: 98.1%;
left: calc(50% - 25px);
content: '';
width: 0;
height: 0;
border-top: solid 50px #e15915;
border-left: solid 50px transparent;
border-right: solid 50px transparent;
}
That hex might need to be wrapped in quotes and made into a string. Javascript might not like the # character
I really don't understand why Javascript world trying to do thing more complicated. Why not just download and include in html? Trying to have something like Maven in Java? But we have to manually include it in html anyway? So, what is the point? Maybe someday I will understand but not now.
This is how I can get it
then I get this message
[email protected] added 1 package in 1.215s
then where is "add package" ? very informative , right? I found it in my C:\Users\surasin\node_modules\popper.js\dist
Hope this help
Just a warning to the correct answers above:
Using the -f / --force Method provides a risk to lose the file if you mix up source and target:
mbucher@server2:~/test$ ls -la
total 11448
drwxr-xr-x 2 mbucher www-data 4096 May 25 15:27 .
drwxr-xr-x 18 mbucher www-data 4096 May 25 15:13 ..
-rw-r--r-- 1 mbucher www-data 4109466 May 25 15:26 data.tar.gz
-rw-r--r-- 1 mbucher www-data 7582480 May 25 15:27 otherdata.tar.gz
lrwxrwxrwx 1 mbucher www-data 11 May 25 15:26 thesymlink -> data.tar.gz
mbucher@server2:~/test$
mbucher@server2:~/test$ ln -s -f thesymlink otherdata.tar.gz
mbucher@server2:~/test$
mbucher@server2:~/test$ ls -la
total 4028
drwxr-xr-x 2 mbucher www-data 4096 May 25 15:28 .
drwxr-xr-x 18 mbucher www-data 4096 May 25 15:13 ..
-rw-r--r-- 1 mbucher www-data 4109466 May 25 15:26 data.tar.gz
lrwxrwxrwx 1 mbucher www-data 10 May 25 15:28 otherdata.tar.gz -> thesymlink
lrwxrwxrwx 1 mbucher www-data 11 May 25 15:26 thesymlink -> data.tar.gz
Of course this is intended, but usually mistakes occur. So, deleting and rebuilding the symlink is a bit more work but also a bit saver:
mbucher@server2:~/test$ rm thesymlink && ln -s thesymlink otherdata.tar.gz
ln: creating symbolic link `otherdata.tar.gz': File exists
which at least keeps my file.
Disable xdebug
For PHP 7: sudo nano /etc/php/7.0/cli/conf.d/20-xdebug.ini
For PHP 5: sudo nano /etc/php5/cli/conf.d/20-xdebug.ini
Then comment out everything and save.
UPDATE -- Disable for CLI only
As per @igoemon's comment, this is a better method:
PHP 7.0 (NGINX)
sudo mv /etc/php/7.0/cli/conf.d/20-xdebug.ini /etc/php/7.0/cli/conf.d/20-xdebug.ini.old
sudo service nginx restart
Note: Update the path to your version of PHP.
In keyboard (Spanish), SO: Win7.
Go into Preferences->Key Bindings - Default,
replace..."ctrl+/"]...
by "ctrl+7"...
And don't use the numpad, it doesn't work. Just use the numbers above the letters
There are two types of associations. Independant association where the related key would only surface as navigation property. Second one is foreign key association where the related key can be changed using foreign key and navigation property. So you can do the following.
//option 1 generic option
var contacttype = new ContactType{Id = 3};
db.ContactTypes.Attach(contacttype);
customer.ContactType = contacttype;
option 2 foreign key option
contact.ContactTypeId = 3;
//generic option works with foreign key and independent association
contact.ContactReference.EntityKey = new EntityKey("container.contactset","contacttypeid",3);
in My project i am getting error int htc device.now this code is universal. I think this is help for you.
public class CustomContentObserver extends ContentObserver {
public CustomContentObserver(Handler handler) {
super(handler);
System.out.println("Content obser");
}
public void onChange(boolean selfChange) {
super.onChange(selfChange);
String lastCallnumber;
currentDate = sdfcur.format(calender.getTime());
System.out.println("Content obser onChange()");
Log.d("PhoneService", "custom StringsContentObserver.onChange( " + selfChange + ")");
//if(!callFlag){
String[] projection = new String[]{CallLog.Calls.NUMBER,
CallLog.Calls.TYPE,
CallLog.Calls.DURATION,
CallLog.Calls.CACHED_NAME,
CallLog.Calls._ID};
Cursor c;
c=mContext.getContentResolver().query(CallLog.Calls.CONTENT_URI, projection, null, null, CallLog.Calls._ID + " DESC");
if(c.getCount()!=0){
c.moveToFirst();
lastCallnumber = c.getString(0);
String type=c.getString(1);
String duration=c.getString(2);
String name=c.getString(3);
String id=c.getString(4);
System.out.println("CALLLLing:"+lastCallnumber+"Type:"+type);
Database db=new Database(mContext);
Cursor cur =db.getFirstRecord(lastCallnumber);
final String endCall=lastCallnumber;
//checking incoming/outgoing call
if(type.equals("3")){
//missed call
}else if(type.equals("1")){
//incoming call
}else if(type.equals("2")){
//outgoing call
}
}
c.close();
}
}
You can use the split() function, which returns a list, to separate them.
letters = 'QH QD JC KD JS'
letters_list = letters.split()
Printing letters_list would now format it like this:
['QH', 'QD', 'JC', 'KD', 'JS']
Now you have a list that you can work with, just like you would with any other list. For example accessing elements based on indexes:
print(letters_list[2])
This would print the third element of your list, which is 'JC'
You have to update your app.config file manually
// Load the app.config file
XmlDocument xml = new XmlDocument();
xml.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
// Do whatever you need, like modifying the appSettings section
// Save the new setting
xml.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
And then tell your application to reload any section you modified
ConfigurationManager.RefreshSection("appSettings");
I had the same problem in Google App Scripts, and solved it like the rest said, but with a little more..
function refreshGrid(entity) {
var store = window.localStorage;
var partitionKey;
if (condition) {
return Browser.msgBox("something");
}
}
This way you not only exit the function, but show a message saying why it stopped. Hope it helps.
Another solution could be.. find the location of composer.phar file in your computer. If composer is installed successfully then it can be found in the installed directory.
Copy that location & instead of composer.phar in the command line, put the entire path there.
It also worked for me!
Local variables are automatically freed when the function ends, you don't need to free them by yourself. You only free dynamically allocated memory (e.g using malloc
) as it's allocated on the heap:
char *arr = malloc(3 * sizeof(char));
strcpy(arr, "bo");
// ...
free(arr);
More about dynamic memory allocation: http://en.wikipedia.org/wiki/C_dynamic_memory_allocation
yu have to install the correct version for your computer 32 or 63 bits thats all
Here's some more detailed information on what Client, Resource, and Session are all about.
Client:
Here's an example of client-level access to an S3 bucket's objects (at most 1000**):
import boto3
client = boto3.client('s3')
response = client.list_objects_v2(Bucket='mybucket')
for content in response['Contents']:
obj_dict = client.get_object(Bucket='mybucket', Key=content['Key'])
print(content['Key'], obj_dict['LastModified'])
** you would have to use a paginator, or implement your own loop, calling list_objects() repeatedly with a continuation marker if there were more than 1000.
Resource:
Here's the equivalent example using resource-level access to an S3 bucket's objects (all):
import boto3
s3 = boto3.resource('s3')
bucket = s3.Bucket('mybucket')
for obj in bucket.objects.all():
print(obj.key, obj.last_modified)
Note that in this case you do not have to make a second API call to get the objects; they're available to you as a collection on the bucket. These collections of subresources are lazily-loaded.
You can see that the Resource
version of the code is much simpler, more compact, and has more capability (it does pagination for you). The Client
version of the code would actually be more complicated than shown above if you wanted to include pagination.
Session:
A useful resource to learn more about these boto3 concepts is the introductory re:Invent video.
In my case, the issue was not about binding redirects or missing/mismatched Microsoft.AspNet.Razor package/dlls, so the above solutions didn't work.
The issue, in my non-web project, was that RazorEngine+Microsoft.AspNet.Razor were installed in a different project (Project A) than the calling assembly/start-up project (Project B). Because there's no explicit reference to Razor, the System.Web.Razor did NOT get copied to /bin in a Release build.
The solution was to Install RazorEngine+Microsoft.AspNet.Razor in the application entry point (Project B, ConsoleApplication in my case), then the System.Web.Razor gets copied to /bin and everyone's happy.
Add a key, value pair to dictionary
aDict = {}
aDict[key] = value
What do you mean by dynamic addition.
create a filter.js and you can make this as reusable
angular.module('yourmodule').filter('date', function($filter)
{
return function(input)
{
if(input == null){ return ""; }
var _date = $filter('date')(new Date(input), 'dd/MM/yyyy');
return _date.toUpperCase();
};
});
view
<span>{{ d.time | date }}</span>
or in controller
var filterdatetime = $filter('date')( yourdate );
I don't know if this was "the" official use case, but the following produces a warning in Java (that can further produce compile errors if mixed with return
statements, leading to unreachable code):
while (1 == 2) { // Note that "if" is treated differently
System.out.println("Unreachable code");
}
However this is legal:
while (isUserAGoat()) {
System.out.println("Unreachable but determined at runtime, not at compile time");
}
So I often find myself writing a silly utility method for the quickest way to dummy out a code block, then in completing debugging find all calls to it, so provided the implementation doesn't change this can be used for that.
JLS points out if (false)
does not trigger "unreachable code" for the specific reason that this would break support for debug flags, i.e., basically this use case (h/t @auselen). (static final boolean DEBUG = false;
for instance).
I replaced while
for if
, producing a more obscure use case. I believe you can trip up your IDE, like Eclipse, with this behavior, but this edit is 4 years into the future, and I don't have an Eclipse environment to play with.
This is not answering the question itself, but I found this question searching for the solution to convert a string to symbol and use it on a hash.
hsh = Hash.new
str_to_symbol = "Book Author Title".downcase.gsub(/\s+/, "_").to_sym
hsh[str_to_symbol] = 10
p hsh
# => {book_author_title: 10}
Hope it helps someone like me!
We can access the matched group in a regular expressions by using backslash followed by number of the matching group:
/([a-z])\1/
In the code \1 represented matched by first group ([a-z])
I performed a full-on cop-out and wrote a class which creates a batch file and then calls sftp
via a system
call. Not the nicest (or fastest) way of doing it but it works for what I need and it didn't require any installation of extra libraries or extensions in PHP.
Could be the way to go if you don't want to use the ssh2
extensions
Use the native PHP $_SERVER['HTTP_USER_AGENT']
variable instead.
One more option which I did not notice in the answers is using std::reduce
which is introduced in c++17.
But you may notice many compilers not supporting it (Above GCC 10 may be good). But eventually the support will come.
With std::reduce
, the advantage comes when using the execution policies. Specifying execution policy is optional. When the execution policy specified is std::execution::par
, the algorithm may use hardware parallel processing capabilities. The gain may be more clear when using big size vectors.
Example:
//SAMPLE
std::vector<int> vec = {2,4,6,8,10,12,14,16,18};
//WITHOUT EXECUTION POLICY
int sum = std::reduce(vec.begin(),vec.end());
//TAKING THE ADVANTAGE OF EXECUTION POLICIES
int sum2 = std::reduce(std::execution::par,vec.begin(),vec.end());
std::cout << "Without execution policy " << sum << std::endl;
std::cout << "With execution policy " << sum2 << std::endl;
You need <numeric>
header for std::reduce
.
And '<execution>'
for execution policies.
Changing the casing to all lowercases worked for me.
This worked for me in a small test:
sourceEncoding = "iso-8859-1"
targetEncoding = "utf-8"
source = open("source")
target = open("target", "w")
target.write(unicode(source.read(), sourceEncoding).encode(targetEncoding))
If you you want to copy a sub-set of the source table you can do:
INSERT INTO def (field_1, field_2, field3)
SELECT other_field_1, other_field_2, other_field_3 from `abc`
or to copy ALL fields from the source table to destination table you can do more simply:
INSERT INTO def
SELECT * from `abc`
If you do not have Administrator access to the MySQL Server configuration (i.e. you are using a hosting service), then there are 2 options to get this to work:
1) Request that the old_passwords option be set to false on the MySQL server
2) Downgrade PHP to 5.2.2 until option 1 occurs.
From what I've been able to find, the issue seems to be with how the MySQL account passwords are stored and if the 'old_passwords' setting is set to true. This causes a compatibility issue between MySQL and newer versions of PHP (5.3+) where PHP attempts to connect using a 41-character hash but the MySQL server is still storing account passwords using a 16-character hash.
This incompatibility was brought about by the changing of the hashing method used in MySQL 4.1 which allows for both short and long hash lengths (Scenario 2 on this page from the MySQL site: http://dev.mysql.com/doc/refman/5.5/en/password-hashing.html) and the inclusion of the MySQL Native Driver in PHP 5.3 (backwards compatibility issue documented on bullet 7 of this page from the PHP documentation: http://www.php.net/manual/en/migration53.incompatible.php).
This worked for me on Windows 10 and powershell 5.1:
Or you can insert raw sql part to conditions so I have 'conditions'=>array('Member.id NOT IN (SELECT Membership.member_id FROM memberships AS Membership)')
Do you mean Delegate.Invoke
/BeginInvoke
or Control.Invoke
/BeginInvoke
?
Delegate.Invoke
: Executes synchronously, on the same thread.Delegate.BeginInvoke
: Executes asynchronously, on a threadpool
thread.Control.Invoke
: Executes on the UI thread, but calling thread waits for completion before continuing.Control.BeginInvoke
: Executes on the UI thread, and calling thread doesn't wait for completion.Tim's answer mentions when you might want to use BeginInvoke
- although it was mostly geared towards Delegate.BeginInvoke
, I suspect.
For Windows Forms apps, I would suggest that you should usually use BeginInvoke
. That way you don't need to worry about deadlock, for example - but you need to understand that the UI may not have been updated by the time you next look at it! In particular, you shouldn't modify data which the UI thread might be about to use for display purposes. For example, if you have a Person
with FirstName
and LastName
properties, and you did:
person.FirstName = "Kevin"; // person is a shared reference
person.LastName = "Spacey";
control.BeginInvoke(UpdateName);
person.FirstName = "Keyser";
person.LastName = "Soze";
Then the UI may well end up displaying "Keyser Spacey". (There's an outside chance it could display "Kevin Soze" but only through the weirdness of the memory model.)
Unless you have this sort of issue, however, Control.BeginInvoke
is easier to get right, and will avoid your background thread from having to wait for no good reason. Note that the Windows Forms team has guaranteed that you can use Control.BeginInvoke
in a "fire and forget" manner - i.e. without ever calling EndInvoke
. This is not true of async calls in general: normally every BeginXXX should have a corresponding EndXXX call, usually in the callback.
Use Link-1 to generate a project. this a basic project for learning. you can understand the folder structure. Use Link-2 for creating a basic Spring boot project. 1: http://start.spring.io/ 2: https://projects.spring.io/spring-boot/
Create a gradle/maven project Automatically src/main/java and src/main/test will be created. create controller/service/Repository package and start writing the code.
-src/main/java(source folder) ---com.package.service(package) ---ServiceClass(Class) ---com.package.controller(package) ---ControllerClass(Class)
Also, note that XDocument
is supported in Xbox 360 and Windows Phone OS 7.0.
If you target them, develop for XDocument
or migrate from XmlDocument
.
Above Answers are correct. I faced an different issue where in HTC M8 my application crashes when selecting an image from gallery. I'm getting null value for image path. I fixed and optimized with the following solution. in onActivityResult method
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if ((requestCode == RESULT_LOAD_IMAGE) && (resultCode == RESULT_OK)) {
if (data != null) {
Uri selectedImageUri = null;
selectedImageUri = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor imageCursor = mainActivity.getContentResolver().query(
selectedImageUri, filePathColumn, null, null, null);
if (imageCursor == null) {
return;
}
imageCursor.moveToFirst();
int columnIndex = imageCursor.getColumnIndex(filePathColumn[0]);
picturePath = imageCursor.getString(columnIndex);
if (picturePath == null) {
picturePath = selectedImageUri.getPath();
String wholeID = DocumentsContract
.getDocumentId(selectedImage);
// Split at colon, use second item in the array
String id = wholeID.split(":")[1];
String[] column = { MediaStore.Images.Media.DATA };
// where id is equal to
String sel = MediaStore.Images.Media._ID + "=?";
Cursor cursor = mainActivity.getContentResolver().query(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
column, sel, new String[] { id }, null);
columnIndex = cursor.getColumnIndex(column[0]);
if (cursor.moveToFirst()) {
picturePath = cursor.getString(columnIndex);
}
cursor.close();
}
picturePathAbs = new File(picturePath).getAbsolutePath();
imageCursor.close();
}
}
I wonder why there are so many "solutions" posted?
If my rookie-understanding on how GetFiles works is right, there are only two options and any of the solutions above can be brought down to these:
GetFiles, then filter: Fast, but a memory killer due to storing overhead untill the filters are applied
Filter while GetFiles: Slower the more filters are set, but low memory usage as no overhead is stored.
This is explained in one of the above posts with an impressive benchmark: Each filter option causes a seperate GetFile-operation so the same part of the harddrive gets read several times.
In my opinion Option 1) is better, but using the SearchOption.AllDirectories on folders like C:\ would use huge amounts of memory.
Therefor i would just make a recursive sub-method that goes through all subfolders using option 1)
This should cause only 1 GetFiles-operation on each folder and therefor be fast (Option 1), but use only a small amount of memory as the filters are applied afters each subfolders' reading -> overhead is deleted after each subfolder.
Please correct me if I am wrong. I am as i said quite new to programming but want to gain deeper understanding of things to eventually become good at this :)
Open the file for 'append' rather than 'write'.
with open('file.txt', 'a') as file:
file.write('input')
When I want to access the application file version (what is set in Assembly Information -> File version), say to set a label's text to it on form load to display the version, I have just used
versionlabel.Text = "Version " + Application.ProductVersion;
This approach requires a reference to System.Windows.Forms
.
Install tqdm
.(pip install tqdm
)
and use it as follows:
import time
from tqdm import tqdm
for i in tqdm(range(1000)):
time.sleep(0.01)
That's a 10 seconds progress bar that'll output something like this:
47%|¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦? | 470/1000 [00:04<00:05, 98.61it/s]
SAP is notoriously bad at making these downloads available... or in an easily accessible location so hopefully this link still works by the time you read this answer.
< original link no longer active >
http://scn.sap.com/docs/DOC-7824 Updated Link 2/6/13:
https://wiki.scn.sap.com/wiki/display/BOBJ/Crystal+Reports%2C+Developer+for+Visual+Studio+Downloads - "Updated 10/31/2017"
http://www.crystalreports.com/crvs/confirm/ - "Updated 10/31/2017"
The Java Service Wrapper might help you, depending on your requirements.
You can checkout the old version of the file to merge, saving it under a different name, then run whatever your merge tool is on the two files.
eg.
git show B:src/common/store.ts > /tmp/store.ts
(where B is the branch name/commit/tag)
meld src/common/store.ts /tmp/store.ts
You can use any of the following:
\b #A word break and will work for both spaces and end of lines.
(^|\s) #the | means or. () is a capturing group.
/\b(stackoverflow)\b/
Also, if you don't want to include the space in your match, you can use lookbehind/aheads.
(?<=\s|^) #to look behind the match
(stackoverflow) #the string you want. () optional
(?=\s|$) #to look ahead.
I always have to check my cheatsheet :-)
Step 1: right-click on the top of putty window and select 'Change settings'.
Step 2: type the name of the session and save.
That's it!. Enjoy!
None of the provided examples on here worked for me. They were either for Python 2 (uurllib2) or those for Python 3 return the error "ImportError: No module named request". I google the error message and it apparently requires me to install a the module - which is obviously unacceptable for such a simple task.
This code worked for me:
import json,urllib
data = urllib.urlopen("https://api.github.com/users?since=0").read()
d = json.loads(data)
print (d)
Assuming that the *.bak file is on the same machine as the SQL Express instance it might be a permissions issue.
If you download procmon http://technet.microsoft.com/en-us/sysinternals/bb896645.aspx you can filter on that file path, look for ACCESS_DENIED errors and if any are there you can see the account name that's failing get to access.
Try this one
.responsive-container{
display:table;
}
.img-container{
display:table-cell;
vertical-align: middle;
}
Solution:
where some_column NOT LIKE '%[^0-9]%'
Is correct.
Just one important note: Add validation for when the string column = ''
(empty string). This scenario will return that ''
is a valid number as well.
If you want to convert any DataTable to a equivalent IEnumerable vector function.
Please take a look at the following generic function, this may help your needs (you may need to include write cases for different datatypes based on your needs).
/// <summary>
/// Get entities from DataTable
/// </summary>
/// <typeparam name="T">Type of entity</typeparam>
/// <param name="dt">DataTable</param>
/// <returns></returns>
public IEnumerable<T> GetEntities<T>(DataTable dt)
{
if (dt == null)
{
return null;
}
List<T> returnValue = new List<T>();
List<string> typeProperties = new List<string>();
T typeInstance = Activator.CreateInstance<T>();
foreach (DataColumn column in dt.Columns)
{
var prop = typeInstance.GetType().GetProperty(column.ColumnName, BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public);
if (prop != null)
{
typeProperties.Add(column.ColumnName);
}
}
foreach (DataRow row in dt.Rows)
{
T entity = Activator.CreateInstance<T>();
foreach (var propertyName in typeProperties)
{
if (row[propertyName] != DBNull.Value)
{
string str = row[propertyName].GetType().FullName;
if (entity.GetType().GetProperty(propertyName).PropertyType == typeof(System.String))
{
object Val = row[propertyName].ToString();
entity.GetType().GetProperty(propertyName, BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public).SetValue(entity, Val, BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public, null, null, null);
}
else if (entity.GetType().GetProperty(propertyName).PropertyType == typeof(System.Guid))
{
object Val = Guid.Parse(row[propertyName].ToString());
entity.GetType().GetProperty(propertyName, BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public).SetValue(entity, Val, BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public, null, null, null);
}
else
{
entity.GetType().GetProperty(propertyName, BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public).SetValue(entity, row[propertyName], BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public, null, null, null);
}
}
else
{
entity.GetType().GetProperty(propertyName, BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public).SetValue(entity, null, BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public, null, null, null);
}
}
returnValue.Add(entity);
}
return returnValue.AsEnumerable();
}
You can also find the name of the current on screen activity using
adb shell dumpsys window windows | grep 'mCurrentFocus'
The way you're doing it you're querying for the process twice. Also Lynn raises a good point about being nice first. I'd probably try something like the following:
# get Firefox process
$firefox = Get-Process firefox -ErrorAction SilentlyContinue
if ($firefox) {
# try gracefully first
$firefox.CloseMainWindow()
# kill after five seconds
Sleep 5
if (!$firefox.HasExited) {
$firefox | Stop-Process -Force
}
}
Remove-Variable firefox
You probably finally realized this between posting this question and today, but the very nature of selectors makes it impossible to navigate through hierarchically unrelated HTML elements.
Or, to put it simply, since you said in your comment that
there are no uniform parent containers
... it's just not possible with selectors alone, without modifying the markup in some way as shown by the other answers.
You have to use the jQuery .eq()
solution.
>>> class X(object):
... pass
...
>>> type(X)
<type 'type'>
>>> isinstance(X,type)
True
Actually, technically when indented properly, it would be:
if (condition) {
...
} else {
if (condition) {
...
} else {
...
}
}
There is no else if
, strictly speaking.
(Update: Of course, as pointed out, the above is not considered good style.)
Could anyone help explain why
In Python 2 a python "int" was equivalent to a C long. In Python 3 an "int" is an arbitrary precision type but numpy still uses "int" it to represent the C type "long" when creating arrays.
The size of a C long is platform dependent. On windows it is always 32-bit. On unix-like systems it is normally 32 bit on 32 bit systems and 64 bit on 64 bit systems.
or give a solution for the code on windows? Thanks so much!
Choose a data type whose size is not platform dependent. You can find the list at https://docs.scipy.org/doc/numpy/reference/arrays.scalars.html#arrays-scalars-built-in the most sensible choice would probably be np.int64
To your secondary question
var elem1 = $('#elem1'),
elem2 = $('#elem2'),
elem3 = $('#elem3');
You can use the variable as the replacement of selector.
elem1.css({'display':'none'}); //will work
In the below case selector is already stored in a variable.
$(elem1,elem2,elem3).css({'display':'none'}); // will not work
i have been working on a dropdown replacement jquery plugin to combat this problem. As of this post, it is almost indistinguishable from a native dropdown in terms of look and functionality.
here is a demo (also a link to downloads): http://programmingdrunk.com/current-projects/dropdownReplacement/
here is the project page of the plugin:
http://plugins.jquery.com/project/dropdownreplacement
(update:) the jquery plugin page seems to no longer work. I will probably not put my plugin on their new site when they get it working, so feel free to use the programmingdrunk.com link for demo/download
In my case issue occurred after following:
I selected proxy settings from Android Studio settings when I was working in a network behind a proxy. When I disconnected from that network and connected to home network which doesn't have a proxy, I removed the proxy settings from Android Studio, but gradle seemed to take the old proxy settings.
The problem was that gradle had also saved the proxy settings in following file when I set proxy settings in Android Studio, but it hasn't got removed when I removed proxy settings from Android Studio.
%HOME%\.gradle\gradle.properties
When I removed the proxy settings from this file, gradle sync worked again.
Do not use classpath. This may cause problems with different ClassLoaders (container vs. application). WEB-INF is always the better choice.
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-config.xml</param-value>
</context-param>
and
<bean id="placeholderConfig" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location">
<value>/WEB-INF/social.properties</value>
</property>
</bean>
Have you tried using the 'static' storage class similar to?:
public static class employee
{
static NameValueCollection appSetting = ConfigurationManager.AppSettings;
}
I benefited a lot from 'Dive into HTML 5'. The explanation and demo are easier and to the point. History chapter - http://diveintohtml5.info/history.html and history demo - http://diveintohtml5.info/examples/history/fer.html
In my case, I use VS 2010, Oracle v11 64 bits. I might to publish in 64 bit mode (Setting to "Any Cpu" mode in Web Project configuration) and I might set IIS on Production Server to 32 Bit compability to false (because the the server is 64 bit and I like to take advantage it).
Then to solve the problem "Could not load file or assembly 'Oracle.DataAccess'":
In case for xml attribute its android:checkedButton
which takes the id
of the RadioButton
to be checked.
<RadioGroup
...
...
android:checkedButton="@+id/IdOfTheRadioButtonInsideThatTobeChecked"
... >....</RadioGroup>
In bootstrap 4 I just use $(el).tooltip('dispose');
then recreate as normal. So you can put the dispose before a function that creates a tooltip to be sure it doesn't double up.
Having to check the state and tinker with values seems less friendly.
Ok, after over 2 days of searching we finally fixed the problem. We deleted all our filter and configurations and instead used this 5 lines of code in the application class.
@SpringBootApplication
public class Application {
public static void main(String[] args) {
final ApplicationContext ctx = SpringApplication.run(Application.class, args);
}
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurerAdapter() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedOrigins("http://localhost:3000");
}
};
}
}
You can use date
to get time and date of a day:
[pengyu@GLaDOS ~]$date
Tue Aug 27 15:01:27 CST 2013
Also hwclock
would do:
[pengyu@GLaDOS ~]$hwclock
Tue 27 Aug 2013 03:01:29 PM CST -0.516080 seconds
For customized output, you can either redirect the output of date
to something like awk
, or write your own program to do that.
Remember to put your own executable scripts/binary into your PATH
(e.g. /usr/bin) to make it invokable anywhere.
Make sure that the "Distributed Transaction Coordinator" Service is running on both database and client. Also make sure you check "Network DTC Access", "Allow Remote Client", "Allow Inbound/Outbound" and "Enable TIP".
To enable Network DTC Access for MS DTC transactions
Open the Component Services snap-in.
To open Component Services, click Start. In the search box, type dcomcnfg, and then press ENTER.
Expand the console tree to locate the DTC (for example, Local DTC) for which you want to enable Network MS DTC Access.
On the Action menu, click Properties.
Click the Security tab and make the following changes: In Security Settings, select the Network DTC Access check box.
In Transaction Manager Communication, select the Allow Inbound and Allow Outbound check boxes.
Great suggestion! Here's my reusable take on it:
public class StreamUtils {
public static <T> Stream<T> asStream(Iterator<T> sourceIterator) {
return asStream(sourceIterator, false);
}
public static <T> Stream<T> asStream(Iterator<T> sourceIterator, boolean parallel) {
Iterable<T> iterable = () -> sourceIterator;
return StreamSupport.stream(iterable.spliterator(), parallel);
}
}
And usage (make sure to statically import asStream):
List<String> aPrefixedStrings = asStream(sourceIterator)
.filter(t -> t.startsWith("A"))
.collect(toList());
The heap memory is the runtime data area from which the Java VM allocates memory for all class instances and arrays. The heap may be of a fixed or variable size. The garbage collector is an automatic memory management system that reclaims heap memory for objects.
Eden Space: The pool from which memory is initially allocated for most objects.
Survivor Space: The pool containing objects that have survived the garbage collection of the Eden space.
Tenured Generation or Old Gen: The pool containing objects that have existed for some time in the survivor space.
Non-heap memory includes a method area shared among all threads and memory required for the internal processing or optimization for the Java VM. It stores per-class structures such as a runtime constant pool, field and method data, and the code for methods and constructors. The method area is logically part of the heap but, depending on the implementation, a Java VM may not garbage collect or compact it. Like the heap memory, the method area may be of a fixed or variable size. The memory for the method area does not need to be contiguous.
Permanent Generation: The pool containing all the reflective data of the virtual machine itself, such as class and method objects. With Java VMs that use class data sharing, this generation is divided into read-only and read-write areas.
Code Cache: The HotSpot Java VM also includes a code cache, containing memory that is used for compilation and storage of native code.
The bind() method creates a new function instance whose this value is bound to the value that was passed into bind(). For example:
window.color = "red";
var o = { color: "blue" };
function sayColor(){
alert(this.color);
}
var objectSayColor = sayColor.bind(o);
objectSayColor(); //blue
Here, a new function called objectSayColor() is created from sayColor() by calling bind() and passing in the object o. The objectSayColor() function has a this value equivalent to o, so calling the function, even as a global call, results in the string “blue” being displayed.
Reference : Nicholas C. Zakas - PROFESSIONAL JAVASCRIPT® FOR WEB DEVELOPERS
To have an idea of the speed penalty, I have tested two versions, one with Array.fill and one with StringBuilder.
public static String repeat(char what, int howmany) {
char[] chars = new char[howmany];
Arrays.fill(chars, what);
return new String(chars);
}
and
public static String repeatSB(char what, int howmany) {
StringBuilder out = new StringBuilder(howmany);
for (int i = 0; i < howmany; i++)
out.append(what);
return out.toString();
}
using
public static void main(String... args) {
String res;
long time;
for (int j = 0; j < 1000; j++) {
res = repeat(' ', 100000);
res = repeatSB(' ', 100000);
}
time = System.nanoTime();
res = repeat(' ', 100000);
time = System.nanoTime() - time;
System.out.println("elapsed repeat: " + time);
time = System.nanoTime();
res = repeatSB(' ', 100000);
time = System.nanoTime() - time;
System.out.println("elapsed repeatSB: " + time);
}
(note the loop in main function is to kick in JIT)
The results are as follows:
elapsed repeat: 65899
elapsed repeatSB: 305171
It is a huge difference
Use max()
:
Using itemgetter()
:
In [53]: lis=[(101, 153), (255, 827), (361, 961)]
In [81]: from operator import itemgetter
In [82]: max(lis,key=itemgetter(1))[0] #faster solution
Out[82]: 361
using lambda
:
In [54]: max(lis,key=lambda item:item[1])
Out[54]: (361, 961)
In [55]: max(lis,key=lambda item:item[1])[0]
Out[55]: 361
timeit
comparison:
In [30]: %timeit max(lis,key=itemgetter(1))
1000 loops, best of 3: 232 us per loop
In [31]: %timeit max(lis,key=lambda item:item[1])
1000 loops, best of 3: 556 us per loop
In HTML:
<form id="my_form"><input id="my_field" type="date" /></form>
In JavaScript
// test and transform if needed_x000D_
if($('#my_field').attr('type') === 'text'){_x000D_
$('#my_field').attr('type', 'text').attr('placeholder','aaaa-mm-dd'); _x000D_
};_x000D_
_x000D_
// check_x000D_
if($('#my_form')[0].elements[0].value.search(/(19[0-9][0-9]|20[0-1][0-5])[- \-.](0[1-9]|1[012])[- \-.](0[1-9]|[12][0-9]|3[01])$/i) === 0){_x000D_
$('#my_field').removeClass('bad');_x000D_
} else {_x000D_
$('#my_field').addClass('bad');_x000D_
};
_x000D_
Suppose you want to give attributes to an instance which was previously not written in code.
The setattr()
does just that.
It takes the instance of the class self
and key and value to set.
class Example:
def __init__(self, **kwargs):
for key, value in kwargs.items():
setattr(self, key, value)
Better late than never! I made mine a class:
.map
{
position:absolute;
top:64px;
width:1100px;
height:735px;
overflow:hidden;
border:1px solid rgb(211,211,211);
border-radius:3px;
}
and then
<div id="map" class="map"></div>
Neither is good.
Behaviour should be configured independent of the actual markup. For instance, in jQuery you might do something like
$('#the-element').click(function () { /* perform action here */ });
in a separate <script>
block.
The advantage of this is that it
Furthermore, it degrades gracefully (but so would using the onclick
event) since you can provide the link tags with a href
in case the user doesn’t have JavaScript enabled.
Of course, these arguments still count if you’re not using jQuery or another JavaScript library (but why do that?).
Let's say you have a script script.sh
. To run it (using Git Bash), you do the following: [a] Add a "sh-bang" line on the first line (e.g. #!/bin/bash
) and then [b]:
# Use ./ (or any valid dir spec):
./script.sh
Note: chmod +x
does nothing to a script's executability on Git Bash. It won't hurt to run it, but it won't accomplish anything either.
please paste below code on surfaceview extend class constructor.............
constructor coding
SurfaceHolder holder = getHolder();
holder.addCallback(this);
SurfaceView sur = (SurfaceView)findViewById(R.id.surfaceview);
sur.setZOrderOnTop(true); // necessary
holder = sur.getHolder();
holder.setFormat(PixelFormat.TRANSPARENT);
xml coding
<com.welcome.panelview.PanelViewWelcomeScreen
android:id="@+id/one"
android:layout_width="600px"
android:layout_height="312px"
android:layout_gravity="center"
android:layout_marginTop="10px"
android:background="@drawable/welcome" />
try above code...
std::map
takes up to four template type arguments, the third one being a comparator. E.g.:
struct cmpByStringLength {
bool operator()(const std::string& a, const std::string& b) const {
return a.length() < b.length();
}
};
// ...
std::map<std::string, std::string, cmpByStringLength> myMap;
Alternatively you could also pass a comparator to map
s constructor.
Note however that when comparing by length you can only have one string of each length in the map as a key.
Try this....modify the code as per your needs.
List<Employee> target = dt.AsEnumerable()
.Select(row => new Employee
{
Name = row.Field<string?>(0).GetValueOrDefault(),
Age= row.Field<int>(1)
}).ToList();
Now find tag and change it to < Directory "C:/xampp/htdocs/myproject/web" >
Restart Your Apache
You can get the ID, or any other attribute, using jQuery's attrib function.
$('ul.art-vmenu li').attrib('id');
To get the menu text, which is in the t span, you can do this:
$('ul.art-vmenu li').children('span.t').html();
To change the HTML is just as easy:
$('ul.art-vmenu li').children('span.t').html("I'm different");
Of course, if you wanted to get all the span.t's in the first place, it would be simpler to do:
$('ul.art-vemnu li span.t').html();
But I'm assuming you've already got the li's, and want to use child() to find something within that element.
Remove the data attribute as you are not POSTING
anything to the server (Your controller does not expect any parameters).
And in your AJAX Method you can use Razor
and use @Url.Action
rather than a static string:
$.ajax({
url: '@Url.Action("FirstAjax", "AjaxTest")',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: successFunc,
error: errorFunc
});
From your update:
$.ajax({
type: "POST",
url: '@Url.Action("FirstAjax", "AjaxTest")',
contentType: "application/json; charset=utf-8",
data: { a: "testing" },
dataType: "json",
success: function() { alert('Success'); },
error: errorFunc
});
The steps below are for Eclipse Indigo Classic Version.
There are a lot of great answers here, but I want to come with my 50 cents.
What all of these answers are missing is a simple analogy which would work for a person who just starts his journey in the programming languages.
Hopefully, I will fill this gap with this analogy:
Feel the difference with a sentence creation.
If I have a sentence "I like cheese"
, I can tell you clearly and loudly (literally, or verbatim): I like cheese.
This is my literal (word by word) creation of the sentence.
All other ways are some tricky ways of making you to understand of what sentence I created exactly. For example, I tell you:
"I"
, the object is "cheese"
, and the predicate is "to like"
.
This is another way of YOU to learn without any ambiguities the very same sentence: "I like cheese".Or,
In this case, you also come to the same result: you know exactly what the sentence is.
You can devise any other methods which would differ from "word-by-word" sentence creation (LITERAL), and which would be INDIRECT (non literal, non verbatim) method of sentence creation.
I think this is the core concept which lays here.
After facing a similar issue, below is what I did :
To the CORS filter, I added corsFilter.getAllowedOrigins().add("http://localhost:4200");
.
Basically, you should add the URL which you want to allow Cross-Origin Resource Sharing. Ans you can also use "*"
instead of any specific URL to allow any URL.
public class RestApplication
extends Application
{
private Set<Object> singletons = new HashSet<Object>();
public MessageApplication()
{
singletons.add(new CalculatorService()); //CalculatorService is your specific service you want to add/use.
CorsFilter corsFilter = new CorsFilter();
// To allow all origins for CORS add following, otherwise add only specific urls.
// corsFilter.getAllowedOrigins().add("*");
System.out.println("To only allow restrcited urls ");
corsFilter.getAllowedOrigins().add("http://localhost:4200");
singletons = new LinkedHashSet<Object>();
singletons.add(corsFilter);
}
@Override
public Set<Object> getSingletons()
{
return singletons;
}
}
<web-app id="WebApp_ID" version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>Restful Web Application</display-name>
<!-- Auto scan rest service -->
<context-param>
<param-name>resteasy.scan</param-name>
<param-value>true</param-value>
</context-param>
<context-param>
<param-name>resteasy.servlet.mapping.prefix</param-name>
<param-value>/rest</param-value>
</context-param>
<listener>
<listener-class>
org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap
</listener-class>
</listener>
<servlet>
<servlet-name>resteasy-servlet</servlet-name>
<servlet-class>
org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher
</servlet-class>
<init-param>
<param-name>javax.ws.rs.Application</param-name>
<param-value>com.app.RestApplication</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>resteasy-servlet</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
</web-app>
The most important code which I was missing when I was getting this issue was, I was not adding my class extending javax.ws.rs.Application i.e RestApplication to the init-param of <servlet-name>resteasy-servlet</servlet-name>
<init-param>
<param-name>javax.ws.rs.Application</param-name>
<param-value>com.app.RestApplication</param-value>
</init-param>
And therefore my Filter was not able to execute and thus the application was not allowing CORS from the URL specified.
try this:
var today = new Date();
var date = today.getFullYear()+'-'+(today.getMonth()+1)+'-'+today.getDate();
var time = today.getHours()+':'+today.getMinutes()+':'+today.getSeconds();
console.log(date + ' '+ time);
_x000D_
Interesting I never spent too much time adjusting the colours in IntelliJ although tried once.
See link below with an already defined colour scheme you can import.
Where can I download IntelliJ IDEA 10 Color Schemes?
http://devnet.jetbrains.net/docs/DOC-1154
Download the jar file, file import the jar where you will see a what to import ;)
<ListView android:id="@id/android:list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:drawSelectorOnTop="false"
android:scrollbars="vertical"/>
In Java, 2D arrays are really arrays of arrays with possibly different lengths (there are no guarantees that in 2D arrays that the 2nd dimension arrays all be the same length)
You can get the length of any 2nd dimension array as z[n].length
where 0 <= n < z.length
.
If you're treating your 2D array as a matrix, you can simply get z.length
and z[0].length
, but note that you might be making an assumption that for each array in the 2nd dimension that the length is the same (for some programs this might be a reasonable assumption).
Using Spring for Android with RestTemplate https://spring.io/guides/gs/consuming-rest-android/
// The connection URL
String url = "https://ajax.googleapis.com/ajax/" +
"services/search/web?v=1.0&q={query}";
// Create a new RestTemplate instance
RestTemplate restTemplate = new RestTemplate();
// Add the String message converter
restTemplate.getMessageConverters().add(new StringHttpMessageConverter());
// Make the HTTP GET request, marshaling the response to a String
String result = restTemplate.getForObject(url, String.class, "Android");
Note that another approach is to keep with the 4.0 validation behaviour, but to define your own class that derives from RequestValidator
and set:
<httpRuntime requestValidationType="YourNamespace.YourValidator" />
(where YourNamespace.YourValidator
is well, you should be able to guess...)
This way you keep the advantages of 4.0s behaviour (specifically, that the validation happens earlier in the processing), while also allowing the requests you need to let through, through.
As an alternative to the keyboard shortcuts, here's an extension named "Back and Forward buttons" that adds the forward and back buttons to the status bar:
https://marketplace.visualstudio.com/items?itemName=grimmer.vscode-back-forward-button
// wrap it in jQuery, now it's a collection
var $elements = $(someHTML);
// append to the DOM
$("#myDiv").append($elements);
// do stuff, using the initial reference
$elements.effects("highlight", {}, 2000);
SizedBox(
width: width-100,
child: Text(
"YOUR LONG TEXT HERE...",
maxLines: 3,
overflow: TextOverflow.clip,
softWrap: true,
style: TextStyle(
fontWeight:FontWeight.bold,
),
),
),
By default forever places all of the files it needs into /$HOME/.forever. If you would like to change that location just set the FOREVER_ROOT environment variable when you are running forever:
FOREVER_ROOT=/etc/forever forever start index.js
Specific actions you can do from SQL client and you don't need to restart anything:
SET GLOBAL log = 'ON';
FLUSH LOGS;
Very Sleepy is a C/C++ CPU profiler for Windows systems (free).
An alternative solution could be using the following code DRandom. This class should be used with a seed. It provides a familiar interface to what you would expect in .NET, it was ported from mono's Random.cs. This code may not be cryptography safe and has not been statistically tested.
If other whitespace characters are possible, then you'd want:
testString.split("\\s+");
If the message is "n commits behind master."
You need to rebase your dev branch with master. You got the above message because after checking out dev branch from master, the master branch got new commit and has moved ahead. You need to get those new commits to your dev branch.
Steps:
git checkout master
git pull #this will update your local master
git checkout yourDevBranch
git rebase master
xCode is picky about the GPX file it accepts.
But, in xCode you can create a GPX file with the format it will accept:
And then just change the content of the file to the location you need.
This will work even when there are multiple instance of jar is running
wmic Path win32_process Where "CommandLine Like '%yourname.jar%'" Call Terminate
Prior to 0.20.203, and officially deprecated in 2.6.0:
hadoop fs -dus [directory]
Since 0.20.203 (dead link) 1.0.4 and still compatible through 2.6.0:
hdfs dfs -du [-s] [-h] URI [URI …]
You can also run hadoop fs -help
for more info and specifics.
$result = ['5' => 'cherry', '7' => 'apple'];
array_multisort($result, SORT_ASC);
print_r($result);
Array ( [0] => apple [1] => cherry )
//...
array_multisort($result, SORT_DESC);
//...
Array ( [0] => cherry [1] => apple )
You can also use blank single quotes for the auto_increment column. something like this. It worked for me.
$query = "INSERT INTO myTable VALUES ('','Fname', 'Lname', 'Website')";
FlexPaper is probably still the best viewer out there to be used for this kind of stuff. It has a traditional viewer and a more turn page / flip book style viewer both in flash and html5
You should be able to use getByName or getByAddress.
The host name can either be a machine name, such as "java.sun.com", or a textual representation of its IP address
InetAddress addr = InetAddress.getByName("127.0.0.1");
The method that takes a byte array can be used like this:
byte[] ipAddr = new byte[]{127, 0, 0, 1};
InetAddress addr = InetAddress.getByAddress(ipAddr);
To make the answer provided by @abourget more complete, the value of scopeValue[field] in the following line of code could be undefined. This would result in an error when setting subfield:
<textarea ng-model="scopeValue[field][subfield]"></textarea>
One way of solving this problem is by adding an attribute ng-focus="nullSafe(field)", so your code would look like the below:
<textarea ng-focus="nullSafe(field)" ng-model="scopeValue[field][subfield]"></textarea>
Then you define nullSafe( field ) in a controller like the below:
$scope.nullSafe = function ( field ) {
if ( !$scope.scopeValue[field] ) {
$scope.scopeValue[field] = {};
}
};
This would guarantee that scopeValue[field] is not undefined before setting any value to scopeValue[field][subfield].
Note: You can't use ng-change="nullSafe(field)" to achieve the same result because ng-change happens after the ng-model has been changed, which would throw an error if scopeValue[field] is undefined.
ps if it is only about space in the input, then some double quotes worked smoothly for me...
read artist;
find "/mnt/2tb_USB_hard_disc/p_music/$artist" -type f -name *.mp3 -exec mpg123 '{}' \;
public String getIMEI(Context context){
TelephonyManager mngr = (TelephonyManager) context.getSystemService(context.TELEPHONY_SERVICE);
String imei = mngr.getDeviceId();
return imei;
}
I cleared this use. By using this site click Here , follow the steps, the same steps follows upto the ubuntu version 18.04
UPDATE mytable SET title=TRIM(REPLACE(REPLACE(title, "\n", ""), "\t", ""));
To Calculate age from Date of birth used used query like this.
'SELECT username, email, skype, avatar, TIMESTAMPDIFF(YEAR, date, CURDATE()) AS age, signup_date, gender FROM users WHERE id="'.$id.'"';
if(isset($_GET['id']))
{
$id = intval($_GET['id']);
$dn = mysql_query('select username, email, skype, avatar, TIMESTAMPDIFF(YEAR, date, CURDATE()) AS age, signup_date, gender from users where id="'.$id.'"');
$dnn = mysql_fetch_array($dn);
echo $dnn['age'];
}
Note: don't use reserved keywords column name.
You can add them in your htaccess file or vhost configuration.
See here : http://httpd.apache.org/docs/2.2/mod/mod_expires.html
But unless you own those domains .. they are our of your control.
Just use the below code to resolve this:
JsonObject obj = Json.createReader(new ByteArrayInputStream(Base64.getDecoder().decode(accessToken.split("\\.")[1].
replace('-', '+').replace('_', '/')))).readObject();
In the above code replace('-', '+').replace('_', '/')
did the job. For more details see the https://jwt.io/js/jwt.js. I understood the problem from the part of the code got from that link:
function url_base64_decode(str) {
var output = str.replace(/-/g, '+').replace(/_/g, '/');
switch (output.length % 4) {
case 0:
break;
case 2:
output += '==';
break;
case 3:
output += '=';
break;
default:
throw 'Illegal base64url string!';
}
var result = window.atob(output); //polifyll https://github.com/davidchambers/Base64.js
try{
return decodeURIComponent(escape(result));
} catch (err) {
return result;
}
}
Another (and I think better) way to achieve this is to actually intercept the data. limitTo is okay but what if you're limiting to 10 when your array actually contains thousands?
When calling my service I simply did this:
TaskService.getTasks(function(data){
$scope.tasks = data.slice(0,10);
});
This limits what is sent to the view, so should be much better for performance than doing this on the front-end.
Or add this part
<script type="text/javascript">
var mySpan = document.createElement("span");
mySpan.innerHTML = "This is my span!";
mySpan.style.color = "red";
document.body.appendChild(mySpan);
alert("Why does the span change after this alert? Not before?");
</script>
after the HTML, like:
<html>
<head>...</head>
<body>...</body>
<script type="text/javascript">
var mySpan = document.createElement("span");
mySpan.innerHTML = "This is my span!";
mySpan.style.color = "red";
document.body.appendChild(mySpan);
alert("Why does the span change after this alert? Not before?");
</script>
</html>
Try this one -
"SELECT
ID, Salt, password, BannedEndDate
, (
SELECT COUNT(1)
FROM dbo.LoginFails l
WHERE l.UserName = u.UserName
AND IP = '" + Request.ServerVariables["REMOTE_ADDR"] + "'
) AS cnt
FROM dbo.Users u
WHERE u.UserName = '" + LoginModel.Username + "'"
I know this topic is old, but there are no correct answers.
rotation transform rotates the element from its center, so, a wider element will rotate this way:
Applying overflow: hidden
hides the longest dimension as you can see here:
img{_x000D_
border: 1px solid #000;_x000D_
transform: rotate(270deg);_x000D_
-ms-transform: rotate(270deg);_x000D_
-moz-transform: rotate(270deg);_x000D_
-webkit-transform: rotate(270deg);_x000D_
-o-transform: rotate(270deg);_x000D_
}_x000D_
.imagetest{_x000D_
overflow: hidden_x000D_
}
_x000D_
<article>_x000D_
<section class="photo">_x000D_
<div></div>_x000D_
<div class="imagetest">_x000D_
<img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSqVNRUwpfOwZ5n4kvVXea2VHd6QZGACVVaBOl5aJ2EGSG-WAIF" width=100%/>_x000D_
</div>_x000D_
</section>_x000D_
</article>
_x000D_
So, what I do is some calculations, in my example the picture is 455px width and 111px height and we have to add some margins based on these dimensions:
in CSS:
margin: calc((455px - 111px)/2) calc((111px - 455px)/2);
Result:
img{_x000D_
border: 1px solid #000;_x000D_
transform: rotate(270deg);_x000D_
-ms-transform: rotate(270deg);_x000D_
-moz-transform: rotate(270deg);_x000D_
-webkit-transform: rotate(270deg);_x000D_
-o-transform: rotate(270deg);_x000D_
/* 455 * 111 */_x000D_
margin: calc((455px - 111px)/2) calc((111px - 455px)/2);_x000D_
}
_x000D_
<article>_x000D_
<section class="photo">_x000D_
<div></div>_x000D_
<div class="imagetest">_x000D_
<img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSqVNRUwpfOwZ5n4kvVXea2VHd6QZGACVVaBOl5aJ2EGSG-WAIF" />_x000D_
</div>_x000D_
</section>_x000D_
</article>
_x000D_
I hope it helps someone!
No, it is not possible. Stack Overflow wants me to answer with a longer answer, so I will say no again.
Documentation: https://docs.microsoft.com/en-us/sql/t-sql/statements/backup-transact-sql#compatibility
Backups that are created by more recent version of SQL Server cannot be restored in earlier versions of SQL Server.
You may want to use a different structure altogether, but there are ways to do it in python 2.7.
d1 = OrderedDict([('a', '1'), ('b', '2')])
d2 = OrderedDict(c='3')
d2.update(d1)
d2 will then contain
>>> d2
OrderedDict([('c', '3'), ('a', '1'), ('b', '2')])
As mentioned by others, in python 3.2 you can use OrderedDict.move_to_end('c', last=False)
to move a given key after insertion.
Note: Take into consideration that the first option is slower for large datasets due to creation of a new OrderedDict and copying of old values.
if(stop = true)
should be if(stop == true)
, or simply (better!) if(stop)
.
This is actually a good opportunity to see a reason to why always use if(something)
if you want to see if it's true
instead of writing if(something == true)
(bad style!).
By doing stop = true
then you are assigning true
to stop
and not comparing.
So why the code below the if
statement executed?
See the JLS - 15.26. Assignment Operators:
At run time, the result of the assignment expression is the value of the variable after the assignment has occurred. The result of an assignment expression is not itself a variable.
So because you wrote stop = true
, then you're satisfying the if
condition.
I think you should need to check for isset and not empty value, like form was submitted without input data so isset will be true This will prevent you to have any error or notice.
if((isset($_POST['name'])) && !empty($_POST['name']))
{
$name = $_POST['name']; //note i used $_POST since you have a post form **method='post'**
echo $name;
}
If optimal performance is not a requirement and you just want something dead simple, you can define a basic function to test each character using the string class's built in "isspace" method:
def remove_space(input_string):
no_white_space = ''
for c in input_string:
if not c.isspace():
no_white_space += c
return no_white_space
Building the no_white_space
string this way will not have ideal performance, but the solution is easy to understand.
>>> remove_space('strip my spaces')
'stripmyspaces'
If you don't want to define a function, you can convert this into something vaguely similar with list comprehension. Borrowing from the top answer's join
solution:
>>> "".join([c for c in "strip my spaces" if not c.isspace()])
'stripmyspaces'
const FindDate = (date, allDate) => {
// moment().diff only works on moment(). Make sure both date and elements in allDate array are in moment format
let nearestDate = -1;
allDate.some(d => {
const currentDate = moment(d)
const difference = currentDate.diff(d); // Or d.diff(date) depending on what you're trying to find
if(difference >= 0){
nearestDate = d
}
});
console.log(nearestDate)
}
These files are from Maven wrapper. It works similarly to the Gradle wrapper.
This allows you to run the Maven project without having Maven installed and present on the path. It downloads the correct Maven version if it's not found (as far as I know by default in your user home directory).
The mvnw
file is for Linux (bash) and the mvnw.cmd
is for the Windows environment.
To create or update all necessary Maven Wrapper files execute the following command:
mvn -N io.takari:maven:wrapper
To use a different version of maven you can specify the version as follows:
mvn -N io.takari:maven:wrapper -Dmaven=3.3.3
Both commands require maven on PATH
(add the path to maven bin
to Path
on System Variables) if you already have mvnw in your project you can use ./mvnw
instead of mvn
in the commands.
If you can already see the SQL being printed, that means you have the code below in your hibernate.cfg.xml:
<property name="show_sql">true</property>
To print the bind parameters as well, add the following to your log4j.properties file:
log4j.logger.net.sf.hibernate.type=debug
You can leverage the browser's URL parser using an <a>
element:
var hostname = $('<a>').prop('href', url).prop('hostname');
or without jQuery:
var a = document.createElement('a');
a.href = url;
var hostname = a.hostname;
(This trick is particularly useful for resolving paths relative to the current page.)
Use the following function:
function get_hostname(url) {
var m = url.match(/^http:\/\/[^/]+/);
return m ? m[0] : null;
}
Use it like this:
get_hostname("http://example.com/path");
This will return http://example.com/
as in your example output.
If you are only trying the get the hostname of the current page, use document.location.hostname
.
You can't do this with CSS alone. Using jQuery you can do
HTML
<label id="lab">Checkbox</label>
<input id="check" type="checkbox" />
CSS
.highlight{
background:yellow;
}
jQuery
$('#check').click(function(){
$('#lab').toggleClass('highlight')
})
This will work in all browsers
If you're running SQL Server 2005, you can write a custom CLR aggregate function to handle this.
C# version:
using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using System.Text;
using Microsoft.SqlServer.Server;
[Serializable]
[Microsoft.SqlServer.Server.SqlUserDefinedAggregate(Format.UserDefined,MaxByteSize=8000)]
public class CSV:IBinarySerialize
{
private StringBuilder Result;
public void Init() {
this.Result = new StringBuilder();
}
public void Accumulate(SqlString Value) {
if (Value.IsNull) return;
this.Result.Append(Value.Value).Append(",");
}
public void Merge(CSV Group) {
this.Result.Append(Group.Result);
}
public SqlString Terminate() {
return new SqlString(this.Result.ToString());
}
public void Read(System.IO.BinaryReader r) {
this.Result = new StringBuilder(r.ReadString());
}
public void Write(System.IO.BinaryWriter w) {
w.Write(this.Result.ToString());
}
}
Put into a script I like something like that:
#!/bin/bash
set -o xtrace # remove me after debug
TABLE=some_table_name
DB_NAME=prod_database
BASE_DIR=/var/backups/someDir
LOCATION="${BASE_DIR}/myApp_$(date +%Y%m%d_%H%M%S)"
FNAME="${LOCATION}_${DB_NAME}_${TABLE}.sql"
# Create backups directory if not exists
if [[ ! -e $BASE_DIR ]];then
mkdir $BASE_DIR
chown -R postgres:postgres $BASE_DIR
fi
sudo -H -u postgres pg_dump --column-inserts --data-only --table=$TABLE $DB_NAME > $FNAME
sudo gzip $FNAME
If none of the above suggestions works for you, try using the style
attribute.
**Notes**
<p style="color:red;">ERROR: Setting focus didn't work for me when I tried from jupyter. However it worked well when I ran it from the terminal</p>
This gives me the following result
In addition to adding @Transactional
on @Test
method, you also need to add @Rollback(false)
It must work. I used to debug a .exe file and a dll at the same time ! What I suggest is 1) Include the path of the dll in your B project, 2) Then compile in debug your A project 3) Control that the path points on the A dll and de pdb file.... 4)After that you start in debug the B project and if all is ok, you will be able to debug in both projects !
Make sure your compiler is set to x86 if you are trying to reference an x86 dll...
I was having similar issues... as mentioned above, trying to use OLEDB to access an Excel file from my C# code in Visual Studio 2012.
I kept getting errors about the Access library not being accessible but I knew that I had loaded it.
During Debug, it dawned on me that I am compiling for 64 bit but have Office x86 loaded. Even though I loaded the Access library for 32 bit, it was never being used by the app... and was, therefore, not accessible.
Here is what I was using in C#:
"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + strFilePath + ";Extended Properties='Excel 12.0 Xml;HDR=Yes'";
...I was getting an error
As soon as I switched the compiler to x86 it worked
I have experienced same problem, I have tried below steps to solve the problem :-
Create sign apk with creating new keystore and new password.
Now create again sign apk by using your old keystore (keystore used at the time of previous apk build upload) but now use new keystore password.
Now definitely you will create successfully sign apk using old keystore.
You need to use the document.getElementsByClassName('class_name');
and dont forget that the returned value is an array of elements so if you want the first one use:
document.getElementsByClassName('class_name')[0]
UPDATE
Now you can use:
document.querySelector(".class_name")
to get the first element with the class_name
CSS class (null
will be returned if non of the elements on the page has this class name)
or document.querySelectorAll(".class_name")
to get a NodeList of elements with the class_name
css class (empty NodeList will be returned if non of. the elements on the the page has this class name).
I totally agree with @jemmons:
But this should not be the default pattern you follow when dealing with blocks that call self! This should only be used to break what would otherwise be a retain cycle between self and the block. If you were to adopt this pattern everywhere, you'd run the risk of passing a block to something that got executed after self was deallocated.
//SUSPICIOUS EXAMPLE: __weak MyObject *weakSelf = self; [[SomeOtherObject alloc] initWithCompletion:^{ //By the time this gets called, "weakSelf" might be nil because it's not retained! [weakSelf doSomething]; }];
To overcome this problem one can define a strong reference over the weakSelf
inside the block:
__weak MyObject *weakSelf = self;
[[SomeOtherObject alloc] initWithCompletion:^{
MyObject *strongSelf = weakSelf;
[strongSelf doSomething];
}];
Encoding.Unicode
is Microsoft's misleading name for UTF-16 (a double-wide encoding, used in the Windows world for historical reasons but not used by anyone else). http://msdn.microsoft.com/en-us/library/system.text.encoding.unicode.aspx
If you inspect your bytes
array, you'll see that every second byte is 0x00
(because of the double-wide encoding).
You should be using Encoding.UTF8.GetBytes
instead.
But also, you will see different results depending on whether or not you consider the terminating '\0'
byte to be part of the data you're hashing. Hashing the two bytes "Hi"
will give a different result from hashing the three bytes "Hi"
. You'll have to decide which you want to do. (Presumably you want to do whichever one your friend's PHP code is doing.)
For ASCII text, Encoding.UTF8
will definitely be suitable. If you're aiming for perfect compatibility with your friend's code, even on non-ASCII inputs, you'd better try a few test cases with non-ASCII characters such as é
and ?
and see whether your results still match up. If not, you'll have to figure out what encoding your friend is really using; it might be one of the 8-bit "code pages" that used to be popular before the invention of Unicode. (Again, I think Windows is the main reason that anyone still needs to worry about "code pages".)
This is an example that works on the AWS Cloud. The scenario is that some machine that booted from autoscaling needs to perform some action on another server, passing the newly spawned instance DNS via SSH
# Get the public DNS of the current machine (AWS specific)
MY_DNS=`curl -s http://169.254.169.254/latest/meta-data/public-hostname`
ssh \
-o StrictHostKeyChecking=no \
-i ~/.ssh/id_rsa \
[email protected] \
<< EOF
cd ~/
echo "Hey I was just SSHed by ${MY_DNS}"
run_other_commands
# Newline is important before final EOF!
EOF
Logically speaking Rohit's solution should have worked, but it didn't. I think SQL Management Studio messed up when trying to optimize this.
But by modifying the string before comparing them I was able to get the right results. This worked for me:
SELECT [ExternalId]
FROM [EquipmentSerialsMaster] where LOWER('0'+[ExternalId]) COLLATE Latin1_General_CS_AS != '0'+[ExternalId]
if you need to run the delete/insert/update you could also run dynamic statements. i.e.:
declare
@v_dynDelete NVARCHAR(500);
SET @v_dynDelete = 'DELETE some_table;';
EXEC @v_dynDelete
xxx >& filename
Or do this to see everything on the screen and have it go to your file:
xxx | & tee ./logfile
putty
cd $ADMIN_SCRIPTS_HOME
./adstpall.sh
drop table t;
This will workout..
Use like this.
List<String> stockList = new ArrayList<String>();
stockList.add("stock1");
stockList.add("stock2");
String[] stockArr = new String[stockList.size()];
stockArr = stockList.toArray(stockArr);
for(String s : stockArr)
System.out.println(s);
Here's my two cents.
As the other answers already state, you should use <pre>
</pre>
in conjuction with {@code
}
.
pre
and {@code}
<pre>
and </pre>
prevents your code from collapsing onto one line;{@code
}
prevents <
, >
and everything in between from disappearing. This is particularly useful when your code contains generics or lambda expressions.Problems with annotations
Problems can arise when your code block contains an annotation. That is probably because when the @
sign appears at the beginning of the Javadoc line, it is considered a Javadoc tag like @param
or @return
. For example, this code could be parsed incorrectly:
/**
* Example usage:
*
* <pre>{@code
* @Override
* public void someOverriddenMethod() {
Above code will disappear completely in my case.
To fix this, the line must not start with an @
sign:
/**
* Example usage:
*
* <pre>{@code @Override
* public int someMethod() {
* return 13 + 37;
* }
* }</pre>
*/
Note that there are two spaces between @code
and @Override
, to keep things aligned with the next lines. In my case (using Apache Netbeans) it is rendered correctly.
I found some detailed instructions here: http://digitallibraryworld.com/?p=6
The key piece of advice seems to be, don't use the 64-bit ASP.DLL (found in system32) if you've configured the app pool to run 32-bit applications (instead, use the 32-bit ASP.DLL).
Add a script map using the following setting:
Request Path: *.asp
Executable: C:\Windows\system32\inetsrv\asp.dll
Name: whatever you want. I named my Classic ASPThe executable above is 64 BIT ASP handler for your asp script. If you want your ASP script to be handled in 32 bit environment, you need to use executable from this location:
C:\Windows\SysWOW64\inetsrv\asp.dll
.
Of course, if you don't need to load any 32-bit libraries (or data providers, etc.), just make your life easier by running the 64-bit ASP.DLL!
Can I just ask about the long term need for this facility - is it for debuging purposes?
If so, then you may want to consider using a proper debugger, such as the one found in Visual Studio, as this allows you to step through the procedure in a more controlled way, and avoids having to constantly add/remove PRINT statement from the procedure.
Just my opinion, but I prefer the debugger approach - for code and databases.
The definition of the perfmon counters has been broken since the beginning and for some reason appears to be too hard to correct.
A good overview of Windows memory management is available in the video "Mysteries of Memory Management Revealed" on MSDN: It covers more topics than needed to track memory leaks (eg working set management) but gives enough detail in the relevant topics.
To give you a hint of the problem with the perfmon counter descriptions, here is the inside story about private bytes from "Private Bytes Performance Counter -- Beware!" on MSDN:
Q: When is a Private Byte not a Private Byte?
A: When it isn't resident.
The Private Bytes counter reports the commit charge of the process. That is to say, the amount of space that has been allocated in the swap file to hold the contents of the private memory in the event that it is swapped out. Note: I'm avoiding the word "reserved" because of possible confusion with virtual memory in the reserved state which is not committed.
From "Performance Planning" on MSDN:
3.3 Private Bytes
3.3.1 Description
Private memory, is defined as memory allocated for a process which cannot be shared by other processes. This memory is more expensive than shared memory when multiple such processes execute on a machine. Private memory in (traditional) unmanaged dlls usually constitutes of C++ statics and is of the order of 5% of the total working set of the dll.
It should be
document.getElementById("hidden").style.display = "block";
not
document.getElementById["hidden"].style.display = "block";
EDIT due to author edit:
Why are you using a <div>
here? Just add an ID to the table element and add a hidden style to it. E.g. <td id="hidden" style="display:none" class="depot_table_left">
I'm wondering if there is any way to get a value from a Promise or wait (block/sleep) until it has resolved, similar to .NET's IAsyncResult.WaitHandle.WaitOne(). I know JavaScript is single-threaded, but I'm hoping that doesn't mean that a function can't yield.
The current generation of Javascript in browsers does not have a wait()
or sleep()
that allows other things to run. So, you simply can't do what you're asking. Instead, it has async operations that will do their thing and then call you when they're done (as you've been using promises for).
Part of this is because of Javascript's single threadedness. If the single thread is spinning, then no other Javascript can execute until that spinning thread is done. ES6 introduces yield
and generators which will allow some cooperative tricks like that, but we're quite a ways from being able to use those in a wide swatch of installed browsers (they can be used in some server-side development where you control the JS engine that is being used).
Careful management of promise-based code can control the order of execution for many async operations.
I'm not sure I understand exactly what order you're trying to achieve in your code, but you could do something like this using your existing kickOff()
function, and then attaching a .then()
handler to it after calling it:
function kickOff() {
return new Promise(function(resolve, reject) {
$("#output").append("start");
setTimeout(function() {
resolve();
}, 1000);
}).then(function() {
$("#output").append(" middle");
return " end";
});
}
kickOff().then(function(result) {
// use the result here
$("#output").append(result);
});
This will return output in a guaranteed order - like this:
start
middle
end
Update in 2018 (three years after this answer was written):
If you either transpile your code or run your code in an environment that supports ES7 features such as async
and await
, you can now use await
to make your code "appear" to wait for the result of a promise. It is still developing with promises. It does still not block all of Javascript, but it does allow you to write sequential operations in a friendlier syntax.
Instead of the ES6 way of doing things:
someFunc().then(someFunc2).then(result => {
// process result here
}).catch(err => {
// process error here
});
You can do this:
// returns a promise
async function wrapperFunc() {
try {
let r1 = await someFunc();
let r2 = await someFunc2(r1);
// now process r2
return someValue; // this will be the resolved value of the returned promise
} catch(e) {
console.log(e);
throw e; // let caller know the promise was rejected with this reason
}
}
wrapperFunc().then(result => {
// got final result
}).catch(err => {
// got error
});
Its simple just try: sudo apt-get remove python3.7 or the versions that you want to remove
There is no .NET framework support for IMAP. You'll need to use some 3rd party component.
Try https://www.limilabs.com/mail, it's very affordable and easy to use, it also supports SSL:
using(Imap imap = new Imap())
{
imap.ConnectSSL("imap.company.com");
imap.Login("user", "password");
imap.SelectInbox();
List<long> uids = imap.SearchFlag(Flag.Unseen);
foreach (long uid in uids)
{
string eml = imap.GetMessageByUID(uid);
IMail message = new MailBuilder()
.CreateFromEml(eml);
Console.WriteLine(message.Subject);
Console.WriteLine(message.TextDataString);
}
imap.Close(true);
}
Please note that this is a commercial product I've created.
You can download it here: https://www.limilabs.com/mail.
<div id="google_translate_element"></div><script type="text/javascript">
function googleTranslateElementInit() {
new google.translate.TranslateElement({pageLanguage: 'en', includedLanguages: 'ar', layout: google.translate.TranslateElement.InlineLayout.SIMPLE}, 'google_translate_element');
}
</script><script type="text/javascript" src="//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"></script>
In iOS7 the URL that switch ur app to App Store for rate and review has changed:
itms-apps://itunes.apple.com/app/idAPP_ID
Where APP_ID need to be replaced with your Application ID.
For iOS 6 and older, URL in previous answers are working fine.
Source: Appirater
Enjoy Coding..!!
You can limit your textview's number of characters and add (...) after the text. Suppose You need to show 5 letters only and thereafter you need to show (...), Just do the following :
String YourString = "abcdefghijk";
if(YourString.length()>5){
YourString = YourString.substring(0,4)+"...";
your_text_view.setText(YourString);
}else{
your_text_view.setText(YourString); //Dont do any change
}
a little hack ^_^. Though its not a good solution. But a work around which worked for me :D
EDIT: I have added check for less character as per your limited no. of characters.
This lists all the gems I have installed.
gem query --local
http://guides.rubygems.org/command-reference/#gem-list
See 2.7 Listing all installed gems
From the man git-stash
page:
The modifications stashed away by this command can be listed with git stash list, inspected with git stash show
show [<stash>]
Show the changes recorded in the stash as a diff between the stashed state and
its original parent. When no <stash> is given, shows the latest one. By default,
the command shows the diffstat, but it will accept any format known to git diff
(e.g., git stash show -p stash@{1} to view the second most recent stash in patch
form).
To list the stashed modifications
git stash list
To show files changed in the last stash
git stash show
So, to view the content of the most recent stash, run
git stash show -p
To view the content of an arbitrary stash, run something like
git stash show -p stash@{1}
ok. I tried the above two ways but it didnt work for me. After trial and error i came to know that actually the file was not getting saved in 'this.state.file' variable.
fileUpload = (e) => {
let data = e.target.files
if(e.target.files[0]!=null){
this.props.UserAction.fileUpload(data[0], this.fallBackMethod)
}
}
here fileUpload is a different js file which accepts two params like this
export default (file , callback) => {
const formData = new FormData();
formData.append('fileUpload', file);
return dispatch => {
axios.put(BaseUrl.RestUrl + "ur/url", formData)
.then(response => {
callback(response.data);
}).catch(error => {
console.log("***** "+error)
});
}
}
don't forget to bind method in the constructor. Let me know if you need more help in this.
You could pass the messages as explicit URL parameter (appropriately encoded), or store the messages into session
(cookie) variable before redirecting and then get the variable before rendering the template. For example:
from flask import session, url_for
def do_baz():
messages = json.dumps({"main":"Condition failed on page baz"})
session['messages'] = messages
return redirect(url_for('.do_foo', messages=messages))
@app.route('/foo')
def do_foo():
messages = request.args['messages'] # counterpart for url_for()
messages = session['messages'] # counterpart for session
return render_template("foo.html", messages=json.loads(messages))
(encoding the session variable might not be necessary, flask may be handling it for you, but can't recall the details)
Or you could probably just use Flask Message Flashing if you just need to show simple messages.
I finally solved!! It's a Web Clip feature on Mac Devices. If a user want to add your website in Dock o Desktop it requests this icon.
You may want users to be able to add your web application
or webpage link to the Home screen. These links, represented
by an icon, are called Web Clips. Follow these simple steps
to specify an icon to represent your web application or webpage
on iOS.
how to solve?: Add a icon to solve problem.
Yes. IE7+ supports attribute selectors:
input[type=radio]
input[type^=ra]
input[type*=d]
input[type$=io]
Element input with attribute type which contains a value that is equal to, begins with, contains or ends with a certain value.
Other safe (IE7+) selectors are:
p > span { font-weight: bold; }
span ~ span { color: blue; }
Which for <p><span/><span/></p>
would effectively give you:
<p>
<span style="font-weight: bold;">
<span style="font-weight: bold; color: blue;">
</p>
Further reading: Browser CSS compatibility on quirksmode.com
I'm surprised that everyone else thinks it can't be done. CSS attribute selectors have been here for some time already. I guess it's time we clean up our .css files.
Try with :
echo "To: [email protected]" > /var/www/report.csv
echo "Subject: Subject" >> /var/www/report.csv
echo "MIME-Version: 1.0" >> /var/www/report.csv
echo "Content-Type: text/html; charset=\"us-ascii\"" >> /var/www/report.csv
echo "Content-Disposition: inline" >> /var/www/report.csv
echo "<html>" >> /var/www/report.csv
mysql -u ***** -p***** -H -e "select * from users LIMIT 20" dev >> /var/www/report.csv
echo "</html>" >> /var/www/report.csv
mail -s "Built notification" [email protected] < /var/www/report.csv
Yes, there is a way. Two in fact. In October 2013 jshint added a way to ignore blocks of code like this:
// Code here will be linted with JSHint.
/* jshint ignore:start */
// Code here will be ignored by JSHint.
/* jshint ignore:end */
// Code here will be linted with JSHint.
You can also ignore a single line with a trailing comment like this:
ignoreThis(); // jshint ignore:line
Until today (9 jan 2014) the Bootstrap 3 still not support sub menu dropdown.
I searched Google about responsive navigation menu and found this is the best i though.
It is Smart menus http://www.smartmenus.org/
I hope this is the way out for anyone who want navigation menu with multilevel sub menu.
update 2015-02-17 Smart menus are now fully support Bootstrap element style for submenu. For more information please look at Smart menus website.
If you use svn+ssh, you can copy your public ssh key to the remote machine:
ssh-copy-id user@remotehost
Update: The GSOC project and the code there isn't active, but this is: https://github.com/hierynomus/sshj
hierynomus took over as maintainer since early 2015. Here is the older, no longer maintained, Github link:
https://github.com/shikhar/sshj
There was a GSOC project:
http://code.google.com/p/commons-net-ssh/
Code quality seem to be better than JSch, which, while a complete and working implementation, lacks documentation. Project page spots an upcoming beta release, last commit to the repository was mid-august.
Compare the APIs:
http://code.google.com/p/commons-net-ssh/
SSHClient ssh = new SSHClient();
//ssh.useCompression();
ssh.loadKnownHosts();
ssh.connect("localhost");
try {
ssh.authPublickey(System.getProperty("user.name"));
new SCPDownloadClient(ssh).copy("ten", "/tmp");
} finally {
ssh.disconnect();
}
Session session = null;
Channel channel = null;
try {
JSch jsch = new JSch();
session = jsch.getSession(username, host, 22);
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.setPassword(password);
session.connect();
// exec 'scp -f rfile' remotely
String command = "scp -f " + remoteFilename;
channel = session.openChannel("exec");
((ChannelExec) channel).setCommand(command);
// get I/O streams for remote scp
OutputStream out = channel.getOutputStream();
InputStream in = channel.getInputStream();
channel.connect();
byte[] buf = new byte[1024];
// send '\0'
buf[0] = 0;
out.write(buf, 0, 1);
out.flush();
while (true) {
int c = checkAck(in);
if (c != 'C') {
break;
}
// read '0644 '
in.read(buf, 0, 5);
long filesize = 0L;
while (true) {
if (in.read(buf, 0, 1) < 0) {
// error
break;
}
if (buf[0] == ' ') {
break;
}
filesize = filesize * 10L + (long) (buf[0] - '0');
}
String file = null;
for (int i = 0;; i++) {
in.read(buf, i, 1);
if (buf[i] == (byte) 0x0a) {
file = new String(buf, 0, i);
break;
}
}
// send '\0'
buf[0] = 0;
out.write(buf, 0, 1);
out.flush();
// read a content of lfile
FileOutputStream fos = null;
fos = new FileOutputStream(localFilename);
int foo;
while (true) {
if (buf.length < filesize) {
foo = buf.length;
} else {
foo = (int) filesize;
}
foo = in.read(buf, 0, foo);
if (foo < 0) {
// error
break;
}
fos.write(buf, 0, foo);
filesize -= foo;
if (filesize == 0L) {
break;
}
}
fos.close();
fos = null;
if (checkAck(in) != 0) {
System.exit(0);
}
// send '\0'
buf[0] = 0;
out.write(buf, 0, 1);
out.flush();
channel.disconnect();
session.disconnect();
}
} catch (JSchException jsche) {
System.err.println(jsche.getLocalizedMessage());
} catch (IOException ioe) {
System.err.println(ioe.getLocalizedMessage());
} finally {
channel.disconnect();
session.disconnect();
}
}
They are two different metrics to evaluate your model's performance usually being used in different phases.
Loss is often used in the training process to find the "best" parameter values for your model (e.g. weights in neural network). It is what you try to optimize in the training by updating weights.
Accuracy is more from an applied perspective. Once you find the optimized parameters above, you use this metrics to evaluate how accurate your model's prediction is compared to the true data.
Let us use a toy classification example. You want to predict gender from one's weight and height. You have 3 data, they are as follows:(0 stands for male, 1 stands for female)
y1 = 0, x1_w = 50kg, x2_h = 160cm;
y2 = 0, x2_w = 60kg, x2_h = 170cm;
y3 = 1, x3_w = 55kg, x3_h = 175cm;
You use a simple logistic regression model that is y = 1/(1+exp-(b1*x_w+b2*x_h))
How do you find b1 and b2? you define a loss first and use optimization method to minimize the loss in an iterative way by updating b1 and b2.
In our example, a typical loss for this binary classification problem can be: (a minus sign should be added in front of the summation sign)
We don't know what b1 and b2 should be. Let us make a random guess say b1 = 0.1 and b2 = -0.03. Then what is our loss now?
so the loss is
Then you learning algorithm (e.g. gradient descent) will find a way to update b1 and b2 to decrease the loss.
What if b1=0.1 and b2=-0.03 is the final b1 and b2 (output from gradient descent), what is the accuracy now?
Let's assume if y_hat >= 0.5, we decide our prediction is female(1). otherwise it would be 0. Therefore, our algorithm predict y1 = 1, y2 = 1 and y3 = 1. What is our accuracy? We make wrong prediction on y1 and y2 and make correct one on y3. So now our accuracy is 1/3 = 33.33%
PS: In Amir's answer, back-propagation is said to be an optimization method in NN. I think it would be treated as a way to find gradient for weights in NN. Common optimization method in NN are GradientDescent and Adam.
I try this code, it works, and took from http://www.catamount.com/blog/1015/uiimage-extensions-for-cutting-scaling-and-rotating-uiimages/
+ (UIImage *)rotateImage:(UIImage*)src byRadian:(CGFloat)radian
{
// calculate the size of the rotated view's containing box for our drawing space
UIView *rotatedViewBox = [[UIView alloc] initWithFrame:CGRectMake(0,0, src.size.width, src.size.height)];
CGAffineTransform t = CGAffineTransformMakeRotation(radian);
rotatedViewBox.transform = t;
CGSize rotatedSize = rotatedViewBox.frame.size;
// Create the bitmap context
UIGraphicsBeginImageContext(rotatedSize);
CGContextRef bitmap = UIGraphicsGetCurrentContext();
// Move the origin to the middle of the image so we will rotate and scale around the center.
CGContextTranslateCTM(bitmap, rotatedSize.width/2, rotatedSize.height/2);
// // Rotate the image context
CGContextRotateCTM(bitmap, radian);
// Now, draw the rotated/scaled image into the context
CGContextScaleCTM(bitmap, 1.0, -1.0);
CGContextDrawImage(bitmap, CGRectMake(-src.size.width / 2, -src.size.height / 2, src.size.width, src.size.height), [src CGImage]);
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
You didn't specify which flavor of regex you're using, but this will work in any of the most popular ones that can be considered "complete".
/.+?(?=abc)/
The .+?
part is the un-greedy version of .+
(one or more of
anything). When we use .+
, the engine will basically match everything.
Then, if there is something else in the regex it will go back in steps
trying to match the following part. This is the greedy behavior,
meaning as much as possible to satisfy.
When using .+?
, instead of matching all at once and going back for
other conditions (if any), the engine will match the next characters by
step until the subsequent part of the regex is matched (again if any).
This is the un-greedy, meaning match the fewest possible to
satisfy.
/.+X/ ~ "abcXabcXabcX" /.+/ ~ "abcXabcXabcX"
^^^^^^^^^^^^ ^^^^^^^^^^^^
/.+?X/ ~ "abcXabcXabcX" /.+?/ ~ "abcXabcXabcX"
^^^^ ^
Following that we have (?=
{contents}
)
, a zero width
assertion, a look around. This grouped construction matches its
contents, but does not count as characters matched (zero width). It
only returns if it is a match or not (assertion).
Thus, in other terms the regex /.+?(?=abc)/
means:
Match any characters as few as possible until a "abc" is found, without counting the "abc".
To use getSingleResult on a TypedQuery you can use
query.setFirstResult(0);
query.setMaxResults(1);
result = query.getSingleResult();
An immutable object is the one you cannot modify after you create it. A typical example are string literals.
A D programming language, which becomes increasingly popular, has a notion of "immutability" through "invariant" keyword. Check this Dr.Dobb's article about it - http://dobbscodetalk.com/index.php?option=com_myblog&show=Invariant-Strings.html&Itemid=29 . It explains the problem perfectly.