Here is a simple letter-range implementation:
Code
def letter_range(start, stop="{", step=1):
"""Yield a range of lowercase letters."""
for ord_ in range(ord(start.lower()), ord(stop.lower()), step):
yield chr(ord_)
Demo
list(letter_range("a", "f"))
# ['a', 'b', 'c', 'd', 'e']
list(letter_range("a", "f", step=2))
# ['a', 'c', 'e']
A simple answer would be (26 characters):
String.fromCharCode(97+n);
If space is precious you could do the following (20 characters):
(10+n).toString(36);
Think about what you could do with all those extra bytes!
How this works is you convert the number to base 36, so you have the following characters:
0123456789abcdefghijklmnopqrstuvwxyz
^ ^
n n+10
By offsetting by 10 the characters start at a
instead of 0
.
Not entirely sure about how fast running the two different examples client-side would compare though.
Surprised no one has suggested a yield solution:
public static IEnumerable<char> Alphabet()
{
for (char letter = 'A'; letter <= 'Z'; letter++)
{
yield return letter;
}
}
Example:
foreach (var c in Alphabet())
{
Console.Write(c);
}
Based on solution You've already found How to apply CSS to iframe?:
var cssLink = document.createElement("link")
cssLink.href = "file://path/to/style.css";
cssLink .rel = "stylesheet";
cssLink .type = "text/css";
frames['iframe'].document.body.appendChild(cssLink);
or more jqueryish (from Append a stylesheet to an iframe with jQuery):
var $head = $("iframe").contents().find("head");
$head.append($("<link/>",
{ rel: "stylesheet", href: "file://path/to/style.css", type: "text/css" }));
as for security issues: Disabling same-origin policy in Safari
You can convert, but I don't think there's anything built in to do it automatically:
public static int[] convertIntegers(List<Integer> integers)
{
int[] ret = new int[integers.size()];
for (int i=0; i < ret.length; i++)
{
ret[i] = integers.get(i).intValue();
}
return ret;
}
(Note that this will throw a NullPointerException if either integers
or any element within it is null
.)
EDIT: As per comments, you may want to use the list iterator to avoid nasty costs with lists such as LinkedList
:
public static int[] convertIntegers(List<Integer> integers)
{
int[] ret = new int[integers.size()];
Iterator<Integer> iterator = integers.iterator();
for (int i = 0; i < ret.length; i++)
{
ret[i] = iterator.next().intValue();
}
return ret;
}
Elaborating from DavidG answer which is really near of what is required for a basic solution:
First, configure the OPTIONSVerbHandler to execute before .Net handlers.
You can also do this in web.config by redefining all handlers under <system.webServer><handlers>
(<clear>
then <add ...>
them back, this is what does the IIS console for you) (By the way, there is no need to ask for "read" permission on this handler.)
Second, configure custom http headers for your cors needs, such as:
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*"/>
<add name="Access-Control-Allow-Headers" value="Content-Type"/>
<add name="Access-Control-Allow-Methods" value="POST,GET,OPTIONS"/>
</customHeaders>
</httpProtocol>
</system.webServer>
You can also do this in IIS console.
This is a basic solution since it will send cors headers even on request which does not requires it. But with WCF, it looks like being the simpliest one.
With MVC or webapi, we could instead handle OPTIONS verb and cors headers by code (either "manually" or with built-in support available in latest version of webapi).
AdventureWorksDataContext db = new AdventureWorksDataContext();
db.Log = Console.Out;
// Get hte first customer record
Customer c = from cust in db.Customers select cust where id = 5;
Console.WriteLine(c.CustomerType);
c.CustomerType = 'I';
db.SubmitChanges(); // Save the changes away
More efficient ways of concatenating strings are:
join():
Very efficent, but a bit hard to read.
>>> Section = 'C_type'
>>> new_str = ''.join(['Sec_', Section]) # inserting a list of strings
>>> print new_str
>>> 'Sec_C_type'
String formatting:
Easy to read and in most cases faster than '+' concatenating
>>> Section = 'C_type'
>>> print 'Sec_%s' % Section
>>> 'Sec_C_type'
If you use a CSS sprite for the background images, you could bump the background offset +/- n pixels depending on whether you were expanding or collapsing. Not a toggle, but closer to it than having to switch background image URLs.
You can use the onload=""
HTML attribute and use JavaScript to adjust the opacity style of your element.
Leave your CSS as you proposed. Edit your HTML code to:
<body onload="document.getElementById(test).style.opacity='1'">
<div id="test">
<p>?This is a test</p>
</div>
</body>
This also works to fade-in the complete page when finished loading:
HTML:
<body onload="document.body.style.opacity='1'">
</body>
CSS:
body{
opacity: 0;
transition: opacity 2s;
-webkit-transition: opacity 2s; /* Safari */
}
Check the W3Schools website: transitions and an article for changing styles with JavaScript.
If there is a failed merge, which is the most common reason for wanting to undo a git pull
, running git reset --merge
does exactly what one would expect: keep the fetched files, but undo the merge that git pull
attempted to merge. Then one can decide what to do without the clutter that git merge
sometimes generates. And it does not need one to find the exact commit ID which --hard
mentioned in every other answer requires.
Try this;
string.Format(new CultureInfo("en-SG", false), "{0:c0}", 123423.083234);
It will convert 123423.083234 to $1,23,423 format.
Another option is to transform your data so that the effect of outliers is mitigated. You can do this by winsorizing your data.
import pandas as pd
from scipy.stats import mstats
%matplotlib inline
test_data = pd.Series(range(30))
test_data.plot()
# Truncate values to the 5th and 95th percentiles
transformed_test_data = pd.Series(mstats.winsorize(test_data, limits=[0.05, 0.05]))
transformed_test_data.plot()
See this blog post. It uses jQuery, but it should help you even if you are not using it.
Basically you add this to your document.ready()
$('iframe').load(function() {
RunAfterIFrameLoaded();
});
select replace(ImagePath, '~/', '../') as NewImagePath from tblMyTable
where "ImagePath" is my column Name.
"NewImagePath" is temporery column Name insted of "ImagePath"
"~/" is my current string.(old string)
"../" is my requried string.(new string)
"tblMyTable" is my table in database.
$('select').val('')
I simply used this on the select itself and it did the trick.
I'm on jQuery 1.7.1.
You could also use a DynamicProxy
to extend the Dispose()
method. This way you could do something like:
using (var wrapperdProxy = new Proxy<yourProxy>())
{
// Do whatever and dispose of Proxy<yourProxy> will be called and work properly.
}
scanf
needs to know the size of the data being pointed at by &d
to fill it properly, whereas variadic functions promote floats to doubles (not entirely sure why), so printf
is always getting a double
.
This date function below achieves the desired effect without an additional script library. Basically it's just a simple date component concatenation in the right format, and augmenting of the Date object's prototype.
Date.prototype.dateToISO8601String = function() {
var padDigits = function padDigits(number, digits) {
return Array(Math.max(digits - String(number).length + 1, 0)).join(0) + number;
}
var offsetMinutes = this.getTimezoneOffset();
var offsetHours = offsetMinutes / 60;
var offset= "Z";
if (offsetHours < 0)
offset = "-" + padDigits(offsetHours.replace("-","") + "00",4);
else if (offsetHours > 0)
offset = "+" + padDigits(offsetHours + "00", 4);
return this.getFullYear()
+ "-" + padDigits((this.getUTCMonth()+1),2)
+ "-" + padDigits(this.getUTCDate(),2)
+ "T"
+ padDigits(this.getUTCHours(),2)
+ ":" + padDigits(this.getUTCMinutes(),2)
+ ":" + padDigits(this.getUTCSeconds(),2)
+ "." + padDigits(this.getUTCMilliseconds(),2)
+ offset;
}
Date.dateFromISO8601 = function(isoDateString) {
var parts = isoDateString.match(/\d+/g);
var isoTime = Date.UTC(parts[0], parts[1] - 1, parts[2], parts[3], parts[4], parts[5]);
var isoDate = new Date(isoTime);
return isoDate;
}
function test() {
var dIn = new Date();
var isoDateString = dIn.dateToISO8601String();
var dOut = Date.dateFromISO8601(isoDateString);
var dInStr = dIn.toUTCString();
var dOutStr = dOut.toUTCString();
console.log("Dates are equal: " + (dInStr == dOutStr));
}
Usage:
var d = new Date();
console.log(d.dateToISO8601String());
Hopefully this helps someone else.
EDIT
Corrected UTC issue mentioned in comments, and credit to Alex for the dateFromISO8601
function.
USE MyDatabase
SELECT Count(*)
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = 'BASE TABLE';
to get table counts
SELECT COUNT(*)
FROM information_schema.tables
WHERE table_schema = 'dbName';
this also works
USE databasename;
SHOW TABLES;
SELECT FOUND_ROWS();
Using id for this task is not an option in many cases. For example - table with twitter statuses. Here is a variant with specified timestamp field.
delete from table
where access_time >=
(
select access_time from
(
select access_time from table
order by access_time limit 150000,1
) foo
)
If you want to run the script directly, you can:
PYTHONPATH
).sys.path
in the your script.Then:
import module_you_wanted
Even though utf8_decode
is a useful solution, I prefer to correct the encoding errors on the table itself. In my opinion it is better to correct the bad characters themselves than making "hacks" in the code. Simply do a replace
on the field on the table. To correct the bad encoded characters from OP :
update <table> set <field> = replace(<field>, "ë", "ë")
update <table> set <field> = replace(<field>, "Ã", "à")
update <table> set <field> = replace(<field>, "ì", "ì")
update <table> set <field> = replace(<field>, "ù", "ù")
Where <table>
is the name of the mysql table and <field>
is the name of the column in the table. Here is a very good check-list for those typically bad encoded windows-1252 to utf-8 characters -> Debugging Chart Mapping Windows-1252 Characters to UTF-8 Bytes to Latin-1 Characters.
Remember to backup your table before trying to replace any characters with SQL!
[I know this is an answer to a very old question, but was facing the issue once again. Some old windows machine didnt encoded the text correct before inserting it to the utf8_general_ci collated table.]
In a simple terms if you have a web service of calculator. WSDL tells about the functions that you can implement or exposed to the client. For example: add, delete, subtract and so on. Where as using SOAP you actually perform actions like doDelete(), doSubtract(), doAdd(). So SOAP and WSDL are apples and oranges. We should not compare them. They both have their own different functionality.
It could be any one of the parameter, not just the file name or alias - for me it was the Key Password.
In your custom adapter inside getView method :
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Do things Here
}
});
If you just want to have a string representation of an object, you could use the JSON.stringify
function, using a JSON library.
This ought to work:
^\d+\s?(\([^\)]+\)\s?)?Z$
Haven't tested it though, but let me give you the breakdown, so if there are any bugs left they should be pretty straightforward to find:
First the beginning:
^ = beginning of string
\d+ = one or more decimal characters
\s? = one optional whitespace
Then this part:
(\([^\)]+\)\s?)?
Is actually:
(.............)?
Which makes the following contents optional, only if it exists fully
\([^\)]+\)\s?
\( = an opening bracket
[^\)]+ = a series of at least one character that is not a closing bracket
\) = followed by a closing bracket
\s? = followed by one optional whitespace
And the end is made up of
Z$
Where
Z = your constant string
$ = the end of the string
In my situation I needed to answer some questions without Y or N but with text or blank. I found the best way to do this in my situation was to create a shellscript file. In my case I called it autocomplete.sh
I was needing to answer some questions for a doctrine schema exporter so my file looked like this.
-- This is an example only --
php vendor/bin/mysql-workbench-schema-export mysqlworkbenchfile.mwb ./doctrine << EOF
`#Export to Doctrine Annotation Format` 1
`#Would you like to change the setup configuration before exporting` y
`#Log to console` y
`#Log file` testing.log
`#Filename [%entity%.%extension%]`
`#Indentation [4]`
`#Use tabs [no]`
`#Eol delimeter (win, unix) [win]`
`#Backup existing file [yes]`
`#Add generator info as comment [yes]`
`#Skip plural name checking [no]`
`#Use logged storage [no]`
`#Sort tables and views [yes]`
`#Export only table categorized []`
`#Enhance many to many detection [yes]`
`#Skip many to many tables [yes]`
`#Bundle namespace []`
`#Entity namespace []`
`#Repository namespace []`
`#Use automatic repository [yes]`
`#Skip column with relation [no]`
`#Related var name format [%name%%related%]`
`#Nullable attribute (auto, always) [auto]`
`#Generated value strategy (auto, identity, sequence, table, none) [auto]`
`#Default cascade (persist, remove, detach, merge, all, refresh, ) [no]`
`#Use annotation prefix [ORM\]`
`#Skip getter and setter [no]`
`#Generate entity serialization [yes]`
`#Generate extendable entity [no]` y
`#Quote identifier strategy (auto, always, none) [auto]`
`#Extends class []`
`#Property typehint [no]`
EOF
The thing I like about this strategy is you can comment what your answers are and using EOF a blank line is just that (the default answer). Turns out by the way this exporter tool has its own JSON counterpart for answering these questions, but I figured that out after I did this =).
to run the script simply be in the directory you want and run 'sh autocomplete.sh'
in terminal.
In short by using << EOL & EOF in combination with Return Lines you can answer each question of the prompt as necessary. Each new line is a new answer.
My example just shows how this can be done with comments also using the ` character so you remember what each step is.
Note the other advantage of this method is you can answer with more then just Y or N ... in fact you can answer with blanks!
Hope this helps someone out.
On my CentOS 6 I have two openssl.cnf :
/openvpn/easy-rsa/
/pki/tls/
That character is the BOM or "Byte Order Mark". It is usually received as the first few bytes of a file, telling you how to interpret the encoding of the rest of the data. You can simply remove the character to continue. Although, since the error says you were trying to convert to 'ascii', you should probably pick another encoding for whatever you were trying to do.
If you want to select particular element use below code
var gridRowData = $("<your grid name>").data("kendoGrid");
var selectedItem = gridRowData.dataItem(gridRowData.select());
var quote = selectedItem["<column name>"];
Matthew's supremely efficient script updated to use the dm_exec_sessions DMV, replacing the deprecated sysprocesses system table:
USE [master];
GO
DECLARE @Kill VARCHAR(8000) = '';
SELECT
@Kill = @Kill + 'kill ' + CONVERT(VARCHAR(5), session_id) + ';'
FROM
sys.dm_exec_sessions
WHERE
database_id = DB_ID('<YourDB>');
EXEC sys.sp_executesql @Kill;
Alternative using WHILE loop (if you want to process any other operations per execution):
USE [master];
GO
DECLARE @DatabaseID SMALLINT = DB_ID(N'<YourDB>');
DECLARE @SQL NVARCHAR(10);
WHILE EXISTS ( SELECT
1
FROM
sys.dm_exec_sessions
WHERE
database_id = @DatabaseID )
BEGIN;
SET @SQL = (
SELECT TOP 1
N'kill ' + CAST(session_id AS NVARCHAR(5)) + ';'
FROM
sys.dm_exec_sessions
WHERE
database_id = @DatabaseID
);
EXEC sys.sp_executesql @SQL;
END;
You cannot avoid this unless you distribute an application via the App Store.
You get this message because the application is signed via an enterprise certificate that has not yet been trusted by the user. Apple force this prompt to appear because the application that is being installed hasn't gone through the App Store review process so is technically untrusted.
Once the user has accepted the prompt, the certificate will be marked as trusted and the application can be installed (along with any other future applications that you wish to install that have been signed with the same certificate)
Note: As pointed out in the comments, as of iOS 8, uninstalling all applications from a specific certificate will cause the prompt to be shown again once an application from said certificate is re-installed.
Here is the link to Apple website that confirms this info: https://support.apple.com/en-us/HT204460
In python 3s print function:
lst = [1, 2, 3]
print('My list:', *lst, sep='\n- ')
Output:
My list:
- 1
- 2
- 3
Con: The sep
must be a string, so you can't modify it based on which element you're printing. And you need a kind of header to do this (above it was 'My list:'
).
Pro: You don't have to join()
a list into a string object, which might be advantageous for larger lists. And the whole thing is quite concise and readable.
Just add remove_button_css as class to your button tag. You can verify the code for Link 1
.remove_button_css {
outline: none;
padding: 5px;
border: 0px;
box-sizing: none;
background-color: transparent;
}
Extra Styles Edit
Add color: #337ab7;
and :hover
and :focus
to match OOTB (bootstrap3)
.remove_button_css:focus,
.remove_button_css:hover {
color: #23527c;
text-decoration: underline;
}
I use a combined version:
if(session_id() == '' || !isset($_SESSION)) {
// session isn't started
session_start();
}
Reading the file is easier done with the static File
class:
// First read all the text into a single string.
string text = File.ReadAllText(FileName);
// Then split the lines at "\r\n".
string[] stringSeparators = new string[] { "\r\n" };
string[] lines = text.Split(stringSeparators, StringSplitOptions.None);
// Finally replace lonely '\r' and '\n' by whitespaces in each line.
foreach (string s in lines) {
Console.WriteLine(s.Replace('\r', ' ').Replace('\n', ' '));
}
Note: The text might also contain vertical tabulators \v
. Those are used by Microsoft Word as manual linebreaks.
In order to catch any possible kind of breaks, you could use regex for the replacement
Console.WriteLine(Regex.Replace(s, @"[\f\n\r\t\v]", " "));
Here an option using a list written on some range, populating an array that will be fiiltered. The information will be erased then the columns sorted.
Sub Filter_Out_Values()
'Automation to remove some codes from the list
Dim ws, ws1 As Worksheet
Dim myArray() As Variant
Dim x, lastrow As Long
Dim cell As Range
Set ws = Worksheets("List")
Set ws1 = Worksheets(8)
lastrow = ws.Cells(Application.Rows.Count, 1).End(xlUp).Row
'Go through the list of codes to exclude
For Each cell In ws.Range("A2:A" & lastrow)
If cell.Offset(0, 2).Value = "X" Then 'If the Code is associated with "X"
ReDim Preserve myArray(x) 'Initiate array
myArray(x) = CStr(cell.Value) 'Populate the array with the code
x = x + 1 'Increase array capacity
ReDim Preserve myArray(x) 'Redim array
End If
Next cell
lastrow = ws1.Cells(Application.Rows.Count, 1).End(xlUp).Row
ws1.Range("C2:C" & lastrow).AutoFilter field:=3, Criteria1:=myArray, Operator:=xlFilterValues
ws1.Range("A2:Z" & lastrow).SpecialCells(xlCellTypeVisible).ClearContents
ws1.Range("A2:Z" & lastrow).AutoFilter field:=3
'Sort columns
lastrow = ws1.Cells(Application.Rows.Count, 1).End(xlUp).Row
'Sort with 2 criteria
With ws1.Range("A1:Z" & lastrow)
.Resize(lastrow).Sort _
key1:=ws1.Columns("B"), order1:=xlAscending, DataOption1:=xlSortNormal, _
key2:=ws1.Columns("D"), order1:=xlAscending, DataOption1:=xlSortNormal, _
Header:=xlYes, MatchCase:=False, Orientation:=xlTopToBottom, SortMethod:=xlPinYin
End With
End Sub
grep astring myfile -A 5 -B 5
That will grep "myfile" for "astring", and show 5 lines before and after each match
If your html is styled with css, you can probably link different style sheets for different sizes.
>>> a="Hello\u2026"
>>> print a.decode('unicode-escape')
Hello…
The previous answers did not work for me, but this did:
docker stop $(docker ps -q --filter ancestor=<image-name> )
max-age When an intermediate cache is forced, by means of a max-age=0 directive, to revalidate its own cache entry, and the client has supplied its own validator in the request, the supplied validator might differ from the validator currently stored with the cache entry. In this case, the cache MAY use either validator in making its own request without affecting semantic transparency. However, the choice of validator might affect performance. The best approach is for the intermediate cache to use its own validator when making its request. If the server replies with 304 (Not Modified), then the cache can return its now validated copy to the client with a 200 (OK) response. If the server replies with a new entity and cache validator, however, the intermediate cache can compare the returned validator with the one provided in the client's request, using the strong comparison function. If the client's validator is equal to the origin server's, then the intermediate cache simply returns 304 (Not Modified). Otherwise, it returns the new entity with a 200 (OK) response. If a request includes the no-cache directive, it SHOULD NOT include min-fresh, max-stale, or max-age.
courtesy: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9.4
Don't accept this as answer - I will have to read it to understand the true usage of it :)
Not sure why none of these seemed to work for me; the one that finally did it was:
$state.reload($state.current.name);
This was with Angular 1.4.0
Based on Henk's answer I have been able to come up with the specific domain, the method I want to allow and also the header I want to enable CORS for:
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
options.AddPolicy("AllowSpecific", p => p.WithOrigins("http://localhost:1233")
.WithMethods("GET")
.WithHeaders("name")));
services.AddMvc();
}
usage:
[EnableCors("AllowSpecific")]
If you want to test private methods, have a look at PrivateObject
and PrivateType
in the Microsoft.VisualStudio.TestTools.UnitTesting
namespace. They offer easy to use wrappers around the necessary reflection code.
Docs: PrivateType, PrivateObject
For VS2017 & 2019, you can find these by downloading the MSTest.TestFramework nuget
Maven can be used for the purpose, you need to add some dependencies and just clean your application. You will get all classes created automatically in your target folder.
Just copy them from target to desired place, here is pom.xml
that I have used to create classed from xsd
files:
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>jaxb2-maven-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>xjc</goal>
</goals>
</execution>
</executions>
<configuration>
<schemaDirectory>src/main/webapp/schemas/</schemaDirectory>
</configuration>
</plugin>
Just place your xsd files under src/main/webapp/schemas/
and maven will find them at compile time.
Hope this will help you, more information can be found at http://www.beingjavaguys.com/2013/04/create-spring-web-services-using-maven.html
There is apparently a lot of misunderstanding about this!
The only practical difference between KeyDown
and KeyPress
is that KeyPress
relays the character resulting from a keypress, and is only called if there is one.
In other words, if you press A on your keyboard, you'll get this sequence of events:
But if you press Shift+A, you'll get:
If you hold down the keys for a while, you'll get something like:
Notice that KeyPress
occurs in between KeyDown
and KeyUp
, not after KeyUp
, as many of the other answers have stated, that KeyPress
is not called when a character isn't generated, and that KeyDown
is repeated while the key is held down, also contrary to many of the other answers.
Examples of keys that do not directly result in calls to KeyPress
:
Examples of keys that do result in calls to KeyPress
:
For the curious, KeyDown
roughly correlates to WM_KEYDOWN
, KeyPress
to WM_CHAR
, and KeyUp
to WM_KEYUP
. WM_KEYDOWN
can be called fewer than the the number of key repeats, but it sends a repeat count, which, IIRC, WinForms uses to generate exactly one KeyDown per repeat.
Isn't this the same:
if ((checkbox.checked || columnname != A2) &&
columnname != a && columnname != b && columnname != c)
{
"statement 1"
}
MicroMVC has a 13 KB ORM that only relies on a 8 KB database class. It also returns all results as ORM objects themselves and uses late static binding to avoid embedding information about the current object's table and meta data into each object. This results in the cheapest ORM overhead there is.
It works with MySQL, PostgreSQL, and SQLite.
SELECT cast( cast(round(37.0/38.0,2) AS DECIMAL(18,2)) as varchar(100)) + ' %'
RESULT: 0.97 %
You have a few different options:
Visit the properties of the .xib files in the file inspector ,the property "Target Membership" pitch on the select box, then your xib file was linked with your target
Found all answers useful, just wanted to add one more use case.
In a composite WPF scenario, your user control can make use of resources defined in any other parent window/control (that is going to host this user control) by referring to that resource as DynamicResource.
As mentioned by others, Staticresource will be looked up at compile time. User controls can not refer to those resources which are defined in hosting/parent control. Though, DynamicResource could be used in this case.
I encountered the same issue and lateron found out that, I have missed call to super.onCreate( savedInstanceState );
in onCreate()
of FragmentActivity.
Your code is
urlpatterns = [
url(r'^$', 'myapp.views.home'),
url(r'^contact/$', 'myapp.views.contact'),
url(r'^login/$', 'django.contrib.auth.views.login'),
]
change it to following as you're importing include()
function :
urlpatterns = [
url(r'^$', views.home),
url(r'^contact/$', views.contact),
url(r'^login/$', views.login),
]
I encountered this running a brand new project. Neither the Allow or Always Allow button seemed to work, however it wasn't giving me the 'incorrect password' shaking feedback. What was happening was that there were multiple dialog boxes all in the same position, so as I entered a password and clicked Allow nothing changed visually. I ended up having at least 3 dialogs all stacked up on each other, which I only discovered when I tried dragging the dialog. Entering passwords into each of them let my project finish building.
flex
and inline-flex
both apply flex layout to children of the container. Container with display:flex
behaves like a block-level element itself, while display:inline-flex
makes the container behaves like an inline element.
Perhaps your code is behind Sheet1, so when you change the focus to Sheet2 the objects cannot be found? If that's the case, simply specifying your target worksheet might help:
Sheets("Sheet1").Range("C21").Select
I'm not very familiar with how Select works because I try to avoid it as much as possible :-). You can define and manipulate ranges without selecting them. Also it's a good idea to be explicit about everything you reference. That way, you don't lose track if you go from one sheet or workbook to another. Try this:
Option Explicit
Sub CopySheet1_to_PasteSheet2()
Dim CLastFundRow As Integer
Dim CFirstBlankRow As Integer
Dim wksSource As Worksheet, wksDest As Worksheet
Dim rngStart As Range, rngSource As Range, rngDest As Range
Set wksSource = ActiveWorkbook.Sheets("Sheet1")
Set wksDest = ActiveWorkbook.Sheets("Sheet2")
'Finds last row of content
CLastFundRow = wksSource.Range("C21").End(xlDown).Row
'Finds first row without content
CFirstBlankRow = CLastFundRow + 1
'Copy Data
Set rngSource = wksSource.Range("A2:C" & CLastFundRow)
'Paste Data Values
Set rngDest = wksDest.Range("A21")
rngSource.Copy
rngDest.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
'Bring back to top of sheet for consistancy
wksDest.Range("A1").Select
End Sub
In working with a similar problem I created the following function after combining a lot of resources I ran into on the web, and adding my own cookie handling. Hopefully this is useful to someone else.
function get_web_page( $url, $cookiesIn = '' ){
$options = array(
CURLOPT_RETURNTRANSFER => true, // return web page
CURLOPT_HEADER => true, //return headers in addition to content
CURLOPT_FOLLOWLOCATION => true, // follow redirects
CURLOPT_ENCODING => "", // handle all encodings
CURLOPT_AUTOREFERER => true, // set referer on redirect
CURLOPT_CONNECTTIMEOUT => 120, // timeout on connect
CURLOPT_TIMEOUT => 120, // timeout on response
CURLOPT_MAXREDIRS => 10, // stop after 10 redirects
CURLINFO_HEADER_OUT => true,
CURLOPT_SSL_VERIFYPEER => true, // Validate SSL Certificates
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_COOKIE => $cookiesIn
);
$ch = curl_init( $url );
curl_setopt_array( $ch, $options );
$rough_content = curl_exec( $ch );
$err = curl_errno( $ch );
$errmsg = curl_error( $ch );
$header = curl_getinfo( $ch );
curl_close( $ch );
$header_content = substr($rough_content, 0, $header['header_size']);
$body_content = trim(str_replace($header_content, '', $rough_content));
$pattern = "#Set-Cookie:\\s+(?<cookie>[^=]+=[^;]+)#m";
preg_match_all($pattern, $header_content, $matches);
$cookiesOut = implode("; ", $matches['cookie']);
$header['errno'] = $err;
$header['errmsg'] = $errmsg;
$header['headers'] = $header_content;
$header['content'] = $body_content;
$header['cookies'] = $cookiesOut;
return $header;
}
You can do it with AJAX !
For PUT
method :
$.ajax({
url: 'path.php',
type: 'PUT',
success: function(data) {
//play with data
}
});
For DELETE
method :
$.ajax({
url: 'path.php',
type: 'DELETE',
success: function(data) {
//play with data
}
});
There is nothing much to add to your code except appending the li tag to the ul
ul.appendChild(li)
and there you go just add this to your function and then it should work.
Instead of - fd.append( 'userfile', $('#userfile')[0].files[0]);
Use - fd.append( 'file', $('#userfile')[0].files[0]);
For character processing, use Unicode strings:
PythonWin 3.3.0 (v3.3.0:bd8afb90ebf2, Sep 29 2012, 10:57:17) [MSC v.1600 64 bit (AMD64)] on win32.
>>> s='ABC??def'
>>> import re
>>> re.sub(r'[^\x00-\x7f]',r' ',s) # Each char is a Unicode codepoint.
'ABC def'
>>> b = s.encode('utf8')
>>> re.sub(rb'[^\x00-\x7f]',rb' ',b) # Each char is a 3-byte UTF-8 sequence.
b'ABC def'
But note you will still have a problem if your string contains decomposed Unicode characters (separate character and combining accent marks, for example):
>>> s = 'mañana'
>>> len(s)
6
>>> import unicodedata as ud
>>> n=ud.normalize('NFD',s)
>>> n
'man~ana'
>>> len(n)
7
>>> re.sub(r'[^\x00-\x7f]',r' ',s) # single codepoint
'ma ana'
>>> re.sub(r'[^\x00-\x7f]',r' ',n) # only combining mark replaced
'man ana'
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// run the code making use of getActivity() from here
}
var value = fac.GetCachedValue("Auto Print Clinical Warnings")
// 0 = Start at the first character
// 1 = The length of the string to grab
if (value.ToLower().SubString(0, 1) == "y")
{
// Do your stuff.
}
Use an object (key/value pairs, the nearest JavaScript has to an associative array) for this and not the array object. Other than that, I believe that is the most elegant way
var foo = {};
foo['alfa'] = "first item";
foo['beta'] = "second item";
for (var key in foo) {
console.log(key);
}
Note: JavaScript doesn't guarantee any particular order for the properties. So you cannot expect the property that was defined first to appear first, it might come last.
EDIT:
In response to your comment, I believe that this article best sums up the cases for why arrays in JavaScript should not be used in this fashion -
You can use map
. Here is an example implementation:
case 'SOME_ACTION':
return {
...state,
contents: state.contents.map(
(content, i) => i === 1 ? {...content, text: action.payload}
: content
)
}
Put /opt/python2.7/bin
in your PATH
environment variable in front of /usr/bin
...or just get used to typing python2.7
.
pip install opencv-python
or
pip install opencv-python3
will definately works fine
VB sample:
@Html.ActionLink("Home", "Index", Nothing, New With {.style = "font-weight:bold;", .class = "someClass"})
Sample Css:
.someClass
{
color: Green !important;
}
In my case, I found that I need the !important attribute to over ride the site.css a:link css class
I simply use this jQuery trick:
$("a:focus").attr('data-id');
It gets the focused a
element and gets the data-id
attribute from it.
For hash references. You should use curly braces like the following:
$hash_ref1 = {%$hash_ref1, %$hash_ref2};
and not the suggested answer above using parenthesis:
$hash_ref1 = ($hash_ref1, $hash_ref2);
With C99 the %j
length modifier can also be used with the printf family of functions to print values of type int64_t
and uint64_t
:
#include <stdio.h>
#include <stdint.h>
int main(int argc, char *argv[])
{
int64_t a = 1LL << 63;
uint64_t b = 1ULL << 63;
printf("a=%jd (0x%jx)\n", a, a);
printf("b=%ju (0x%jx)\n", b, b);
return 0;
}
Compiling this code with gcc -Wall -pedantic -std=c99
produces no warnings, and the program prints the expected output:
a=-9223372036854775808 (0x8000000000000000)
b=9223372036854775808 (0x8000000000000000)
This is according to printf(3)
on my Linux system (the man page specifically says that j
is used to indicate a conversion to an intmax_t
or uintmax_t
; in my stdint.h, both int64_t
and intmax_t
are typedef'd in exactly the same way, and similarly for uint64_t
). I'm not sure if this is perfectly portable to other systems.
Following rajibchowdhury's answer (upvoted), use git rm
command which is advised is for removing the special entry in the index indicating a submodule (a 'folder' with a special mode 160000
).
If that special entry path isn't referenced in the .gitmodule
(like 'Classes/Support/Three20
' in the original question), then you need to remove it, in order to avoid the "No submodule mapping found in .gitmodules
for path" error message.
You can check all the entries in the index which are referencing submodules:
git ls-files --stage | grep 160000
Previous answer (November 2010)
It is possible that you haven't declared your initial submodule correctly (i.e. without any tail '/' at the end, as described in my old answer, even though your .gitmodule
has paths which looks ok in it).
This thread mentions:
do you get the same error when running 'git submodule init' from a fresh clone?
If so, you have something wrong.If you have no submodules, delete
.gitmodules
, and any references to submodules in .git/config, and ensure the Pikimal dir does not have a.git
dir in it.
If that fixes the problem, check in and do the same on your cruise working copy.
Obviously, don't delete your main .gitmodules
file, but look after other extra .gitmodules
files in your working tree.
Still in the topic of "incorrect submodule initialization", Jefromi mentions submodules which actually are gitlinks.
See How to track untracked content? in order to convert such a directory to a real submodule.
I only use MicrosoftAdvertising.Mobile and Microsoft.Advertising.Mobile.UI and I am served ads. The SDK should only add the DLLs not reference itself.
Note: You need to explicitly set width and height Make sure the phone dialer, and web browser capabilities are enabled
Followup note: Make sure that after you've removed the SDK DLL, that the xmlns references are not still pointing to it. The best route to take here is
Here is the xmlns reference:
xmlns:AdNamepace="clr-namespace:Microsoft.Advertising.Mobile.UI;assembly=Microsoft.Advertising.Mobile.UI"
Then the ad itself:
<AdNamespace:AdControl x:Name="myAd" Height="80" Width="480" AdUnitId="yourAdUnitIdHere" ApplicationId="yourIdHere"/>
It is already a list
type(my_set)
>>> <type 'list'>
Do you want something like
my_set = set([1,2,3,4])
my_list = list(my_set)
print my_list
>> [1, 2, 3, 4]
EDIT : Output of your last comment
>>> my_list = [1,2,3,4]
>>> my_set = set(my_list)
>>> my_new_list = list(my_set)
>>> print my_new_list
[1, 2, 3, 4]
I'm wondering if you did something like this :
>>> set=set()
>>> set([1,2])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'set' object is not callable
I think the best option is to implement like this:
public static int IndexOf<T>(this IEnumerable<T> enumerable, T element, IEqualityComparer<T> comparer = null)
{
int i = 0;
comparer = comparer ?? EqualityComparer<T>.Default;
foreach (var currentElement in enumerable)
{
if (comparer.Equals(currentElement, element))
{
return i;
}
i++;
}
return -1;
}
It will also not create the anonymous object
If your table is "independent" from others (I mean, it will not trigger a cascade delete or will not set any foreign keys relations to null), a nice trick could be to first DELETE the row and then INSERT it again. It could go like this:
DELETE FROM MyTable WHERE prop1 = 'aaa'; //assuming it will select at most one row!
INSERT INTO MyTable (prop1, ...) VALUES ('aaa', ...);
If your are deleting something which does not exist, nothing will happen.
I got the same error and found the cause to be a wrong or missing foreign key. (Using JDBC)
This is useful in contexts where the encoding is not told per HTTP header or other meta data, e.g. the local file system.
Imagine the following stylesheet:
[rel="external"]::after
{
content: ' ?';
}
If a reader saves the file to a hard drive and you omit the @charset
rule, most browsers will read it in the OS’ locale encoding, e.g. Windows-1252, and insert ↗ instead of an arrow.
Unfortunately, you cannot rely on this mechanism as the support is rather … rare.
And remember that on the net an HTTP header will always override the @charset
rule.
The correct rules to determine the character set of a stylesheet are in order of priority:
@charset
rule.The last rule is the weakest, it will fail in some browsers.
The charset
attribute in <link rel='stylesheet' charset='utf-8'>
is obsolete in HTML 5.
Watch out for conflict between the different declarations. They are not easy to debug.
@charset
if more than one name is registered for the same encoding.@charset
. There is a support table. I do not trust this. :)Python 2.x: docs.python.org/2/library/httplib.html:
Note: HTTPS support is only available if the socket module was compiled with SSL support.
Python 3.x: docs.python.org/3/library/http.client.html:
Note HTTPS support is only available if Python was compiled with SSL support (through the ssl module).
#!/usr/bin/env python
import httplib
c = httplib.HTTPSConnection("ccc.de")
c.request("GET", "/")
response = c.getresponse()
print response.status, response.reason
data = response.read()
print data
# =>
# 200 OK
# <!DOCTYPE html ....
To verify if SSL is enabled, try:
>>> import socket
>>> socket.ssl
<function ssl at 0x4038b0>
As you noted yourself, fmin
and fmax
were introduced in C99. Standard C++ library doesn't have fmin
and fmax
functions. Until C99 standard library gets incorporated into C++ (if ever), the application areas of these functions are cleanly separated. There's no situation where you might have to "prefer" one over the other.
You just use templated std::min
/std::max
in C++, and use whatever is available in C.
You can't. CSS is a presentation language. It isn't designed to add content (except for the very trivial with :before
and :after
).
You can use DataFrame.values
to get an numpy array of the data and then use NumPy functions such as argsort()
to get the most correlated pairs.
But if you want to do this in pandas, you can unstack
and sort the DataFrame:
import pandas as pd
import numpy as np
shape = (50, 4460)
data = np.random.normal(size=shape)
data[:, 1000] += data[:, 2000]
df = pd.DataFrame(data)
c = df.corr().abs()
s = c.unstack()
so = s.sort_values(kind="quicksort")
print so[-4470:-4460]
Here is the output:
2192 1522 0.636198
1522 2192 0.636198
3677 2027 0.641817
2027 3677 0.641817
242 130 0.646760
130 242 0.646760
1171 2733 0.670048
2733 1171 0.670048
1000 2000 0.742340
2000 1000 0.742340
dtype: float64
I would suggest to use a variable instead of a public field:
public class Variables
{
private static string name = "";
public static string Name
{
get { return name; }
set { name = value; }
}
}
From another class, you call your variable like this:
public class Main
{
public void DoSomething()
{
string var = Variables.Name;
}
}
Komodo is wonderful, and it runs on OS X; they have a free version, Komodo Edit.
UPDATE from 2015: I've switched to PHPStorm from Jetbrains, the same folks that built IntelliJ IDEA and Resharper. It's better. Not just better. It's well worth the money.
You can also write for passing multiple data from your controller to a view
return \View::make('myHome')
->with(compact('project'))
->with(['hello'=>$hello])
->with(['hello2'=>$hello2])
->with(['hello3'=>$hello3]);
because when the constructor is called, the bean is not yet initialized - i.e. no dependencies are injected. In the @PostConstruct
method the bean is fully initialized and you can use the dependencies.
because this is the contract that guarantees that this method will be invoked only once in the bean lifecycle. It may happen (though unlikely) that a bean is instantiated multiple times by the container in its internal working, but it guarantees that @PostConstruct
will be invoked only once.
Try this code for to trim
a String
Public Function AllTrim(ByVal GeVar As String) As String
Dim i As Integer
Dim e As Integer
Dim NewStr As String = ""
e = Len(GeVar)
For i = 1 To e
If Mid(GeVar, i, 1) <> " " Then
NewStr = NewStr + Mid(GeVar, i, 1)
End If
Next i
AllTrim = NewStr
' MsgBox("alltrim = " & NewStr)
End Function
A bit more along the same lines
attrs <- {}
attrs.a <- 1
f <- function(d) {
attrs.a <- d
}
f(20)
print(attrs.a)
will print "1"
attrs <- {}
attrs.a <- 1
f <- function(d) {
attrs.a <<- d
}
f(20)
print(attrs.a)
Will print "20"
I had the same problem, then I did this two steps:
There you have it, null-safe invocation in Java 8:
public void someMethod() {
String userName = nullIfAbsent(new Order(), t -> t.getAccount().getUser()
.getName());
}
static <T, R> R nullIfAbsent(T t, Function<T, R> funct) {
try {
return funct.apply(t);
} catch (NullPointerException e) {
return null;
}
}
The following code stops the execution right after an exception is thrown. You need to set a windows_exception_handler along with a termination handler. I tested this in MinGW 32bits.
void beforeCrash(void);
static const bool SET_TERMINATE = std::set_terminate(beforeCrash);
void beforeCrash() {
__asm("int3");
}
int main(int argc, char *argv[])
{
SetUnhandledExceptionFilter(windows_exception_handler);
...
}
Check the following code for the windows_exception_handler function: http://www.codedisqus.com/0ziVPgVPUk/exception-handling-and-stacktrace-under-windows-mingwgcc.html
Zach is correct about the direct answer to the question.
An interesting side note is that the following two loops do not execute the same:
for i=1:10000
% do something
end
for i=[1:10000]
% do something
end
The first loop creates a variable i
that is a scalar and it iterates it like a C for loop. Note that if you modify i
in the loop body, the modified value will be ignored, as Zach says. In the second case, Matlab creates a 10k-element array, then it walks all elements of the array.
What this means is that
for i=1:inf
% do something
end
works, but
for i=[1:inf]
% do something
end
does not (because this one would require allocating infinite memory). See Loren's blog for details.
Also note that you can iterate over cell arrays.
Normally it's done with a named Mutex (use new Mutex( "your app name", true ) and check the return value), but there's also some support classes in Microsoft.VisualBasic.dll that can do it for you.
As other answers describe this pattern is acceptable in python:
def dostuff(self):
from foo import bar
...
Which will avoid the execution of the import statement when the file is imported by other modules. Only if there is a logical circular dependency, this will fail.
Most Circular Imports are not actually logical circular imports but rather raise ImportError
errors, because of the way import()
evaluates top level statements of the entire file when called.
These ImportErrors
can almost always be avoided if you positively want your imports on top:
Consider this circular import:
# profiles/serializers.py
from images.serializers import SimplifiedImageSerializer
class SimplifiedProfileSerializer(serializers.Serializer):
name = serializers.CharField()
class ProfileSerializer(SimplifiedProfileSerializer):
recent_images = SimplifiedImageSerializer(many=True)
# images/serializers.py
from profiles.serializers import SimplifiedProfileSerializer
class SimplifiedImageSerializer(serializers.Serializer):
title = serializers.CharField()
class ImageSerializer(SimplifiedImageSerializer):
profile = SimplifiedProfileSerializer()
From David Beazleys excellent talk Modules and Packages: Live and Let Die! - PyCon 2015, 1:54:00
, here is a way to deal with circular imports in python:
try:
from images.serializers import SimplifiedImageSerializer
except ImportError:
import sys
SimplifiedImageSerializer = sys.modules[__package__ + '.SimplifiedImageSerializer']
This tries to import SimplifiedImageSerializer
and if ImportError
is raised, because it already is imported, it will pull it from the importcache.
PS: You have to read this entire post in David Beazley's voice.
Try handling the change event of the select
and using this.value
to determine whether it's 'Yes' or not.
JS
document.getElementById('test').addEventListener('change', function () {
var style = this.value == 1 ? 'block' : 'none';
document.getElementById('hidden_div').style.display = style;
});
HTML
<select id="test" name="form_select">
<option value="0">No</option>
<option value ="1">Yes</option>
</select>
<div id="hidden_div" style="display: none;">Hello hidden content</div>
Given this binary tree:
Breadth First Traversal:
Traverse across each level from left to right.
"I'm G, my kids are D and I, my grandkids are B, E, H and K, their grandkids are A, C, F"
- Level 1: G
- Level 2: D, I
- Level 3: B, E, H, K
- Level 4: A, C, F
Order Searched: G, D, I, B, E, H, K, A, C, F
Depth First Traversal:
Traversal is not done ACROSS entire levels at a time. Instead, traversal dives into the DEPTH (from root to leaf) of the tree first. However, it's a bit more complex than simply up and down.
There are three methods:
1) PREORDER: ROOT, LEFT, RIGHT.
You need to think of this as a recursive process:
Grab the Root. (G)
Then Check the Left. (It's a tree)
Grab the Root of the Left. (D)
Then Check the Left of D. (It's a tree)
Grab the Root of the Left (B)
Then Check the Left of B. (A)
Check the Right of B. (C, and it's a leaf node. Finish B tree. Continue D tree)
Check the Right of D. (It's a tree)
Grab the Root. (E)
Check the Left of E. (Nothing)
Check the Right of E. (F, Finish D Tree. Move back to G Tree)
Check the Right of G. (It's a tree)
Grab the Root of I Tree. (I)
Check the Left. (H, it's a leaf.)
Check the Right. (K, it's a leaf. Finish G tree)
DONE: G, D, B, A, C, E, F, I, H, K
2) INORDER: LEFT, ROOT, RIGHT
Where the root is "in" or between the left and right child node.
Check the Left of the G Tree. (It's a D Tree)
Check the Left of the D Tree. (It's a B Tree)
Check the Left of the B Tree. (A)
Check the Root of the B Tree (B)
Check the Right of the B Tree (C, finished B Tree!)
Check the Right of the D Tree (It's a E Tree)
Check the Left of the E Tree. (Nothing)
Check the Right of the E Tree. (F, it's a leaf. Finish E Tree. Finish D Tree)...
Onwards until...
DONE: A, B, C, D, E, F, G, H, I, K
3) POSTORDER:
LEFT, RIGHT, ROOT
DONE: A, C, B, F, E, D, H, K, I, G
Usage (aka, why do we care):
I really enjoyed this simple Quora explanation of the Depth First Traversal methods and how they are commonly used:
"In-Order Traversal will print values [in order for the BST (binary search tree)]"
"Pre-order traversal is used to create a copy of the [binary search tree]."
"Postorder traversal is used to delete the [binary search tree]."
https://www.quora.com/What-is-the-use-of-pre-order-and-post-order-traversal-of-binary-trees-in-computing
In Typescript use the For Each like below.
selectChildren(data, $event) {
let parentChecked = data.checked;
for(var obj in this.hierarchicalData)
{
for (var childObj in obj )
{
value.checked = parentChecked;
}
}
}
On a default instance, SQL Server listens on TCP/1433 by default. This can be changed. On a named instance, unless configured differently, SQL Server listens on a dynamic TCP port. What that means is should SQL Server discover that the port is in use, it will pick another TCP port. How clients usually find the right port in the case of a named instance is by talking to the SQL Server Listener Service/SQL Browser. That listens on UDP/1434 and cannot be changed. If you have a named instance, you can configure a static port and if you have a need to use Kerberos authentication/delegation, you should.
What you'll need to determine is what port your SQL Server is listening on. Then you'll need to get with your networking/security folks to determine if they allow communication to that port via VPN. If they are, as indicated, check your firewall settings. Some systems have multiple firewalls (my laptop is an example). If so, you'll need to check all the firewalls on your system.
If all of those are correct, verify the server doesn't have an IPSEC policy that restricts access to the SQL Server port via IP address. That also could result in you being blocked.
if you use this
public int countLines(String filename) throws IOException {
LineNumberReader reader = new LineNumberReader(new FileReader(filename));
int cnt = 0;
String lineRead = "";
while ((lineRead = reader.readLine()) != null) {}
cnt = reader.getLineNumber();
reader.close();
return cnt;
}
you cant run to big num rows, likes 100K rows, because return from reader.getLineNumber is int. you need long type of data to process maximum rows..
You can make bar a function making it a method.
Foo.bar = function(passvariable){ };
As a property it would just be assigned a string, data type or boolean
Foo.bar = "a place";
1. Choose project, right click, in context menu, choose Show in Explorer
(on Mac, select Reveal in Finder
).
2. Choose menu File \ Close Project
3. In Windows Explorer, press Del or Shift+Del for permanent delete.
4. At IntelliJ IDEA startup windows, hover cursor on old project name (what has been deleted) press Del for delelte.
I was facing the same issue in which I need to align selected placeholder value to the right of the select box & also need to align options to right but when I have used direction: rtl; to select & applied some right padding to select then all options also getting shift to the right by padding as I only want to apply padding to selected placeholder.
I have fixed the issue by the following the style:
select:first-child{
text-indent: 24%;
direction: rtl;
padding-right: 7px;
}
select option{
direction: rtl;
}
You can change text-indent as per your requirement. Hope it will help you.
I modified the above function to account for carriage returns in IE. It's untested but I did something similar with it in my code so it should be workable.
function getCaret(el) {
if (el.selectionStart) {
return el.selectionStart;
} else if (document.selection) {
el.focus();
var r = document.selection.createRange();
if (r == null) {
return 0;
}
var re = el.createTextRange(),
rc = re.duplicate();
re.moveToBookmark(r.getBookmark());
rc.setEndPoint('EndToStart', re);
var add_newlines = 0;
for (var i=0; i<rc.text.length; i++) {
if (rc.text.substr(i, 2) == '\r\n') {
add_newlines += 2;
i++;
}
}
//return rc.text.length + add_newlines;
//We need to substract the no. of lines
return rc.text.length - add_newlines;
}
return 0;
}
<?php
if (!isset($_GET) || empty($_GET))
{
// do stuff here
}
you should use
getActivity.getSupportFragmentManager() like
//in my fragment
SupportMapFragment fm = (SupportMapFragment)
getActivity().getSupportFragmentManager().findFragmentById(R.id.map);
I have also this issues but resolved after adding getActivity()
before getSupportFragmentManager
.
This isn't straightforward, but
SELECT CHAR(CURRENT DATE, ISO) FROM SYSIBM.SYSDUMMY1
returns the current date in yyyy-mm-dd format. You would have to substring and concatenate the result to get yyyymmdd.
SELECT SUBSTR(CHAR(CURRENT DATE, ISO), 1, 4) ||
SUBSTR(CHAR(CURRENT DATE, ISO), 6, 2) ||
SUBSTR(CHAR(CURRENT DATE, ISO), 9, 2)
FROM SYSIBM.SYSDUMMY1
It does not sound like you imported the library right especially when you say at the point Add the library to your application project: I felt lost .. basically because I don't have the "add" option by itself .. however I clicked on "add library" and moved on ..
in eclipse you need to right click on the project, go to Properties, select Android in the list then Add to add the library
follow this tutorial in the docs
http://developer.android.com/tools/support-library/setup.html
Not tested, but the closer you can get seems to be is with AutoCompleteTextView. You can write an adapter wich ignores the filter functions. Something like:
class UnconditionalArrayAdapter<T> extends ArrayAdapter<T> {
final List<T> items;
public UnconditionalArrayAdapter(Context context, int textViewResourceId, List<T> items) {
super(context, textViewResourceId, items);
this.items = items;
}
public Filter getFilter() {
return new NullFilter();
}
class NullFilter extends Filter {
protected Filter.FilterResults performFiltering(CharSequence constraint) {
final FilterResults results = new FilterResults();
results.values = items;
return results;
}
protected void publishResults(CharSequence constraint, Filter.FilterResults results) {
items.clear(); // `items` must be final, thus we need to copy the elements by hand.
for (Object item : (List) results.values) {
items.add((String) item);
}
if (results.count > 0) {
notifyDataSetChanged();
} else {
notifyDataSetInvalidated();
}
}
}
}
... then in your onCreate:
String[] COUNTRIES = new String[] {"Belgium", "France", "Italy", "Germany"};
List<String> contriesList = Arrays.asList(COUNTRIES());
ArrayAdapter<String> adapter = new UnconditionalArrayAdapter<String>(this,
android.R.layout.simple_dropdown_item_1line, contriesList);
AutoCompleteTextView textView = (AutoCompleteTextView)
findViewById(R.id.countries_list);
textView.setAdapter(adapter);
The code is not tested, there can be some features with the filtering method I did not consider, but there you have it, the basic principles to emulate a ComboBox with an AutoCompleteTextView.
Edit
Fixed NullFilter implementation.
We need access on the items, thus the constructor of the UnconditionalArrayAdapter
needs to take a reference to a List (kind of a buffer).
You can also use e.g. adapter = new UnconditionalArrayAdapter<String>(..., new ArrayList<String>);
and then use adapter.add("Luxemburg")
, so you don't need to manage the buffer list.
If what you want is a fixed size array, and initialize it with nil
values, you can use an UnsafeMutableBufferPointer
, allocate memory for 64 nodes with it, and then read/write from/to the memory by subscripting the pointer type instance. This also has the benefit of avoiding checking if the memory must be reallocated, which Array
does. I would however be surprised if the compiler doesn't optimize that away for arrays that don't have any more calls to methods that may require resizing, other than at the creation site.
let count = 64
let sprites = UnsafeMutableBufferPointer<SKSpriteNode>.allocate(capacity: count)
for i in 0..<count {
sprites[i] = ...
}
for sprite in sprites {
print(sprite!)
}
sprites.deallocate()
This is however not very user friendly. So, let's make a wrapper!
class ConstantSizeArray<T>: ExpressibleByArrayLiteral {
typealias ArrayLiteralElement = T
private let memory: UnsafeMutableBufferPointer<T>
public var count: Int {
get {
return memory.count
}
}
private init(_ count: Int) {
memory = UnsafeMutableBufferPointer.allocate(capacity: count)
}
public convenience init(count: Int, repeating value: T) {
self.init(count)
memory.initialize(repeating: value)
}
public required convenience init(arrayLiteral: ArrayLiteralElement...) {
self.init(arrayLiteral.count)
memory.initialize(from: arrayLiteral)
}
deinit {
memory.deallocate()
}
public subscript(index: Int) -> T {
set(value) {
precondition((0...endIndex).contains(index))
memory[index] = value;
}
get {
precondition((0...endIndex).contains(index))
return memory[index]
}
}
}
extension ConstantSizeArray: MutableCollection {
public var startIndex: Int {
return 0
}
public var endIndex: Int {
return count - 1
}
func index(after i: Int) -> Int {
return i + 1;
}
}
Now, this is a class, and not a structure, so there's some reference counting overhead incurred here. You can change it to a struct
instead, but because Swift doesn't provide you with an ability to use copy initializers and deinit
on structures, you'll need a deallocation method (func release() { memory.deallocate() }
), and all copied instances of the structure will reference the same memory.
Now, this class may just be good enough. Its use is simple:
let sprites = ConstantSizeArray<SKSpriteNode?>(count: 64, repeating: nil)
for i in 0..<sprites.count {
sprite[i] = ...
}
for sprite in sprites {
print(sprite!)
}
For more protocols to implement conformance to, see the Array documentation (scroll to Relationships).
CN refers to class name, so put in your LDAP query CN=Users. Should work.
input width is 10 + 2 times 1 px for border
In your build.gradle
file simply use the following snippet
bootRun {
args = ["--spring.profiles.active=${project.properties['profile'] ?: 'prod'}"]
}
And then run following command to use dev
profile:
./gradlew bootRun -Pprofile=dev
It's more complicated than the language you used to write your project. Getting it configured right is harder than actual programming.
With Spring Boot JPA, use the below code in your application.properties file and obviously you can modify timezone to your choice
spring.jpa.properties.hibernate.jdbc.time_zone = UTC
Then in your Entity class file,
@Column
private LocalDateTime created;
In order to run the bootstrap date time picker you need to include Moment.js as well. Here is the working code sample in your case.
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
<head>_x000D_
<meta charset="utf-8">_x000D_
<meta name="viewport" content="width=device-width, initial-scale=1">_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
_x000D_
_x000D_
<!-- <link rel="stylesheet" type="text/css" href="css/bootstrap-datetimepicker.css"> -->_x000D_
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.15.1/moment.min.js"></script>_x000D_
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.43/css/bootstrap-datetimepicker.min.css"> _x000D_
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.43/css/bootstrap-datetimepicker-standalone.css"> _x000D_
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.43/js/bootstrap-datetimepicker.min.js"></script>_x000D_
_x000D_
</head>_x000D_
_x000D_
_x000D_
<body>_x000D_
_x000D_
<div class="container">_x000D_
<div class="row">_x000D_
<div class='col-sm-6'>_x000D_
<div class="form-group">_x000D_
<div class='input-group date' id='datetimepicker1'>_x000D_
<input type='text' class="form-control" />_x000D_
<span class="input-group-addon">_x000D_
<span class="glyphicon glyphicon-calendar"></span>_x000D_
</span>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
<script type="text/javascript">_x000D_
$(function () {_x000D_
$('#datetimepicker1').datetimepicker();_x000D_
});_x000D_
</script>_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
It should be like this.
In your Component
computed: {
...mapGetters({
nameFromStore: 'name'
}),
name: {
get(){
return this.nameFromStore
},
set(newName){
return newName
}
}
}
In your store
export const store = new Vuex.Store({
state:{
name : "Stackoverflow"
},
getters: {
name: (state) => {
return state.name;
}
}
}
Go to installed mysql path and find bin folder,open my.ini and search 3306 after that change 3306 to 3360
In May 2017 Google launched the official Google Maps URLs documentation. The Google Maps URLs introduces universal cross-platform syntax that you can use in your applications.
Have a look at the following document:
https://developers.google.com/maps/documentation/urls/guide
You can use URLs in search, directions, map and street view modes.
For example, to show the marker at specified position you can use the following URL:
https://www.google.com/maps/search/?api=1&query=36.26577,-92.54324
For further details please read aforementioned documentation.
You can also file feature requests for this API in Google issue tracker.
Hope this helps!
Use JSON.
In the following example $php_variable
can be any PHP variable.
<script type="text/javascript">
var obj = <?php echo json_encode($php_variable); ?>;
</script>
In your code, you could use like the following:
drawChart(600/50, <?php echo json_encode($day); ?>, ...)
In cases where you need to parse out an object from JSON-string (like in an AJAX request), the safe way is to use JSON.parse(..)
like the below:
var s = "<JSON-String>";
var obj = JSON.parse(s);
In your function definition you're constraining sets a and b to the same type. You can also write
public <X,Y> void myFunction(Set<X> s1, Set<Y> s2){...}
If you mean you want to delete a drop from a table if it exists, you can use the DELETE
command, for example:
DELETE FROM users WHERE user_login = 'foobar'
If no rows match, it's not an error.
Yes you are right. You have placed WHERE
clause wrong. You can only use one WHERE
clause in single query so try AND
for multiple conditions like this:
SELECT table1.f_id FROM table1
INNER JOIN table2
ON table2.f_id = table1.f_id
WHERE table2.f_type = 'InProcess'
AND f_com_id = '430'
AND f_status = 'Submitted'
You could implement a custom IEqualityComparer<Employee>
:
public class Employee
{
public string empName { get; set; }
public string empID { get; set; }
public string empLoc { get; set; }
public string empPL { get; set; }
public string empShift { get; set; }
public class Comparer : IEqualityComparer<Employee>
{
public bool Equals(Employee x, Employee y)
{
return x.empLoc == y.empLoc
&& x.empPL == y.empPL
&& x.empShift == y.empShift;
}
public int GetHashCode(Employee obj)
{
unchecked // overflow is fine
{
int hash = 17;
hash = hash * 23 + (obj.empLoc ?? "").GetHashCode();
hash = hash * 23 + (obj.empPL ?? "").GetHashCode();
hash = hash * 23 + (obj.empShift ?? "").GetHashCode();
return hash;
}
}
}
}
Now you can use this overload of Enumerable.Distinct
:
var distinct = employees.Distinct(new Employee.Comparer());
The less reusable, robust and efficient approach, using an anonymous type:
var distinctKeys = employees.Select(e => new { e.empLoc, e.empPL, e.empShift })
.Distinct();
var joined = from e in employees
join d in distinctKeys
on new { e.empLoc, e.empPL, e.empShift } equals d
select e;
// if you want to replace the original collection
employees = joined.ToList();
Official document of Crypto++ AES is a good start. And from my archive, a basic implementation of AES is as follows:
Please refer here with more explanation, I recommend you first understand the algorithm and then try to understand each line step by step.
#include <iostream>
#include <iomanip>
#include "modes.h"
#include "aes.h"
#include "filters.h"
int main(int argc, char* argv[]) {
//Key and IV setup
//AES encryption uses a secret key of a variable length (128-bit, 196-bit or 256-
//bit). This key is secretly exchanged between two parties before communication
//begins. DEFAULT_KEYLENGTH= 16 bytes
CryptoPP::byte key[ CryptoPP::AES::DEFAULT_KEYLENGTH ], iv[ CryptoPP::AES::BLOCKSIZE ];
memset( key, 0x00, CryptoPP::AES::DEFAULT_KEYLENGTH );
memset( iv, 0x00, CryptoPP::AES::BLOCKSIZE );
//
// String and Sink setup
//
std::string plaintext = "Now is the time for all good men to come to the aide...";
std::string ciphertext;
std::string decryptedtext;
//
// Dump Plain Text
//
std::cout << "Plain Text (" << plaintext.size() << " bytes)" << std::endl;
std::cout << plaintext;
std::cout << std::endl << std::endl;
//
// Create Cipher Text
//
CryptoPP::AES::Encryption aesEncryption(key, CryptoPP::AES::DEFAULT_KEYLENGTH);
CryptoPP::CBC_Mode_ExternalCipher::Encryption cbcEncryption( aesEncryption, iv );
CryptoPP::StreamTransformationFilter stfEncryptor(cbcEncryption, new CryptoPP::StringSink( ciphertext ) );
stfEncryptor.Put( reinterpret_cast<const unsigned char*>( plaintext.c_str() ), plaintext.length() );
stfEncryptor.MessageEnd();
//
// Dump Cipher Text
//
std::cout << "Cipher Text (" << ciphertext.size() << " bytes)" << std::endl;
for( int i = 0; i < ciphertext.size(); i++ ) {
std::cout << "0x" << std::hex << (0xFF & static_cast<CryptoPP::byte>(ciphertext[i])) << " ";
}
std::cout << std::endl << std::endl;
//
// Decrypt
//
CryptoPP::AES::Decryption aesDecryption(key, CryptoPP::AES::DEFAULT_KEYLENGTH);
CryptoPP::CBC_Mode_ExternalCipher::Decryption cbcDecryption( aesDecryption, iv );
CryptoPP::StreamTransformationFilter stfDecryptor(cbcDecryption, new CryptoPP::StringSink( decryptedtext ) );
stfDecryptor.Put( reinterpret_cast<const unsigned char*>( ciphertext.c_str() ), ciphertext.size() );
stfDecryptor.MessageEnd();
//
// Dump Decrypted Text
//
std::cout << "Decrypted Text: " << std::endl;
std::cout << decryptedtext;
std::cout << std::endl << std::endl;
return 0;
}
For installation details :
sudo apt-get install libcrypto++-dev libcrypto++-doc libcrypto++-utils
public static string ToSqlParamsString(this IDictionary<string, string> dict)
{
string result = string.Empty;
foreach (var kvp in dict)
{
result += $"@{kvp.Key}='{kvp.Value}',";
}
return result.Trim(',', ' ');
}
public static List<T> RunSproc<T>(string sprocName, IDictionary<string, string> parameters)
{
string command = $"exec {sprocName} {parameters.ToSqlParamsString()}";
return Context.Database.SqlQuery<T>(command).ToList();
}
You can use the display property of style. Intialy set the result section style as
style = "display:none"
Then the div will not be visible and there won't be any white space.
Once the search results are being populated change the display property using the java script like
document.getElementById("someObj").style.display = "block"
Using java script you can make the div invisible
document.getElementById("someObj").style.display = "none"
As long as they are of the same type, it's very simple with AddRange:
list2.AddRange(list1);
I too had this problem, its easy to solve:
Go to Control panel - System and maintenance - System - Advanced system settings - Environment variables - System variables - path - click edit - add
"c:\xampp\mysql\bin"
- it should look like this :
\Program Files (x86)\NVIDIA Corporation\PhysX\Common;C:\Program Files (x86)\Intel\iCLS Client\;C:\Program Files\Intel\iCLS Client\;%SystemRoot%\system32;%SystemRoot%;%SystemRoot%\System32\Wbem;%SYSTEMROOT%\System32\WindowsPowerShell\v1.0\;C:\Program Files\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files (x86)\Intel\OpenCL SDK\2.0\bin\x86;C:\Program Files (x86)\Intel\OpenCL SDK\2.0\bin\x64;C:\Program Files (x86)\Windows Live\Shared;C:\Program Files (x86)\QuickTime Alternative\QTSystem;c:\xampp\mysql\bin
And don't forget to start MySQL from control panel of Xampp.
Personally, I think the concatenation is the better solution. The generic implementation would be
entity shifter is
generic (
REGSIZE : integer := 8);
port(
clk : in str_logic;
Data_in : in std_logic;
Data_out : out std_logic(REGSIZE-1 downto 0);
end shifter ;
architecture bhv of shifter is
signal shift_reg : std_logic_vector(REGSIZE-1 downto 0) := (others<='0');
begin
process (clk) begin
if rising_edge(clk) then
shift_reg <= shift_reg(REGSIZE-2 downto 0) & Data_in;
end if;
end process;
end bhv;
Data_out <= shift_reg;
Both will implement as shift registers. If you find yourself in need of more shift registers than you are willing to spend resources on (EG dividing 1000 numbers by 4) you might consider using a BRAM to store the values and a single shift register to contain "indices" that result in the correct shift of all the numbers.
Found a library that does just that: https://github.com/recruit-lifestyle/FloatingView
There's a sample project in the root folder. I ran it and it works as required. The background is clickable - even if it's another app.
May be sometimes upgrading to a superuser might not be a good option. So apart from super user there are lot of other options which you can use. Open your terminal and type the following:
$ sudo su - postgres
[sudo] password for user: (type your password here)
$ psql
postgres@user:~$ psql
psql (10.5 (Ubuntu 10.5-1.pgdg18.04+1))
Type "help" for help.
postgres=# ALTER USER my_user WITH option
Also listing the list of options
SUPERUSER | NOSUPERUSER | CREATEDB | NOCREATEDB | CREATEROLE | NOCREATEROLE |
CREATEUSER | NOCREATEUSER | INHERIT | NOINHERIT | LOGIN | NOLOGIN | REPLICATION|
NOREPLICATION | BYPASSRLS | NOBYPASSRLS | CONNECTION LIMIT connlimit |
[ ENCRYPTED | UNENCRYPTED ] PASSWORD 'password' | VALID UNTIL 'timestamp'
So in command line it will look like
postgres=# ALTER USER my_user WITH LOGIN
OR use an encrypted password.
postgres=# ALTER USER my_user WITH ENCRYPTED PASSWORD '5d41402abc4b2a76b9719d911017c592';
OR revoke permissions after a specific time.
postgres=# ALTER USER my_user WITH VALID UNTIL '2019-12-29 19:09:00';
I was facing the same issue as below.
npm ERR! errno -4058 npm ERR! syscall open npm ERR! enoent ENOENT: no such file or directory, open 'D:\SVenu\FullStackDevelopment\Angular\Angular2_Splitter_CodeSkeleton\CodeSke leton\run\package.json' npm ERR! enoent This is related to npm not being able to find a file. npm ERR! enoent
The problem I made was, I was running the command npm build run
instead of running npm run build
.
Just sharing to help someone who does small mistakes like me.
Probably a duplicate of this post: A customized input text box in html/html5
input {_x000D_
border: 0;_x000D_
outline: 0;_x000D_
background: transparent;_x000D_
border-bottom: 1px solid black;_x000D_
}
_x000D_
<input></input>
_x000D_
There's probably a more direct way using regular expressions. With luck, somebody else will provide it. But here's what I'd do without needing to go to the manuals.
Create a PLSQL function to receive your input string and return a varchar2.
In the PLSQL function, do an asciistr() of your input. The PLSQL is because that may return a string longer than 4000 and you have 32K available for varchar2 in PLSQL.
That function converts the non-ASCII characters to \xxxx notation. So you can use regular expressions to find and remove those. Then return the result.
after hardware check on the server and it was found out that memory had gone bad, replaced the memory and the server is now fully accessible.
One more procedural style example with mysqli_multi_query
, assumes $query
is filled with semicolon-separated statements.
mysqli_begin_transaction ($link);
for (mysqli_multi_query ($link, $query);
mysqli_more_results ($link);
mysqli_next_result ($link) );
! mysqli_errno ($link) ?
mysqli_commit ($link) : mysqli_rollback ($link);
what'd you say about Cross join solution?
SELECT t1.*, t2.*
FROM table1 t1
INNER JOIN table2 t2
ON 1=1;
Here is a javascript code I have tested successfully :
var txtFile = new XMLHttpRequest();
var allText = "file not found";
txtFile.onreadystatechange = function () {
if (txtFile.readyState === XMLHttpRequest.DONE && txtFile.status == 200) {
allText = txtFile.responseText;
allText = allText.split("\n").join("<br>");
}
document.getElementById('txt').innerHTML = allText;
}
txtFile.open("GET", '/result/client.txt', true);
txtFile.send(null);
All user installed apks are located in /data/app/, but you can only access this if you are rooted(afaik, you can try without root and if it doesn't work, rooting isn't hard. I suggest you search xda-developers for rooting instructions)
Use Root explorer or ES File Explorer to access /data/app/ (you have to keep going "up" until you reach the root directory /, kind of like C: in windows, before you can see the data directory(folder)). In ES file explorer you must also tick a checkbox in settings to allow going up to the root directory.
When you are in there you will see all your applications apks, though they might be named strangely. Just copy the wanted .apk and paste in the sd card, after that you can copy it to your computer and when you want to install it just open the .apk in a file manager (be sure to have install from unknown sources enabled in android settings). Even if you only want to send over bluetooth I would recommend copying it to the SD first.
PS Note that paid apps probably won't work being copied this way, since they usually check their licence online. PPS Installing an app this way may not link it with google play(you won't see it in my apps and it won't get updates).
Specify a height and a width:
.header-shadow{
background-image: url('../images/header-shade.jpg');
height: 10px;
width: 10px;
}
Yes, the biggest difference is that reject is a callback function that gets carried out after the promise is rejected, whereas throw cannot be used asynchronously. If you chose to use reject, your code will continue to run normally in asynchronous fashion whereas throw will prioritize completing the resolver function (this function will run immediately).
An example I've seen that helped clarify the issue for me was that you could set a Timeout function with reject, for example:
new Promise((resolve, reject) => {
setTimeout(()=>{reject('err msg');console.log('finished')}, 1000);
return resolve('ret val')
})
.then((o) => console.log("RESOLVED", o))
.catch((o) => console.log("REJECTED", o));
_x000D_
The above could would not be possible to write with throw.
try{
new Promise((resolve, reject) => {
setTimeout(()=>{throw new Error('err msg')}, 1000);
return resolve('ret val')
})
.then((o) => console.log("RESOLVED", o))
.catch((o) => console.log("REJECTED", o));
}catch(o){
console.log("IGNORED", o)
}
_x000D_
In the OP's small example the difference in indistinguishable but when dealing with more complicated asynchronous concept the difference between the two can be drastic.
Initially,module.exports=exports
, and the require
function returns the object module.exports
refers to.
if we add property to the object, say exports.a=1
, then module.exports and exports still refer to the same object. So if we call require and assign the module to a variable, then the variable has a property a and its value is 1;
But if we override one of them, for example, exports=function(){}
, then they are different now: exports refers to a new object and module.exports refer to the original object. And if we require the file, it will not return the new object, since module.exports is not refer to the new object.
For me, i will keep adding new property, or override both of them to a new object. Just override one is not right. And keep in mind that module.exports
is the real boss.
It's all down to how calls to objects are handled, and how much protection they need. COM objects can ask the runtime to protect them against being called by multiple threads at the same time; those that don't can potentially be called concurrently from different threads, so they have to protect their own data.
In addition, it's also necessary for the runtime to prevent a COM object call from blocking the user interface, if a call is made from a user interface thread.
An apartment is a place for objects to live, and they contain one or more threads. The apartment defines what happens when calls are made. Calls to objects in an apartment will be received and processed on any thread in that apartment, with the exception that a call by a thread already in the right apartment is processed by itself (i.e. a direct call to the object).
Threads can be either in a Single-Threaded Apartment (in which case they are the only thread in that apartment) or in a Multi-Threaded Apartment. They specify which when the thread initializes COM for that thread.
The STA is primarily for compatibility with the user interface, which is tied to a specific thread. An STA receives notifications of calls to process by receiving a window message to a hidden window; when it makes an outbound call, it starts a modal message loop to prevent other window messages being processed. You can specify a message filter to be called, so that your application can respond to other messages.
By contrast all MTA threads share a single MTA for the process. COM may start a new worker thread to handle an incoming call if no threads are available, up to a pool limit. Threads making outbound calls simply block.
For simplicity we'll consider only objects implemented in DLLs, which advertise in the registry what they support, by setting the ThreadingModel
value for their class's key. There are four options:
ThreadingModel
value not present). The object is created on the host's main UI thread, and all calls are marshalled to that thread. The class factory will only be called on that thread.Apartment
. This indicates that the class can run on any single-threaded-mode thread. If the thread that creates it is an STA thread, the object will run on that thread, otherwise it will be created in the main STA - if no main STA exists, an STA thread will be created for it. (This means MTA threads that create Apartment objects will be marshalling all calls to a different thread.) The class factory can be called concurrently by multiple STA threads so it must protect its internal data against this.Free
. This indicates a class designed to run in the MTA. It will always load in the MTA, even if created by an STA thread, which again means the STA thread's calls will be marshalled. This is because a Free
object is generally written with the expectation that it can block.Both
. These classes are flexible and load in whichever apartment they're created from. They must be written to fit both sets of requirements, however: they must protect their internal state against concurrent calls, in case they're loaded in the MTA, but must not block, in case they're loaded in an STA.From the .NET Framework, basically just use [STAThread]
on any thread that creates UI. Worker threads should use the MTA, unless they're going to use Apartment
-marked COM components, in which case use the STA to avoid marshalling overhead and scalability problems if the same component is called from multiple threads (as each thread will have to wait for the component in turn). It's much easier all around if you use a separate COM object per thread, whether the component is in the STA or MTA.
It's possible to find the element in Dictionary collection by using ContainsKey or TryGetValue as follows:
class Program
{
protected static Dictionary<string, string> _tags = new Dictionary<string,string>();
static void Main(string[] args)
{
string strValue;
_tags.Add("101", "C#");
_tags.Add("102", "ASP.NET");
if (_tags.ContainsKey("101"))
{
strValue = _tags["101"];
Console.WriteLine(strValue);
}
if (_tags.TryGetValue("101", out strValue))
{
Console.WriteLine(strValue);
}
}
}
try:
parts = ip.split('.')
return len(parts) == 4 and all(0 <= int(part) < 256 for part in parts)
except ValueError:
return False # one of the 'parts' not convertible to integer
except (AttributeError, TypeError):
return False # `ip` isn't even a string
Here's a solution using that ggplot
package (version 3.x) in addition to what you've gotten so far.
We use the position
argument of geom_bar
set to position = "fill"
. You may also use position = position_fill()
if you want to use the arguments of position_fill()
(vjust
and reverse
).
Note that your data is in a 'wide' format, whereas ggplot2
requires it to be in a 'long' format. Thus, we first need to gather
the data.
library(ggplot2)
library(dplyr)
library(tidyr)
dat <- read.table(text = " ONE TWO THREE
1 23 234 324
2 34 534 12
3 56 324 124
4 34 234 124
5 123 534 654",sep = "",header = TRUE)
# Add an id variable for the filled regions and reshape
datm <- dat %>%
mutate(ind = factor(row_number())) %>%
gather(variable, value, -ind)
ggplot(datm, aes(x = variable, y = value, fill = ind)) +
geom_bar(position = "fill",stat = "identity") +
# or:
# geom_bar(position = position_fill(), stat = "identity")
scale_y_continuous(labels = scales::percent_format())
You can do it by using attr, the mistake that you made is that you put the true inside quotes. instead of that try this:
$("input").attr("required", true);
I ended up using:
Function DirectoryExists(Directory As String) As Boolean
DirectoryExists = False
If Len(Dir(Directory, vbDirectory)) > 0 Then
If (GetAttr(Directory) And vbDirectory) = vbDirectory Then
DirectoryExists = True
End If
End If
End Function
which is a mix of @Brian and @ZygD answers. Where I think @Brian's answer is not enough and don't like the On Error Resume Next
used in @ZygD's answer
With the help of this post, I have made a script that will install via the app Installous for rapid deployment:
# compress application.
/bin/mkdir -p $CONFIGURATION_BUILD_DIR/Payload
/bin/cp -R $CONFIGURATION_BUILD_DIR/MyApp.app $CONFIGURATION_BUILD_DIR/Payload
/bin/cp iTunesCrap/logo_itunes.png $CONFIGURATION_BUILD_DIR/iTunesArtwork
/bin/cp iTunesCrap/iTunesMetadata.plist $CONFIGURATION_BUILD_DIR/iTunesMetadata.plist
cd $CONFIGURATION_BUILD_DIR
# zip up the HelloWorld directory
/usr/bin/zip -r MyApp.ipa Payload iTunesArtwork iTunesMetadata.plist
What Is missing in the post referenced above, is the iTunesMetadata. Without this, Installous will not install apps correctly. Here is an example of an iTunesMetadata:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>appleId</key>
<string></string>
<key>artistId</key>
<integer>0</integer>
<key>artistName</key>
<string>MYCOMPANY</string>
<key>buy-only</key>
<true/>
<key>buyParams</key>
<string></string>
<key>copyright</key>
<string></string>
<key>drmVersionNumber</key>
<integer>0</integer>
<key>fileExtension</key>
<string>.app</string>
<key>genre</key>
<string></string>
<key>genreId</key>
<integer>0</integer>
<key>itemId</key>
<integer>0</integer>
<key>itemName</key>
<string>MYAPP</string>
<key>kind</key>
<string>software</string>
<key>playlistArtistName</key>
<string>MYCOMPANY</string>
<key>playlistName</key>
<string>MYAPP</string>
<key>price</key>
<integer>0</integer>
<key>priceDisplay</key>
<string>nil</string>
<key>rating</key>
<dict>
<key>content</key>
<string></string>
<key>label</key>
<string>4+</string>
<key>rank</key>
<integer>100</integer>
<key>system</key>
<string>itunes-games</string>
</dict>
<key>releaseDate</key>
<string>Sunday, December 12, 2010</string>
<key>s</key>
<integer>143441</integer>
<key>softwareIcon57x57URL</key>
<string></string>
<key>softwareIconNeedsShine</key>
<false/>
<key>softwareSupportedDeviceIds</key>
<array>
<integer>1</integer>
</array>
<key>softwareVersionBundleId</key>
<string>com.mycompany.myapp</string>
<key>softwareVersionExternalIdentifier</key>
<integer>0</integer>
<key>softwareVersionExternalIdentifiers</key>
<array>
<integer>1466803</integer>
<integer>1529132</integer>
<integer>1602608</integer>
<integer>1651681</integer>
<integer>1750461</integer>
<integer>1930253</integer>
<integer>1961532</integer>
<integer>1973932</integer>
<integer>2026202</integer>
<integer>2526384</integer>
<integer>2641622</integer>
<integer>2703653</integer>
</array>
<key>vendorId</key>
<integer>0</integer>
<key>versionRestrictions</key>
<integer>0</integer>
</dict>
</plist>
Obviously, replace all instances of MyApp with the name of your app and MyCompany with the name of your company.
Basically, this will install on any jailbroken device with Installous installed. After it is set up, this results in very fast deployment, as it can be installed from anywhere, just upload it to your companies website, and download the file directly to the device, and copy / move it to ~/Documents/Installous/Downloads
.
If you set up an IAM role for your server that has the AmazonAPIGatewayInvokeFullAccess permission, you still need to pass headers on each request. You can do this in python with the aws-requests-auth library like so:
import requests
from aws_requests_auth.boto_utils import BotoAWSRequestsAuth
auth = BotoAWSRequestsAuth(
aws_host="API_ID.execute-api.us-east-1.amazonaws.com",
aws_region="us-east-1",
aws_service="execute-api"
)
response = requests.get("https://API_ID.execute-api.us-east-1.amazonaws.com/STAGE/RESOURCE", auth=auth)
None of the answers here show the difference, which could be helpful for folks struggling to understand the difference. Consider this sample code:
using System;
using System.Collections.Generic;
namespace ExceptionDemo
{
class Program
{
static void Main(string[] args)
{
void fail()
{
(null as string).Trim();
}
void bareThrow()
{
try
{
fail();
}
catch (Exception e)
{
throw;
}
}
void rethrow()
{
try
{
fail();
}
catch (Exception e)
{
throw e;
}
}
void innerThrow()
{
try
{
fail();
}
catch (Exception e)
{
throw new Exception("outer", e);
}
}
var cases = new Dictionary<string, Action>()
{
{ "Bare Throw:", bareThrow },
{ "Rethrow", rethrow },
{ "Inner Throw", innerThrow }
};
foreach (var c in cases)
{
Console.WriteLine(c.Key);
Console.WriteLine(new string('-', 40));
try
{
c.Value();
} catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
}
}
}
Which generates the following output:
Bare Throw:
----------------------------------------
System.NullReferenceException: Object reference not set to an instance of an object.
at ExceptionDemo.Program.<Main>g__fail|0_0() in C:\...\ExceptionDemo\Program.cs:line 12
at ExceptionDemo.Program.<>c.<Main>g__bareThrow|0_1() in C:\...\ExceptionDemo\Program.cs:line 19
at ExceptionDemo.Program.Main(String[] args) in C:\...\ExceptionDemo\Program.cs:line 64
Rethrow
----------------------------------------
System.NullReferenceException: Object reference not set to an instance of an object.
at ExceptionDemo.Program.<>c.<Main>g__rethrow|0_2() in C:\...\ExceptionDemo\Program.cs:line 35
at ExceptionDemo.Program.Main(String[] args) in C:\...\ExceptionDemo\Program.cs:line 64
Inner Throw
----------------------------------------
System.Exception: outer ---> System.NullReferenceException: Object reference not set to an instance of an object.
at ExceptionDemo.Program.<Main>g__fail|0_0() in C:\...\ExceptionDemo\Program.cs:line 12
at ExceptionDemo.Program.<>c.<Main>g__innerThrow|0_3() in C:\...\ExceptionDemo\Program.cs:line 43
--- End of inner exception stack trace ---
at ExceptionDemo.Program.<>c.<Main>g__innerThrow|0_3() in C:\...\ExceptionDemo\Program.cs:line 47
at ExceptionDemo.Program.Main(String[] args) in C:\...\ExceptionDemo\Program.cs:line 64
The bare throw, as indicated in the previous answers, clearly shows both the original line of code that failed (line 12) as well as the two other points active in the call stack when the exception occurred (lines 19 and 64).
The output of the re-throw case shows why it's a problem. When the exception is rethrown like this the exception won't include the original stack information. Note that only the throw e
(line 35) and outermost call stack point (line 64) are included. It would be difficult to track down the fail() method as the source of the problem if you throw exceptions this way.
The last case (innerThrow) is most elaborate and includes more information than either of the above. Since we're instantiating a new exception we get the chance to add contextual information (the "outer" message, here but we can also add to the .Data dictionary on the new exception) as well as preserving all of the information in the original exception (including help links, data dictionary, etc.).
Modal In Out Effect with Animate.css and jquery Very easy and short code.
In HTML:
<div class="modal fade" id="DirectorModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog bounceInDown animated"><!-- Add here Modal COME Effect "Animate.css" -->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Modal Header</h4>
</div>
<div class="modal-body">
</div>
</div>
</div>
</div>
this bellow jquery code i got from: https://codepen.io/nhembram/pen/PzyYLL
i am modify this for regular use.
jquery code:
<script>
$(document).ready(function () {
// BS MODAL OPEN CLOSE EFFECT ---------------------------------
var timeoutHandler = null;
$('.modal').on('hide.bs.modal', function (e) {
var anim = $('.modal-dialog').removeClass('bounceInDown').addClass('fadeOutDownBig'); // Model Come class Remove & Out effect class add
if (timeoutHandler) clearTimeout(timeoutHandler);
timeoutHandler = setTimeout(function() {
$('.modal-dialog').removeClass('fadeOutDownBig').addClass('bounceInDown'); // Model Out class Remove & Come effect class add
}, 500); // some delay for complete Animation
});
});
</script>
In jsp you can do it like this:
<%
boolean checkboxDisabled = true; //do your logic here
String checkboxState = checkboxDisabled ? "disabled" : "";
%>
<input type="checkbox" <%=checkboxState%>>
In simplest terms :
Keystore is used to store your credential (server or client) while truststore is used to store others credential (Certificates from CA).
Keystore is needed when you are setting up server side on SSL, it is used to store server's identity certificate, which server will present to a client on the connection while trust store setup on client side must contain to make the connection work. If you browser to connect to any website over SSL it verifies certificate presented by server against its truststore.
See http://api.jquery.com/jQuery.ajax/, there's mention of datatype and contentType there.
They are both used in the request to the server so the server knows what kind of data to receive/send.
You must place the label after a caption in order to for label
to store the table's number, not the chapter's number.
\begin{table} \begin{tabular}{| p{5cm} | p{5cm} | p{5cm} |} -- cut -- \end{tabular} \caption{My table} \label{table:kysymys} \end{table} Table \ref{table:kysymys} on page \pageref{table:kysymys} refers to the ...
I'd rather use the bas64 encode/decode methods from CryptoJS, the most popular library for standard and secure cryptographic algorithms implemented in JavaScript using best practices and patterns.
Preserving the validity of iterators is one reason to use a list. Another is when you don't want a vector to reallocate when pushing items. This can be managed by an intelligent use of reserve(), but in some cases it might be easier or more feasible to just use a list.
Just as an alternative, you can use ancestor
.
//*[title="50"]/ancestor::store
It's more powerful than parent
since it can get even the grandparent or great great grandparent
Alternatively to usleep()
, which is not defined in POSIX 2008 (though it was defined up to POSIX 2004, and it is evidently available on Linux and other platforms with a history of POSIX compliance), the POSIX 2008 standard defines nanosleep()
:
nanosleep
- high resolution sleep#include <time.h> int nanosleep(const struct timespec *rqtp, struct timespec *rmtp);
The
nanosleep()
function shall cause the current thread to be suspended from execution until either the time interval specified by therqtp
argument has elapsed or a signal is delivered to the calling thread, and its action is to invoke a signal-catching function or to terminate the process. The suspension time may be longer than requested because the argument value is rounded up to an integer multiple of the sleep resolution or because of the scheduling of other activity by the system. But, except for the case of being interrupted by a signal, the suspension time shall not be less than the time specified byrqtp
, as measured by the system clock CLOCK_REALTIME.The use of the
nanosleep()
function has no effect on the action or blockage of any signal.
There are 3 access specifiers
for a class/struct/Union in C++. These access specifiers define how the members of the class can be accessed. Of course, any member of a class is accessible within that class(Inside any member function of that same class). Moving ahead to type of access specifiers, they are:
Public - The members declared as Public are accessible from outside the Class through an object of the class.
Protected - The members declared as Protected are accessible from outside the class BUT only in a class derived from it.
Private - These members are only accessible from within the class. No outside Access is allowed.
An Source Code Example:
class MyClass
{
public:
int a;
protected:
int b;
private:
int c;
};
int main()
{
MyClass obj;
obj.a = 10; //Allowed
obj.b = 20; //Not Allowed, gives compiler error
obj.c = 30; //Not Allowed, gives compiler error
}
Inheritance in C++ can be one of the following types:
Private
Inheritance Public
Inheritance Protected
inheritance Here are the member access rules with respect to each of these:
First and most important rule
Private
members of a class are never accessible from anywhere except the members of the same class.
All
Public
members of the Base Class becomePublic
Members of the derived class &
AllProtected
members of the Base Class becomeProtected
Members of the Derived Class.
i.e. No change in the Access of the members. The access rules we discussed before are further then applied to these members.
Code Example:
Class Base
{
public:
int a;
protected:
int b;
private:
int c;
};
class Derived:public Base
{
void doSomething()
{
a = 10; //Allowed
b = 20; //Allowed
c = 30; //Not Allowed, Compiler Error
}
};
int main()
{
Derived obj;
obj.a = 10; //Allowed
obj.b = 20; //Not Allowed, Compiler Error
obj.c = 30; //Not Allowed, Compiler Error
}
All
Public
members of the Base Class becomePrivate
Members of the Derived class &
AllProtected
members of the Base Class becomePrivate
Members of the Derived Class.
An code Example:
Class Base
{
public:
int a;
protected:
int b;
private:
int c;
};
class Derived:private Base //Not mentioning private is OK because for classes it defaults to private
{
void doSomething()
{
a = 10; //Allowed
b = 20; //Allowed
c = 30; //Not Allowed, Compiler Error
}
};
class Derived2:public Derived
{
void doSomethingMore()
{
a = 10; //Not Allowed, Compiler Error, a is private member of Derived now
b = 20; //Not Allowed, Compiler Error, b is private member of Derived now
c = 30; //Not Allowed, Compiler Error
}
};
int main()
{
Derived obj;
obj.a = 10; //Not Allowed, Compiler Error
obj.b = 20; //Not Allowed, Compiler Error
obj.c = 30; //Not Allowed, Compiler Error
}
All
Public
members of the Base Class becomeProtected
Members of the derived class &
AllProtected
members of the Base Class becomeProtected
Members of the Derived Class.
A Code Example:
Class Base
{
public:
int a;
protected:
int b;
private:
int c;
};
class Derived:protected Base
{
void doSomething()
{
a = 10; //Allowed
b = 20; //Allowed
c = 30; //Not Allowed, Compiler Error
}
};
class Derived2:public Derived
{
void doSomethingMore()
{
a = 10; //Allowed, a is protected member inside Derived & Derived2 is public derivation from Derived, a is now protected member of Derived2
b = 20; //Allowed, b is protected member inside Derived & Derived2 is public derivation from Derived, b is now protected member of Derived2
c = 30; //Not Allowed, Compiler Error
}
};
int main()
{
Derived obj;
obj.a = 10; //Not Allowed, Compiler Error
obj.b = 20; //Not Allowed, Compiler Error
obj.c = 30; //Not Allowed, Compiler Error
}
Remember the same access rules apply to the classes and members down the inheritance hierarchy.
- Access Specification is per-Class not per-Object
Note that the access specification C++ work on per-Class basis and not per-object basis.
A good example of this is that in a copy constructor or Copy Assignment operator function, all the members of the object being passed can be accessed.
- A Derived class can only access members of its own Base class
Consider the following code example:
class Myclass
{
protected:
int x;
};
class derived : public Myclass
{
public:
void f( Myclass& obj )
{
obj.x = 5;
}
};
int main()
{
return 0;
}
It gives an compilation error:
prog.cpp:4: error: ‘int Myclass::x’ is protected
Because the derived class can only access members of its own Base Class. Note that the object obj
being passed here is no way related to the derived
class function in which it is being accessed, it is an altogether different object and hence derived
member function cannot access its members.
friend
? How does friend
affect access specification rules?You can declare a function or class as friend
of another class. When you do so the access specification rules do not apply to the friend
ed class/function. The class or function can access all the members of that particular class.
So do
friend
s break Encapsulation?
No they don't, On the contrary they enhance Encapsulation!
friend
ship is used to indicate a intentional strong coupling between two entities.
If there exists a special relationship between two entities such that one needs access to others private
or protected
members but You do not want everyone to have access by using the public
access specifier then you should use friend
ship.
What about naming your column?
INSERT INTO dbo.rLicenses (name) VALUES ('test')
It's been years since I tried updating via a view so YMMV as HLGEM mentioned.
I would consider an "INSTEAD OF" trigger on the view to allow a simple INSERT dbo.Licenses
(ie the table) in the trigger
Use window.open("file2.html");
Syntax
var windowObjectReference = window.open(strUrl, strWindowName[, strWindowFeatures]);
Return value and parameters
windowObjectReference
A reference to the newly created window. If the call failed, it will be null. The reference can be used to access properties and methods of the new window provided it complies with Same origin policy security requirements.
strUrl
The URL to be loaded in the newly opened window. strUrl
can be an HTML document on the web, image file or any resource supported by the browser.
strWindowName
A string name for the new window. The name can be used as the target of links and forms using the target attribute of an <a>
or <form>
element. The name should not contain any blank space. Note that strWindowName
does not specify the title of the new window.
strWindowFeatures
Optional parameter listing the features (size, position, scrollbars, etc.) of the new window. The string must not contain any blank space, each feature name and value must be separated by a comma.
If you want to use default value for a DateTime parameter in a method, you can only use default(DateTime).
The following line will not compile:
private void MyMethod(DateTime syncedTime = DateTime.MinValue)
This line will compile:
private void MyMethod(DateTime syncedTime = default(DateTime))
ImageArtist is a pure gd wrapper authored by me, this enables you to do complex image manipulations insanely easy, for your question solution can be done using very few steps using this powerful library.
here is a sample code.
$img1 = new Image("./cover.jpg");
$img2 = new Image("./box.png");
$img2->merge($img1,9,9);
$img2->save("./merged.png",IMAGETYPE_PNG);
This is how my result looks like.
The @ symbol serves 2 purposes in C#:
Firstly, it allows you to use a reserved keyword as a variable like this:
int @int = 15;
The second option lets you specify a string without having to escape any characters. For instance the '\' character is an escape character so typically you would need to do this:
var myString = "c:\\myfolder\\myfile.txt"
alternatively you can do this:
var myString = @"c:\myFolder\myfile.txt"
One suspects this perennial bit of manager-candy was coined when everything was a sys app written in C because if nothing else the magic number would vary by orders of magnitude depending on the language, scale and nature of the application. And then you have to discount comments and attributes. And ultimately who cares about the number of lines of code written? Are you supposed to be finished when you've reach 10K lines? 100K? So arbitrary.
It's useless.
Make sure that your query ran successfully and you got the results. You can check like this:
$result = mysql_query("SELECT * FROM student WHERE IDNO=".$_GET['id']) or die(mysql_error());
if (is_resource($result))
{
// your while loop and fetch array function here....
}
In addition to the other responses:
Once obtained, Access Tokens are typically sent along with every request from Clients to protected Resource Servers. This induce a risk for access token stealing and replay (assuming of course that access tokens are of type "Bearer" (as defined in the initial RFC6750).
Examples of those risks, in real life:
Resource Servers generally are distributed application servers and typically have lower security levels compared to Authorization Servers (lower SSL/TLS config, less hardening, etc.). Authorization Servers on the other hand are usually considered as critical Security infrastructure and are subject to more severe hardening.
Access Tokens may show up in HTTP traces, logs, etc. that are collected legitimately for diagnostic purposes on the Resource Servers or clients. Those traces can be exchanged over public or semi-public places (bug tracers, service-desk, etc.).
Backend RS applications can be outsourced to more or less trustworthy third-parties.
The Refresh Token, on the other hand, is typically transmitted only twice over the wires, and always between the client and the Authorization Server: once when obtained by client, and once when used by client during refresh (effectively "expiring" the previous refresh token). This is a drastically limited opportunity for interception and replay.
Last thought, Refresh Tokens offer very little protection, if any, against compromised clients.
I used below ms sql script pattern several times successfully which uses Try-Catch,Commit Transaction- Rollback Transaction,Error Tracking.
Your TRY block will be as follows
BEGIN TRY
BEGIN TRANSACTION T
----
//your script block
----
COMMIT TRANSACTION T
END TRY
Your CATCH block will be as follows
BEGIN CATCH
DECLARE @ErrMsg NVarChar(4000),
@ErrNum Int,
@ErrSeverity Int,
@ErrState Int,
@ErrLine Int,
@ErrProc NVarChar(200)
SELECT @ErrNum = Error_Number(),
@ErrSeverity = Error_Severity(),
@ErrState = Error_State(),
@ErrLine = Error_Line(),
@ErrProc = IsNull(Error_Procedure(), '-')
SET @ErrMsg = N'ErrLine: ' + rtrim(@ErrLine) + ', proc: ' + RTRIM(@ErrProc) + ',
Message: '+ Error_Message()
Your ROLLBACK script will be part of CATCH block as follows
IF (@@TRANCOUNT) > 0
BEGIN
PRINT 'ROLLBACK: ' + SUBSTRING(@ErrMsg,1,4000)
ROLLBACK TRANSACTION T
END
ELSE
BEGIN
PRINT SUBSTRING(@ErrMsg,1,4000);
END
END CATCH
Above different script blocks you need to use as one block. If any error happens in the TRY block it will go the the CATCH block. There it is setting various details about the error number,error severity,error line ..etc. At last all these details will get append to @ErrMsg parameter. Then it will check for the count of transaction (@@TRANCOUNT >0) , ie if anything is there in the transaction for rollback. If it is there then show the error message and ROLLBACK TRANSACTION. Otherwise simply print the error message.
We have kept our COMMIT TRANSACTION T script towards the last line of TRY block in order to make sure that it should commit the transaction(final change in the database) only after all the code in the TRY block has run successfully.
My problem was unrelated to processData
. It was because I sent a function that cannot be called later with apply
because it did not have enough arguments. Specifically I shouldn't have used alert
as the error
callback.
$.ajax({
url: csvApi,
success: parseCsvs,
dataType: "json",
timeout: 5000,
processData: false,
error: alert
});
See this answer for more information on why that can be a problem: Why are certain function calls termed "illegal invocations" in JavaScript?
The way I was able to discover this was by adding a console.log(list[ firingIndex ])
to jQuery so I could track what it was firing.
This was the fix:
function myError(jqx, textStatus, errStr) {
alert(errStr);
}
$.ajax({
url: csvApi,
success: parseCsvs,
dataType: "json",
timeout: 5000,
error: myError // Note that passing `alert` instead can cause a "jquery.js:3189 Uncaught TypeError: Illegal invocation" sometimes
});
Here, save and try this script (kill_ipcs.sh) on your shell:
#!/bin/bash
ME=`whoami`
IPCS_S=`ipcs -s | egrep "0x[0-9a-f]+ [0-9]+" | grep $ME | cut -f2 -d" "`
IPCS_M=`ipcs -m | egrep "0x[0-9a-f]+ [0-9]+" | grep $ME | cut -f2 -d" "`
IPCS_Q=`ipcs -q | egrep "0x[0-9a-f]+ [0-9]+" | grep $ME | cut -f2 -d" "`
for id in $IPCS_M; do
ipcrm -m $id;
done
for id in $IPCS_S; do
ipcrm -s $id;
done
for id in $IPCS_Q; do
ipcrm -q $id;
done
We use it whenever we run IPCS programs in the university student server. Some people don't always cleanup so...it's needed :P
You can adjust the subplot geometry in the very tight_layout
call as follows:
fig.tight_layout(rect=[0, 0.03, 1, 0.95])
As it's stated in the documentation (https://matplotlib.org/users/tight_layout_guide.html):
tight_layout()
only considers ticklabels, axis labels, and titles. Thus, other artists may be clipped and also may overlap.
Define a behavior in your .config
file:
<configuration>
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name="debug">
<serviceDebug includeExceptionDetailInFaults="true" />
</behavior>
</serviceBehaviors>
</behaviors>
...
</system.serviceModel>
</configuration>
Then apply the behavior to your service along these lines:
<configuration>
<system.serviceModel>
...
<services>
<service name="MyServiceName" behaviorConfiguration="debug" />
</services>
</system.serviceModel>
</configuration>
You can also set it programmatically. See this question.
If you are looking for ReactNative's componentDidMount
equivalent, Flutter has it. It's not that simple but it's working just the same way. In Flutter, Widget
s do not handle their events directly. Instead they use their State
object to do that.
class MyWidget extends StatefulWidget{
@override
State<StatefulWidget> createState() => MyState(this);
Widget build(BuildContext context){...} //build layout here
void onLoad(BuildContext context){...} //callback when layout build done
}
class MyState extends State<MyWidget>{
MyWidget widget;
MyState(this.widget);
@override
Widget build(BuildContext context) => widget.build(context);
@override
void initState() => widget.onLoad(context);
}
State.initState
immediately will be called once upon screen has finishes rendering the layout. And will never again be called even on hot reload if you're in debug mode, until explicitly reaches time to do so.
you can Try the following snippet:
var str = "How are you doing today?";
var res = str.split("o");
console.log("My Result:",res)
and your output like that
My Result: H,w are y,u d,ing t,day?
jQuery UI extends the jQuery native toggleClass
to take a second optional parameter: duration
toggleClass( class, [duration] )
To expand on @T.J.'s answer, if you're looking for simple months, rather than full calendar months, you could just check if d2's date is greater than or equal to than d1's. That is, if d2 is later in its month than d1 is in its month, then there is 1 more month. So you should be able to just do this:
function monthDiff(d1, d2) {
var months;
months = (d2.getFullYear() - d1.getFullYear()) * 12;
months -= d1.getMonth() + 1;
months += d2.getMonth();
// edit: increment months if d2 comes later in its month than d1 in its month
if (d2.getDate() >= d1.getDate())
months++
// end edit
return months <= 0 ? 0 : months;
}
monthDiff(
new Date(2008, 10, 4), // November 4th, 2008
new Date(2010, 2, 12) // March 12th, 2010
);
// Result: 16; 4 Nov – 4 Dec '08, 4 Dec '08 – 4 Dec '09, 4 Dec '09 – 4 March '10
This doesn't totally account for time issues (e.g. 3 March at 4:00pm and 3 April at 3:00pm), but it's more accurate and for just a couple lines of code.
From Alexandre Gomes Blog I have not tried it. Let me know if it works for you.
function getScrollBarWidth () {
var inner = document.createElement('p');
inner.style.width = "100%";
inner.style.height = "200px";
var outer = document.createElement('div');
outer.style.position = "absolute";
outer.style.top = "0px";
outer.style.left = "0px";
outer.style.visibility = "hidden";
outer.style.width = "200px";
outer.style.height = "150px";
outer.style.overflow = "hidden";
outer.appendChild (inner);
document.body.appendChild (outer);
var w1 = inner.offsetWidth;
outer.style.overflow = 'scroll';
var w2 = inner.offsetWidth;
if (w1 == w2) w2 = outer.clientWidth;
document.body.removeChild (outer);
return (w1 - w2);
};
In 2010 it is Ctrl+k, Ctrl+d. See image below.
public static double calculateInventoryTotal(Book[] arrayBooks) {
final AtomicReference<BigDecimal> total = new AtomicReference<>(BigDecimal.ZERO);
Optional.ofNullable(arrayBooks).map(Arrays::asList).ifPresent(books -> books.forEach(book -> total.accumulateAndGet(book.getPrice(), BigDecimal::add)));
return total.get().doubleValue();
}
The problem of most of the answers, that they are good for unique items in list. If items are not unique and you still want to know whether there is an intersection, you should count items:
from collections import Counter as count
def listContains(l1, l2):
list1 = count(l1)
list2 = count(l2)
return list1&list2 == list1
print( listContains([1,1,2,5], [1,2,3,5,1,2,1]) ) # Returns True
print( listContains([1,1,2,8], [1,2,3,5,1,2,1]) ) # Returns False
You can also return the intersection by using ''.join(list1&list2)
Very safe:
the annual risk of a given person being hit by a meteorite is estimated to be one chance in 17 billion, which means the probability is about 0.00000000006 (6 × 10-11), equivalent to the odds of creating a few tens of trillions of UUIDs in a year and having one duplicate. In other words, only after generating 1 billion UUIDs every second for the next 100 years, the probability of creating just one duplicate would be about 50%.
Caveat:
However, these probabilities only hold when the UUIDs are generated using sufficient entropy. Otherwise, the probability of duplicates could be significantly higher, since the statistical dispersion might be lower. Where unique identifiers are required for distributed applications, so that UUIDs do not clash even when data from many devices is merged, the randomness of the seeds and generators used on every device must be reliable for the life of the application. Where this is not feasible, RFC4122 recommends using a namespace variant instead.
Source: The Random UUID probability of duplicates section of the Wikipedia article on Universally unique identifiers (link leads to a revision from December 2016 before editing reworked the section).
Also see the current section on the same subject on the same Universally unique identifier article, Collisions.
You can do something similar to this:
// Get the parent to attatch the element into
var parent = document.getElementsByTagName("ul")[0];
// Create element with random id
var element = document.createElement("li");
element.id = "li-"+Math.floor(Math.random()*9999);
// Add event listener
element.addEventListener("click", EVENT_FN);
// Add to parent
parent.appendChild(element);
ASCII is a subset of UTF-8, so all ASCII files are already UTF-8 encoded. The bytes in the ASCII file and the bytes that would result from "encoding it to UTF-8" would be exactly the same bytes. There's no difference between them, so there's no need to do anything.
It looks like your problem is that the files are not actually ASCII. You need to determine what encoding they are using, and transcode them properly.
Give the path of the script, that is, path setting by cmd:
$> . c:\program file\prog.ps1
Run the entry point function of PowerShell:
For example, $> add or entry_func or main
I had originally asked myself the question "Do I need a PDB file deployed to my customer's machine?", and after reading this post, decided to exclude the file.
Everything worked fine, until today, when I was trying to figure out why a message box containing an Exception.StackTrace
was missing the file and line number information - necessary for troubleshooting the exception. I re-read this post and found the key nugget of information: that although the PDB is not necessary for the app to run, it is necessary for the file and line numbers to be present in the StackTrace
string. I included the PDB file in the executable folder and now all is fine.
Here's how I managed to do something similar to this inside a <footer>
element:
<div class="content-wrapper">
<div style="float:left">
<p>© 2012 - @DateTime.Now.Year @Localization.ClientName</p>
</div>
<div style="float:right">
<p>@Localization.DevelopedBy <a href="http://leniel.net" target="_blank">Leniel Macaferi</a></p>
</div>
<div style="text-align:center;">
<p>? (24) 3347-3110 | (24) 8119-1085 ? @Html.ActionLink(Localization.Contact, MVC.Home.ActionNames.Contact, MVC.Home.Name)</p>
</div>
</div>
CSS:
.content-wrapper
{
margin: 0 auto;
max-width: 1216px;
}
Have you tried this?
<appSettings>
<add key="myurl" value="http://www.myurl.com?&cid=&sid="/>
<appSettings>
Try this:
x <- "some text in a string"
n <- 5
substr(x, nchar(x)-n, nchar(x))
It shoudl give:
[1] "string"
class Foo(object):
bar = 1
def bah(object_reference):
object_reference.var = Foo.bar
return object_reference.var
f = Foo()
print 'var=', f.bah()
I had a similar issue. I needed to keep the legacy encrypted passwords (Base64/SHA-1/Random salt Encoded) as users will not want to change their passwords or re-register. However I wanted to use the BCrypt encoder moving forward too.
My solution was to write a bespoke decoder that checks to see which encryption method was used first before matching (BCrypted ones start with $
).
To get around the salt issue, I pass into the decoder a concatenated String of salt + encrypted password via my modified user object.
Decoder
@Component
public class LegacyEncoder implements PasswordEncoder {
private static final String BCRYP_TYPE = "$";
private static final PasswordEncoder BCRYPT = new BCryptPasswordEncoder();
@Override
public String encode(CharSequence rawPassword) {
return BCRYPT.encode(rawPassword);
}
@Override
public boolean matches(CharSequence rawPassword, String encodedPassword) {
if (encodedPassword.startsWith(BCRYP_TYPE)) {
return BCRYPT.matches(rawPassword, encodedPassword);
}
return sha1SaltMatch(rawPassword, encodedPassword);
}
@SneakyThrows
private boolean sha1SaltMatch(CharSequence rawPassword, String encodedPassword) {
String[] saltHash = encodedPassword.split(User.SPLIT_CHAR);
// Legacy code from old system
byte[] b64salt = Base64.getDecoder().decode(saltHash[0].getBytes());
byte[] validHash = Base64.getDecoder().decode(saltHash[1]);
byte[] checkHash = Utility.getHash(5, rawPassword.toString(), b64salt);
return Arrays.equals(checkHash, validHash);
}
}
User Object
public class User implements UserDetails {
public static final String SPLIT_CHAR = ":";
@Id
@Column(name = "user_id", nullable = false)
private Integer userId;
@Column(nullable = false, length = 60)
private String password;
@Column(nullable = true, length = 32)
private String salt;
.
.
@PostLoad
private void init() {
username = emailAddress; //To comply with UserDetails
password = salt == null ? password : salt + SPLIT_CHAR + password;
}
You can also add a hook to re-encode the password in the new BCrypt format and replace it. Thus phasing out the old method.
Here's a quick-and-dirty technique I have used:
SELECT * FROM Tags
WHERE '|ruby|rails|scruffy|rubyonrails|'
LIKE '%|' + Name + '|%'
So here's the C# code:
string[] tags = new string[] { "ruby", "rails", "scruffy", "rubyonrails" };
const string cmdText = "select * from tags where '|' + @tags + '|' like '%|' + Name + '|%'";
using (SqlCommand cmd = new SqlCommand(cmdText)) {
cmd.Parameters.AddWithValue("@tags", string.Join("|", tags);
}
Two caveats:
LIKE "%...%"
queries are not indexed.|
, blank, or null tags or this won't workThere are other ways to accomplish this that some people may consider cleaner, so please keep reading.
You want to convert html (a byte-like object) into a string using .decode
, e.g. html = response.read().decode('utf-8')
.
I came across a similar problem (wanting to pull a commit that included some binary files which caused conflicts when merged), but came across a different solution that can be done entirely using git (i.e. not having to manually copy files over). I figured I'd include it here so at the very least I can remember it the next time I need it. :) The steps look like this:
% git fetch
This fetches the latest commit(s) from the remote repository (you may need to specify a remote branch name, depending on your setup), but doesn't try to merge them. It records the the commit in FETCH_HEAD
% git checkout FETCH_HEAD stuff/to/update
This takes the copy of the binary files I want and overwrites what's in the working tree with the version fetched from the remote branch. git doesn't try to do any merging, so you just end up with an exact copy of the binary file from the remote branch. Once that's done, you can add/commit the new copy just like normal.
You can directly create your own style in this way:
input[type=button]
{
//Change the style as you like
}
With IntelliJ, you can do this from the test configuration. Once you open this window, you can choose to run the test any number of times you want,.
when you run the test, intellij will execute all tests you have selected for the number of times you specified.
It's declaring the string as nvarchar
data type, rather than varchar
You may have seen Transact-SQL code that passes strings around using an N prefix. This denotes that the subsequent string is in Unicode (the N actually stands for National language character set). Which means that you are passing an NCHAR, NVARCHAR or NTEXT value, as opposed to CHAR, VARCHAR or TEXT.
To quote from Microsoft:
Prefix Unicode character string constants with the letter N. Without the N prefix, the string is converted to the default code page of the database. This default code page may not recognize certain characters.
If you want to know the difference between these two data types, see this SO post: