SessionFactory
vs. EntityManagerFactory
As I explained in the Hibernate User Guide, the Hibernate SessionFactory
extends the JPA EntityManagerFactory
, as illustrated by the following diagram:
So, the SessionFactory
is also a JPA EntityManagerFactory
.
Both the SessionFactory
and the EntityManagerFactory
contain the entity mapping metadata and allow you to create a Hibernate Session
or a EntityManager
.
Session
vs. EntityManager
Just like the SessionFactory
and EntityManagerFactory
, the Hibernate Session
extends the JPA EntityManager
. So, all methods defined by the EntityManager
are available in the Hibernate Session
.
The Session
and the `EntityManager translate entity state transitions into SQL statements, like SELECT, INSERT, UPDATE, and DELETE.
When bootstrapping a JPA or Hibernate application, you have two choices:
SessionFactory
via the BootstrapServiceRegistryBuilder
. If you're using Spring, the Hibernate bootstrap is done via the LocalSessionFactoryBean
, as illustrated by this GitHub example.EntityManagerFactory
via the Persistence
class or the EntityManagerFactoryBuilder
. If you're using Spring, the JPA bootstrap is done via the LocalContainerEntityManagerFactoryBean
, as illustrated by this GitHub example.Bootstrapping via JPA is to be preferred. That's because the JPA FlushModeType.AUTO
is a much better choice than the legacy FlushMode.AUTO
, which breaks read-your-writes consistency for native SQL queries.
Also, if you bootstrap via JPA, and you have injected the EntityManagerFactory
via the @PersistenceUnit
annotation:
@PersistenceUnit
private EntityManagerFactory entityManagerFactory;
You can easily get access to the underlying Sessionfactory
using the unwrap
method:
SessionFactory sessionFactory = entityManagerFactory.unwrap(SessionFactory.class);
The same can be done with the JPA EntityManager
. If you inject the EntityManager
via the @PersistenceContext
annotation:
@PersistenceContext
private EntityManager entityManager;
You can easily get access to the underlying Session
using the unwrap
method:
Session session = entityManager.unwrap(Session.class);
So, you should bootstrap via JPA, use the EntityManagerFactory
and EntityManager
, and only unwrap those to their associated Hibernate interfaces when you want to get access to some Hibernate-specific methods that are not available in JPA, like fetching the entity via its natural identifier.
1) check if service declaration in manifest is nested in application tag
<application>
<service android:name="" />
</application>
2) check if your service.java
is in the same package or diff package as the activity
<application>
<!-- service.java exists in diff package -->
<service android:name="com.package.helper.service" />
</application>
<application>
<!-- service.java exists in same package -->
<service android:name=".service" />
</application>
In stall PuTTY in our system and set the environment variable PATH Pointing to putty path. open the command prompt and move to putty folder. Using PSCP command
Yet another approach is ISNULL().
UPDATE [DATABASE].[dbo].[TABLE_NAME]
SET
[ABC] = ISNULL(@ABC, [ABC]),
[ABCD] = ISNULL(@ABCD, [ABCD])
The difference between ISNULL and COALESCE is the return type. COALESCE can also take more than 2 arguments, and use the first that is not null. I.e.
select COALESCE(null, null, 1, 'two') --returns 1
select COALESCE(null, null, null, 'two') --returns 'two'
In PostgreSQL 9.1, the idle connections with following query. It helped me to ward off the situation which warranted in restarting the database. This happens mostly with JDBC connections opened and not closed properly.
SELECT
pg_terminate_backend(procpid)
FROM
pg_stat_activity
WHERE
current_query = '<IDLE>'
AND
now() - query_start > '00:10:00';
char ch = 't';
char chArray[2];
sprintf(chArray, "%c", ch);
char chOutput[10]="tes";
strcat(chOutput, chArray);
cout<<chOutput;
OUTPUT:
test
Boosting your maven-compiler-plugin to 3.8.0 seems to be necessary but not sufficient. If you're still having problems, you should also make sure your JAVA_HOME environment variable is set to Java 10 (or 11) if you're running from the command line. (The error message you get won't tell you this.) Or if you're running from an IDE, you need to make sure it is set to run maven with your current JDK.
I had the same issue with importing matplotlib.pylab with Python 3.5.1 on Win 64. Installing the Visual C++ Redistributable für Visual Studio 2015 from this links: https://www.microsoft.com/en-us/download/details.aspx?id=48145 fixed the missing DLLs.
I find it better and easier than downloading and pasting DLLs.
If you are truly looking to replicate Contains, but for an array, here is an extension method and sample code for usage:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ContainsAnyThingy
{
class Program
{
static void Main(string[] args)
{
string testValue = "123345789";
//will print true
Console.WriteLine(testValue.ContainsAny("123", "987", "554"));
//but so will this also print true
Console.WriteLine(testValue.ContainsAny("1", "987", "554"));
Console.ReadKey();
}
}
public static class StringExtensions
{
public static bool ContainsAny(this string str, params string[] values)
{
if (!string.IsNullOrEmpty(str) || values.Length > 0)
{
foreach (string value in values)
{
if(str.Contains(value))
return true;
}
}
return false;
}
}
}
As long as you don't need the definition (think pointers and references) you can get away with forward declarations. This is why mostly you'd see them in headers while implementation files typically will pull the header for the appropriate definition(s).
Non of above solutions worked well for me. I ended up by using an edited version of @ryascl solution as below:
/// <summary>
/// Depth-first recursive delete, with handling for descendant
/// directories open in Windows Explorer.
/// </summary>
public static void DeleteDirectory(string path)
{
foreach (string directory in Directory.GetDirectories(path))
{
Thread.Sleep(1);
DeleteDir(directory);
}
DeleteDir(path);
}
private static void DeleteDir(string dir)
{
try
{
Thread.Sleep(1);
Directory.Delete(dir, true);
}
catch (IOException)
{
DeleteDir(dir);
}
catch (UnauthorizedAccessException)
{
DeleteDir(dir);
}
}
You may be an administrator on the workstation, but that means nothing to SQL Server. Your login has to be a member of the sysadmin role in order to perform the actions in question. By default, the local administrators group is no longer added to the sysadmin role in SQL 2008 R2. You'll need to login with something else (sa for example) in order to grant yourself the permissions.
This API gives you the current time and several formats in JSON - https://market.mashape.com/parsify/format#time. Here's a sample response:
{
"time": {
"daysInMonth": 31,
"millisecond": 283,
"second": 42,
"minute": 55,
"hour": 1,
"date": 6,
"day": 3,
"week": 10,
"month": 2,
"year": 2013,
"zone": "+0000"
},
"formatted": {
"weekday": "Wednesday",
"month": "March",
"ago": "a few seconds",
"calendar": "Today at 1:55 AM",
"generic": "2013-03-06T01:55:42+00:00",
"time": "1:55 AM",
"short": "03/06/2013",
"slim": "3/6/2013",
"hand": "Mar 6 2013",
"handTime": "Mar 6 2013 1:55 AM",
"longhand": "March 6 2013",
"longhandTime": "March 6 2013 1:55 AM",
"full": "Wednesday, March 6 2013 1:55 AM",
"fullSlim": "Wed, Mar 6 2013 1:55 AM"
},
"array": [
2013,
2,
6,
1,
55,
42,
283
],
"offset": 1362534942283,
"unix": 1362534942,
"utc": "2013-03-06T01:55:42.283Z",
"valid": true,
"integer": false,
"zone": 0
}
If you try exec sp_rename
and receieve a LockMatchID error then it might help to add a use [database] statement first:
I tried
exec sp_rename '[database_name].[dbo].[table_name]', 'new_table_name';
-- Invalid EXECUTE statement using object "Object", method "LockMatchID".
What I had to do to fix it was to rewrite it to:
use database_name
exec sp_rename '[dbo].[table_name]', 'new_table_name';
I suppose there is some conflict with other JS library in your code. Try to force showing the close button:
...
open:function () {
$(".ui-dialog-titlebar-close").show();
}
...
This worked for me.
I have copied your code and it runs fine.
I suspect you are simply having some problem in the actual file name of hello.txt, or you are running in a wrong directory. Consider verifying by the method suggested by @Eng.Fouad
In C & C++ single quotes is known as a character ('a') whereas double quotes is know as a string ("Hello"). The difference is that a character can store anything but only one alphabet/number etc. A string can store anything. But also remember that there is a difference between '1' and 1. If you type cout<<'1'<<endl<<1; The output would be the same, but not in this case:
cout<<int('1')<<endl<<int(1);
This time the first line would be 48. As when you convert a character to an int it converts to its ascii and the ascii for '1' is 48. Same, if you do:
string s="Hi";
s+=48; //This will add "1" to the string
s+="1"; This will also add "1" to the string
You can get Current timestamp in Android by trying below code
time.setText(String.valueOf(System.currentTimeMillis()));
and timeStamp to time format
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
String dateString = formatter.format(new Date(Long.parseLong(time.getText().toString())));
time.setText(dateString);
if you don't have any content with 100% width, you can set the background color of the track to the same color of the body's background
I had this same issue and fixed it by installing pylint in my virtualenv and then adding a .pylintrc file to my project directory with the following in the file:
[Master]
init-hook='sys.path = list(); sys.path.append("./Lib/site-packages/")'
sklearn
estimators implement methods to make it easy for you to save relevant trained properties of an estimator. Some estimators implement __getstate__
methods themselves, but others, like the GMM
just use the base implementation which simply saves the objects inner dictionary:
def __getstate__(self):
try:
state = super(BaseEstimator, self).__getstate__()
except AttributeError:
state = self.__dict__.copy()
if type(self).__module__.startswith('sklearn.'):
return dict(state.items(), _sklearn_version=__version__)
else:
return state
The recommended method to save your model to disc is to use the pickle
module:
from sklearn import datasets
from sklearn.svm import SVC
iris = datasets.load_iris()
X = iris.data[:100, :2]
y = iris.target[:100]
model = SVC()
model.fit(X,y)
import pickle
with open('mymodel','wb') as f:
pickle.dump(model,f)
However, you should save additional data so you can retrain your model in the future, or suffer dire consequences (such as being locked into an old version of sklearn).
From the documentation:
In order to rebuild a similar model with future versions of scikit-learn, additional metadata should be saved along the pickled model:
The training data, e.g. a reference to a immutable snapshot
The python source code used to generate the model
The versions of scikit-learn and its dependencies
The cross validation score obtained on the training data
This is especially true for Ensemble estimators that rely on the tree.pyx
module written in Cython(such as IsolationForest
), since it creates a coupling to the implementation, which is not guaranteed to be stable between versions of sklearn. It has seen backwards incompatible changes in the past.
If your models become very large and loading becomes a nuisance, you can also use the more efficient joblib
. From the documentation:
In the specific case of the scikit, it may be more interesting to use joblib’s replacement of
pickle
(joblib.dump
&joblib.load
), which is more efficient on objects that carry large numpy arrays internally as is often the case for fitted scikit-learn estimators, but can only pickle to the disk and not to a string:
vim /etc/default/locale
add to it:
LC_ALL="en_US.UTF-8"
You could use:
List<String> tokens = Arrays.stream(s.split("\\s+")).collect(Collectors.toList());
You should ask yourself if you really need the ArrayList in the first place. Very often, you're going to filter the list based on additional criteria, for which a Stream is perfect. You may want a set; you may want to filter them by means of another regular expression, etc. Java 8 provides this very useful extension, by the way, which will work on any CharSequence
: https://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html#splitAsStream-java.lang.CharSequence-. Since you don't need the array at all, avoid creating it thus:
// This will presumably be a static final field somewhere.
Pattern splitter = Pattern.compile("\\s+");
// ...
String untokenized = reader.readLine();
Stream<String> tokens = splitter.splitAsStream(untokenized);
I just coded a benchmark and tested the first 3 answers.
It seems that for short strings (<500 characters)
the third most voted answer is faster than the second most voted one.
For long strings (add ".repeat(300)" to the test string) the faster is answer 1 followed by the second and the third.
Note:
The above is true for browsers using v8 engine (chrome/chromium etc).
With firefox (SpiderMonkey engine) the results are totally different
Check for yourselves!! Firefox with the third solution seems to be
more than 4.5 times faster than Chrome with the first solution... crazy :D
function log(data) {_x000D_
document.getElementById("log").textContent += data + "\n";_x000D_
}_x000D_
_x000D_
benchmark = (() => {_x000D_
_x000D_
time_function = function(ms, f, num) {_x000D_
var z;_x000D_
var t = new Date().getTime();_x000D_
for (z = 0;_x000D_
((new Date().getTime() - t) < ms); z++) f(num);_x000D_
return (z / ms)_x000D_
} // returns how many times the function was run in "ms" milliseconds._x000D_
_x000D_
_x000D_
function benchmark() {_x000D_
function compare(a, b) {_x000D_
if (a[1] > b[1]) {_x000D_
return -1;_x000D_
}_x000D_
if (a[1] < b[1]) {_x000D_
return 1;_x000D_
}_x000D_
return 0;_x000D_
}_x000D_
_x000D_
// functions_x000D_
_x000D_
function replace1(s) {_x000D_
s.replace(/foo/g, "bar")_x000D_
}_x000D_
_x000D_
String.prototype.replaceAll2 = function(_f, _r){ _x000D_
_x000D_
var o = this.toString();_x000D_
var r = '';_x000D_
var s = o;_x000D_
var b = 0;_x000D_
var e = -1;_x000D_
// if(_c){ _f = _f.toLowerCase(); s = o.toLowerCase(); }_x000D_
_x000D_
while((e=s.indexOf(_f)) > -1)_x000D_
{_x000D_
r += o.substring(b, b+e) + _r;_x000D_
s = s.substring(e+_f.length, s.length);_x000D_
b += e+_f.length;_x000D_
}_x000D_
_x000D_
// Add Leftover_x000D_
if(s.length>0){ r+=o.substring(o.length-s.length, o.length); }_x000D_
_x000D_
// Return New String_x000D_
return r;_x000D_
};_x000D_
_x000D_
String.prototype.replaceAll = function(str1, str2, ignore) {_x000D_
return this.replace(new RegExp(str1.replace(/([\/\,\!\\\^\$\{\}\[\]\(\)\.\*\+\?\|\<\>\-\&])/g, "\\$&"), (ignore ? "gi" : "g")), (typeof(str2) == "string") ? str2.replace(/\$/g, "$$$$") : str2);_x000D_
}_x000D_
_x000D_
function replace2(s) {_x000D_
s.replaceAll("foo", "bar")_x000D_
}_x000D_
_x000D_
function replace3(s) {_x000D_
s.split('foo').join('bar');_x000D_
}_x000D_
_x000D_
function replace4(s) {_x000D_
s.replaceAll2("foo", "bar")_x000D_
}_x000D_
_x000D_
_x000D_
funcs = [_x000D_
[replace1, 0],_x000D_
[replace2, 0],_x000D_
[replace3, 0],_x000D_
[replace4, 0]_x000D_
];_x000D_
_x000D_
funcs.forEach((ff) => {_x000D_
console.log("Benchmarking: " + ff[0].name);_x000D_
ff[1] = time_function(2500, ff[0], "foOfoobarBaR barbarfoobarf00".repeat(10));_x000D_
console.log("Score: " + ff[1]);_x000D_
_x000D_
})_x000D_
return funcs.sort(compare);_x000D_
}_x000D_
_x000D_
return benchmark;_x000D_
})()_x000D_
log("Starting benchmark...\n");_x000D_
res = benchmark();_x000D_
console.log("Winner: " + res[0][0].name + " !!!");_x000D_
count = 1;_x000D_
res.forEach((r) => {_x000D_
log((count++) + ". " + r[0].name + " score: " + Math.floor(10000 * r[1] / res[0][1]) / 100 + ((count == 2) ? "% *winner*" : "% speed of winner.") + " (" + Math.round(r[1] * 100) / 100 + ")");_x000D_
});_x000D_
log("\nWinner code:\n");_x000D_
log(res[0][0].toString());
_x000D_
<textarea rows="50" cols="80" style="font-size: 16; resize:none; border: none;" id="log"></textarea>
_x000D_
The test will run for 10s (+2s) as you click the button.
My results (on the same pc):
Chrome/Linux Ubuntu 64:
1. replace1 score: 100% *winner* (766.18)
2. replace4 score: 99.07% speed of winner. (759.11)
3. replace3 score: 68.36% speed of winner. (523.83)
4. replace2 score: 59.35% speed of winner. (454.78)
Firefox/Linux Ubuntu 64
1. replace3 score: 100% *winner* (3480.1)
2. replace1 score: 13.06% speed of winner. (454.83)
3. replace4 score: 9.4% speed of winner. (327.42)
4. replace2 score: 4.81% speed of winner. (167.46)
Nice mess uh?
Took the liberty of adding more test results
Chrome/Windows 10
1. replace1 score: 100% *winner* (742.49)
2. replace4 score: 85.58% speed of winner. (635.44)
3. replace2 score: 54.42% speed of winner. (404.08)
4. replace3 score: 50.06% speed of winner. (371.73)
Firefox/Windows 10
1. replace3 score: 100% *winner* (2645.18)
2. replace1 score: 30.77% speed of winner. (814.18)
3. replace4 score: 22.3% speed of winner. (589.97)
4. replace2 score: 12.51% speed of winner. (331.13)
Edge/Windows 10
1. replace1 score: 100% *winner* (1251.24)
2. replace2 score: 46.63% speed of winner. (583.47)
3. replace3 score: 44.42% speed of winner. (555.92)
4. replace4 score: 20% speed of winner. (250.28)
Chrome on Galaxy Note 4
1. replace4 score: 100% *winner* (99.82)
2. replace1 score: 91.04% speed of winner. (90.88)
3. replace3 score: 70.27% speed of winner. (70.15)
4. replace2 score: 38.25% speed of winner. (38.18)
catch (Exception ex) { ... }
WILL catch RuntimeException.
Whatever you put in catch block will be caught as well as the subclasses of it.
In addition to the comprehensive answer already posted sometimes it is useful to be able to access the execution plan programatically to extract information. Example code for this is below.
DECLARE @TraceID INT
EXEC StartCapture @@SPID, @TraceID OUTPUT
EXEC sp_help 'sys.objects' /*<-- Call your stored proc of interest here.*/
EXEC StopCapture @TraceID
StartCapture
DefinitionCREATE PROCEDURE StartCapture
@Spid INT,
@TraceID INT OUTPUT
AS
DECLARE @maxfilesize BIGINT = 5
DECLARE @filepath NVARCHAR(200) = N'C:\trace_' + LEFT(NEWID(),36)
EXEC sp_trace_create @TraceID OUTPUT, 0, @filepath, @maxfilesize, NULL
exec sp_trace_setevent @TraceID, 122, 1, 1
exec sp_trace_setevent @TraceID, 122, 22, 1
exec sp_trace_setevent @TraceID, 122, 34, 1
exec sp_trace_setevent @TraceID, 122, 51, 1
exec sp_trace_setevent @TraceID, 122, 12, 1
-- filter for spid
EXEC sp_trace_setfilter @TraceID, 12, 0, 0, @Spid
-- start the trace
EXEC sp_trace_setstatus @TraceID, 1
StopCapture
DefinitionCREATE PROCEDURE StopCapture
@TraceID INT
AS
WITH XMLNAMESPACES ('http://schemas.microsoft.com/sqlserver/2004/07/showplan' as sql),
CTE
as (SELECT CAST(TextData AS VARCHAR(MAX)) AS TextData,
ObjectID,
ObjectName,
EventSequence,
/*costs accumulate up the tree so the MAX should be the root*/
MAX(EstimatedTotalSubtreeCost) AS EstimatedTotalSubtreeCost
FROM fn_trace_getinfo(@TraceID) fn
CROSS APPLY fn_trace_gettable(CAST(value AS NVARCHAR(200)), 1)
CROSS APPLY (SELECT CAST(TextData AS XML) AS xPlan) x
CROSS APPLY (SELECT T.relop.value('@EstimatedTotalSubtreeCost',
'float') AS EstimatedTotalSubtreeCost
FROM xPlan.nodes('//sql:RelOp') T(relop)) ca
WHERE property = 2
AND TextData IS NOT NULL
AND ObjectName not in ( 'StopCapture', 'fn_trace_getinfo' )
GROUP BY CAST(TextData AS VARCHAR(MAX)),
ObjectID,
ObjectName,
EventSequence)
SELECT ObjectName,
SUM(EstimatedTotalSubtreeCost) AS EstimatedTotalSubtreeCost
FROM CTE
GROUP BY ObjectID,
ObjectName
-- Stop the trace
EXEC sp_trace_setstatus @TraceID, 0
-- Close and delete the trace
EXEC sp_trace_setstatus @TraceID, 2
GO
1) "container" is a class and not an ID 2) .container - set z-index and display: none in your CSS and not inline unless there is a really good reason to do so. Demo@fiddle
$("#button").click(function() {
$(".container").css("opacity", 0.2);
$("#loading-img").css({"display": "block"});
});
CSS:
#loading-img {
background: url(http://web.bogdanteodoru.com/wp-content/uploads/2012/01/bouncy-css3-loading-animation.jpg) center center no-repeat; /* different for testing purposes */
display: none;
height: 100px; /* for testing purposes */
z-index: 12;
}
And a demo with animated image.
You can use this function if you want to add the data into database, with a button. I hope it will help.
// dgvBill is name of DataGridView
string StrQuery;
try
{
using (SqlConnection conn = new SqlConnection(ConnectingString))
{
using (SqlCommand comm = new SqlCommand())
{
comm.Connection = conn;
conn.Open();
for (int i = 0; i < dgvBill.Rows.Count; i++)
{
StrQuery = @"INSERT INTO tblBillDetails (IdBill, productID, quantity, price, total) VALUES ('" + IdBillVar+ "','" + dgvBill.Rows[i].Cells[0].Value + "', '" + dgvBill.Rows[i].Cells[4].Value + "', '" + dgvBill.Rows[i].Cells[3].Value + "', '" + dgvBill.Rows[i].Cells[2].Value + "');";
comm.CommandText = StrQuery;
comm.ExecuteNonQuery();
}
}
}
}
catch (Exception err)
{
MessageBox.Show(err.Message , "Error !");
}
A predicate is a function that returns a true/false (i.e. boolean) value, as opposed to a proposition which is a true/false (i.e. boolean) value. In Java, one cannot have standalone functions, and so one creates a predicate by creating an interface for an object that represents a predicate and then one provides a class that implements that interface. An example of an interface for a predicate might be:
public interface Predicate<ARGTYPE>
{
public boolean evaluate(ARGTYPE arg);
}
And then you might have an implementation such as:
public class Tautology<E> implements Predicate<E>
{
public boolean evaluate(E arg){
return true;
}
}
To get a better conceptual understanding, you might want to read about first-order logic.
Edit
There is a standard Predicate interface (java.util.function.Predicate) defined in the Java API as of Java 8. Prior to Java 8, you may find it convenient to reuse the com.google.common.base.Predicate interface from Guava.
Also, note that as of Java 8, it is much simpler to write predicates by using lambdas. For example, in Java 8 and higher, one can pass p -> true
to a function instead of defining a named Tautology subclass like the above.
Add an else to your case statements so that they default to zero if the test condition is not found. At the moment if the test condition isn't found NULL is being passed to the SUM() function.
Select c.rundate,
sum(case when c.runstatus = 'Succeeded' then 1 else 0 end) as Succeeded,
sum(case when c.runstatus = 'Failed' then 1 else 0 end) as Failed,
sum(case when c.runstatus = 'Cancelled' then 1 else 0 end) as Cancelled,
count(*) as Totalrun from
( Select a.name,case when b.run_status=0 Then 'Failed' when b.run_status=1 Then 'Succeeded'
when b.run_status=2 Then 'Retry' Else 'Cancelled' End as Runstatus,
---cast(run_date as datetime)
cast(substring(convert(varchar(8),run_date),1,4)+'/'+substring(convert(varchar(8),run_date),5,2)+'/' +substring(convert(varchar(8),run_date),7,2) as Datetime) as RunDate
from msdb.dbo.sysjobs as a(nolock) inner join msdb.dbo.sysjobhistory as b(nolock)
on a.job_id=b.job_id
where a.name='AI'
and b.step_id=0) as c
group by
c.rundate
create procedure PSaleCForms
as
begin
declare
@b varchar(9),
@c nvarchar(500),
@q nvarchar(max)
declare @T table(FY nvarchar(9),Qtr int,title nvarchar (max),invoicenumber nvarchar(max),invoicedate datetime,sp decimal 18,2),grandtotal decimal(18,2))
declare @data cursor
set @data= Cursor
forward_only static
for
select x.DBTitle,y.CurrentFinancialYear from [Accounts Manager].dbo.DBManager x inner join [Accounts Manager].dbo.Accounts y on y.DBID=x.DBID where x.cfy=1
open @data
fetch next from @data
into @c,@b
while @@FETCH_STATUS=0
begin
set @q=N'Select '''+@b+''' [fy], case cast(month(i.invoicedate)/3.1 as int) when 0 then 4 else cast(month(i.invoicedate)/3.1 as int) end [Qtr], l.title,i.invoicenumber,i.invoicedate,i.sp,i.grandtotal from ['+@c+'].dbo.invoicemain i inner join ['+@c+'].dbo.ledgermain l on l.ledgerid=i.ledgerid where (sp=0 or stocktype=''x'') and invoicetype=''DS'''
insert into @T exec [master].dbo.sp_executesql @q fetch next from @data into @c,@b end close @data deallocate @data select * from @T return end
If you can modify the HTML: http://jsfiddle.net/8JwhZ/3/
<div class="title">
<span class="name">Cumulative performance</span>
<span class="date">20/02/2011</span>
</div>
.title .date { float:right }
.title .name { float:left }
So here is the controller code.
public IActionResult AddURLTest()
{
return ViewComponent("AddURL");
}
You can load it using JQuery load method.
$(document).ready (function(){
$("#LoadSignIn").click(function(){
$('#UserControl').load("/Home/AddURLTest");
});
});
source code link
find
's optionsThere is actually no exec of /bin/ls
needed;
Find has an option that does just that:
find . -maxdepth 2 -type d -ls
To see only the one level of subdirectories you are interested in, add -mindepth
to the same level as -maxdepth
:
find . -mindepth 2 -maxdepth 2 -type d -ls
When the details that get shown should be different, -printf
can show any detail about a file in custom format;
To show the symbolic permissions and the owner name of the file, use -printf
with %M
and %u
in the format
.
I noticed later you want the full ownership information, which includes
the group. Use %g
in the format for the symbolic name, or %G
for the group id (like also %U
for numeric user id)
find . -mindepth 2 -maxdepth 2 -type d -printf '%M %u %g %p\n'
This should give you just the details you need, for just the right files.
I will give an example that shows actually different values for user and group:
$ sudo find /tmp -mindepth 2 -maxdepth 2 -type d -printf '%M %u %g %p\n'
drwx------ www-data www-data /tmp/user/33
drwx------ octopussy root /tmp/user/126
drwx------ root root /tmp/user/0
drwx------ siegel root /tmp/user/1000
drwxrwxrwt root root /tmp/systemd-[...].service-HRUQmm/tmp
(Edited for readability: indented, shortened last line)
Although the execution time is mostly irrelevant for this kind of command, increase in performance is large enough here to make it worth pointing it out:
Not only do we save creating a new process for each name - a huge task -
the information does not even need to be read, as find
already knows it.
Warning: Don't forget to clear the user data again. Otherwise this key will be pushed on every instance start. Step-by-step instructions.
#cloud-config
bootcmd:
- echo 'ssh-rsa AAAAB3Nz...' > /root/.ssh/authorized_keys
You can use this code(Recommended)
MemoryStream objMS = new MemoryStream();
DataTable oDT = new DataTable();//Your DataTable which you want to convert
oDT.WriteXml(objMS);
objMS.Position = 0;
XPathDocument result = new XPathDocument(objMS);
This is another way but first ex. is recommended
StringWriter objSW = new StringWriter();
DataTable oDt = new DataTable();//Your DataTable which you want to convert
oDt.WriteXml(objSW);
string result = objSW.ToString();
Since Qt 5.8, we now have QDateTime::currentSecsSinceEpoch()
to deliver the seconds directly, a.k.a. as real Unix timestamp. So, no need to divide the result by 1000 to get seconds anymore.
Credits: also posted as comment to this answer. However, I think it is easier to find if it is a separate answer.
The answers here were somewhat incomplete. And I had to compile information from other sources to actually acquire the plugin list.
The Jenkins CLI will allow us to interact with our Jenkins server from the command line. We can get it with a simple curl call.
curl 'localhost:8080/jnlpJars/jenkins-cli.jar' > jenkins-cli.jar
Save the following as plugins.groovy
.
def plugins = jenkins.model.Jenkins.instance.getPluginManager().getPlugins()
plugins.each {println "${it.getShortName()}: ${it.getVersion()}"}
Call the Jenkins server (localhost:8080
here) with your login username and password while referencing the Groovy script:
java -jar jenkins-cli.jar -s http://localhost:8080 groovy --username "admin" --password "admin" = < plugins.groovy > plugins.txt
The output to plugins.txt looks like this:
ace-editor: 1.1
ant: 1.5
antisamy-markup-formatter: 1.5
authentication-tokens: 1.3
blueocean-autofavorite: 1.0.0
blueocean-commons: 1.1.4
blueocean-config: 1.1.4
blueocean-dashboard: 1.1.4
blueocean-display-url: 2.0
blueocean-events: 1.1.4
blueocean-git-pipeline: 1.1.4
blueocean-github-pipeline: 1.1.4
blueocean-i18n: 1.1.4
blueocean-jwt: 1.1.4
blueocean-personalization: 1.1.4
blueocean-pipeline-api-impl: 1.1.4
blueocean-pipeline-editor: 0.2.0
blueocean-pipeline-scm-api: 1.1.4
blueocean-rest-impl: 1.1.4
Answers above elucidated many things, but I think it is useful to make a conceptual distinction.
What if you take a perfectly on-focus picture of a blurred image?
The blurring detection problem is only well posed when you have a reference. If you need to design, e.g., an auto-focus system, you compare a sequence of images taken with different degrees of blurring, or smoothing, and you try to find the point of minimum blurring within this set. I other words you need to cross reference the various images using one of the techniques illustrated above (basically--with various possible levels of refinement in the approach--looking for the one image with the highest high-frequency content).
off topic but here is the formula for middle value.. just in case someone is looking for it
Math.Min(Math.Min(Math.Max(x,y), Math.Max(y,z)), Math.Max(x,z));
Use the command dir
to list all the directories and files in a directory; ls
is a unix command.
From the Errata:
ModelState.AddRuleViolations(dinner.GetRuleViolations());
Should be:
ModelState.AddModelErrors(dinner.GetRuleViolations());
I ran into similar situation where I had to merge Date and Time fields to DateTime field. None of the above mentioned solution work, specially adding two fields as the data type for addition of these 2 fields is not same.
I created below solution, where I added hour and then minute part to the date. This worked beautifully for me. Please check it out and do let me know if you get into any issues.
;with tbl as ( select StatusTime = '12/30/1899 5:17:00 PM', StatusDate = '7/24/2019 12:00:00 AM' ) select DATEADD(MI, DATEPART(MINUTE,CAST(tbl.StatusTime AS TIME)),DATEADD(HH, DATEPART(HOUR,CAST(tbl.StatusTime AS TIME)), CAST(tbl.StatusDate as DATETIME))) from tbl
Result: 2019-07-24 17:17:00.000
Both are logical AND operations. The && though, is a "short-circuit" operator. From the MATLAB docs:
They are short-circuit operators in that they evaluate their second operand only when the result is not fully determined by the first operand.
See more here.
You can add a class declaration to the submit button of a form by doing the following:
<%= f.submit class: 'btn btn-default' %>
<-- Note: there is no comma!
If you are altering a _form.html.erb partial of a scaffold and you want to keep
the dynamic change of the button name between controller actions, DO NOT specify a name 'name'
.
Without specifying a name and depending on the action the form is rendered the button will get the .class = "btn btn-default"
(Bootstrap class)(or whatever .class
you specify) with the following names:
Update model_name
Create model_name
(where model_name the name of the scaffold's model)
You can only have one primary key, but you can have multiple columns in your primary key.
You can also have Unique Indexes on your table, which will work a bit like a primary key in that they will enforce unique values, and will speed up querying of those values.
Overall:You persist entity that is violating database rules like as saving entity that has varchar field over 250 chars ,something like that.
In my case it was a squishy problem with TestEntityManager ,because it use HSQL database /in memory database/ and it persist the user but when you try to find it ,it drops the same exception :/
@RunWith(SpringRunner.class)
@ContextConfiguration(classes= Application.class)
@DataJpaTest
@ActiveProfiles("test")
public class UserServicesTests {
@Autowired
private TestEntityManager testEntityManager;
@Autowired
private UserRepository userRepository;
@Test
public void oops() {
User user = new User();
user.setUsername("Toshko");
//EMAIL IS REQUIRED:
//user.setEmail("OPS");
this.testEntityManager.persist(user);
//HERE COMES TE EXCEPTION BECAUSE THE EMAIL FIELD IN TE DATABASE IS REQUIRED :
this.userRepository.findUserByUsername("Toshko");
System.out.println();
}
}
You can use Culture to get month name for your country like:
System.Globalization.CultureInfo culture = new System.Globalization.CultureInfo("ar-EG");
string FormatDate = DateTime.Now.ToString("dddd., MMM dd yyyy, hh:MM tt", culture);
According to the tkinterbook the code to clear a text element should be:
text.delete(1.0,END)
This worked for me. source
It's different from clearing an entry element, which is done like this:
entry.delete(0,END) #note the 0 instead of 1.0
I have tried and it successfully, before pulling, let commit all file that you have not committed, then you will not receive that messages from AS.
//---- remove first and last char of str
str = str.substring(1,((keyw.length)-1));
//---- remove only first char
str = str.substring(1,(keyw.length));
//---- remove only last char
str = str.substring(0,(keyw.length));
I added "Microsoft ASP.NET Razor" using Manage NuGet Packages.
With Add References, for some reason, I only had System.Web.Helpers 1.0.0 and 2.0.0... but not 3.0.0.
Another option, that worked form me was to delete the references to System.Web.Mvc and System.Web.Http... then re-add them browing to the package locations in the csproj file (you can most easily edit the project with a text editor):
<Reference Include="System.Web.Http">
<HintPath>..\packages\Microsoft.AspNet.WebApi.Core.5.2.3\lib\net45\System.Web.Http.dll</HintPath>
<Reference Include="System.Web.Mvc, Version=5.2.3.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.AspNet.Mvc.5.2.3\lib\net45\System.Web.Mvc.dll</HintPath>
Try using a ConcurrentHashMap
instead of a plain HashMap
I had a similar issue and solved after running these instructions!
npm install npm -g
npm install --save-dev @angular/cli@latest
npm install
npm start
Well, I just did
brew install mongodb
and followed the instructions that were output to the STDOUT
after it finished installing, and that seems to have worked just fine. I guess it kinda works just like make install
and overwrites (upgrades) a previous install.
Try this expression:
typeof(variable) != "undefined" && variable !== null
This will be true if the variable is defined and not null, which is the equivalent of how PHP's isset works.
You can use it like this:
if(typeof(variable) != "undefined" && variable !== null) {
bla();
}
I just found Scandinavian Keyboard as a fine solution to this problem. It do also have English and German keyboard, but neither Dutch nor Spanish - but I guess they could be added. And I guess there is other alternatives out there.
Java 8 supports default methods in interfaces. And in JDK 8 a lot of old interfaces now have new default methods. For example, now in CharSequence we have chars and codePoints methods.
If source level of your project is lower than 1.8, then compiler doesn't allow you to use default methods in interfaces. So it cannot compile classes that directly on indirectly depend on this interfaces.
If I get your problem right, then you have two solutions. First solution is to rollback to JDK 7, then you will use old CharSequence interface without default methods. Second solution is to set source level of your project to 1.8, then your compiler will not complain about default methods in interfaces.
isValidJsonString - check for valid json string
JSON data types - string, number, object (JSON object), array, boolean, null (https://www.json.org/json-en.html)
falsy values in javascript - false, 0, -0, 0n, ", null, undefined, NaN - (https://developer.mozilla.org/en-US/docs/Glossary/Falsy)
JSON.parse
works well for number , boolean, null and valid json String won't raise any error. please refer example below
break when you parse undefined , object, array etc
function isValidJsonString(jsonString){
if(!(jsonString && typeof jsonString === "string")){
return false;
}
try{
JSON.parse(jsonString);
return true;
}catch(error){
return false;
}
}
Convert the array into a hash. Then look for the key.
array = ['a', 'b', 'c']
hash = Hash[array.map.with_index.to_a] # => {"a"=>0, "b"=>1, "c"=>2}
hash['b'] # => 1
This message digital envelope routines: EVP_DecryptFInal_ex: bad decrypt
can also occur when you encrypt and decrypt with an incompatible versions of openssl.
The issue I was having was that I was encrypting on Windows which had version 1.1.0 and then decrypting on a generic Linux system which had 1.0.2g.
It is not a very helpful error message!
A possible solution from @AndrewSavinykh that worked for many (see the comments):
Default digest has changed between those versions from md5 to sha256. One can specify the default digest on the command line as
-md sha256
or-md md5
respectively
To call get with multiple parameter in web api core
[ApiController]
[Route("[controller]")]
public class testController : Controller
{
[HttpGet]
[Route("testaction/{id:int}/{startdate}/{enddate}")]
public IEnumerable<classname> test_action(int id, string startdate, string enddate)
{
return List_classobject;
}
}
In web browser
https://localhost:44338/test/testaction/3/2010-09-30/2012-05-01
There are a few different ways of doing this. I prefer using apply
, since it's easily extendable:
##Generate some data
dd = data.frame(a = 1:4, b= 1:0, c=0:3)
##Go through each row and determine if a value is zero
row_sub = apply(dd, 1, function(row) all(row !=0 ))
##Subset as usual
dd[row_sub,]
We copy the JRE's truststore and add our custom certificates to that truststore, then tell the application to use the custom truststore with a system property. This way we leave the default JRE truststore alone.
The downside is that when you update the JRE you don't get its new truststore automatically merged with your custom one.
You could maybe handle this scenario by having an installer or startup routine that verifies the truststore/jdk and checks for a mismatch or automatically updates the truststore. I don't know what happens if you update the truststore while the application is running.
This solution isn't 100% elegant or foolproof but it's simple, works, and requires no code.
As per 'dtb' you need to use HttpStatusCode, but following 'zeldi' you need to be extra careful with code responses >= 400.
This has worked for me:
HttpWebResponse response = null;
HttpStatusCode statusCode;
try
{
response = (HttpWebResponse)request.GetResponse();
}
catch (WebException we)
{
response = (HttpWebResponse)we.Response;
}
statusCode = response.StatusCode;
Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
sResponse = reader.ReadToEnd();
Console.WriteLine(sResponse);
Console.WriteLine("Response Code: " + (int)statusCode + " - " + statusCode.ToString());
def main():
result = int(input("Enter a whole, positive, number to be converted to hexadecimal: "))
hexadecimal = ""
while result != 0:
remainder = changeDigit(result % 16)
hexadecimal = str(remainder) + hexadecimal
result = int(result / 16)
print(hexadecimal)
def changeDigit(digit):
decimal = [10 , 11 , 12 , 13 , 14 , 15 ]
hexadecimal = ["A", "B", "C", "D", "E", "F"]
for counter in range(7):
if digit == decimal[counter - 1]:
digit = hexadecimal[counter - 1]
return digit
main()
This is the densest I could make for converting decimal to hexadecimal. NOTE: This is in Python version 3.5.1
Works for me >
the environment:
localhost
Windows 10
PHP 5.6.31
MYSQL 8
set:
default-character-set=utf8
on:
c:\programdata\mysql\mysql server 8.0\my.ini
C:\Program Files\MySQL\MySQL Server 5.5\my.ini
Tools that helps:
C:\Program Files\MySQL\MySQL Server 8.0\bin>mysql -u root -p
mysql> show variables like 'char%';
mysql> show variables like 'collation%';
\m/
Simply
SELECT @@system_time_zone;
Returns PST
(or whatever is relevant to your system).
If you're trying to determine the session timezone you can use this query:
SELECT IF(@@session.time_zone = 'SYSTEM', @@system_time_zone, @@session.time_zone);
Which will return the session timezone if it differs from the system timezone.
@Egidius, when creating an XMLHttpRequest, you should use
var xhr = new XMLHttpRequest({mozSystem: true});
What is mozSystem?
mozSystem Boolean: Setting this flag to true allows making cross-site connections without requiring the server to opt-in using CORS. Requires setting mozAnon: true, i.e. this can't be combined with sending cookies or other user credentials. This only works in privileged (reviewed) apps; it does not work on arbitrary webpages loaded in Firefox.
Changes to your Manifest
On your manifest, do not forget to include this line on your permissions:
"permissions": {
"systemXHR" : {},
}
<import resource="classpath:spring-config.xml" />
Reference:
classpath:
part is explained)Short and sweet. This was my solution when doing codeAcademy course. Prints a string in rev order.
def reverse(text):
string = ""
for i in range(len(text)-1,-1,-1):
string += text[i]
return string
First off, this has nothing to do with php. This is a unix permission issue. You need to login as a superuser ( sudo/su ) and type your password, then try that command.
$ su
(type password )
\# your command
$ sudo command
$ (type password)
It might also help if you actually specified the operating system you use.
The response from Marco is the BEST solution. I needed to control my error handling, and I mean really CONTROL it. Of course, I have extended the solution a little and created a full error management system that manages everything. I have also read about this solution in other blogs and it seems very acceptable by most of the advanced developers.
Here is the final code that I am using:
protected void Application_EndRequest()
{
if (Context.Response.StatusCode == 404)
{
var exception = Server.GetLastError();
var httpException = exception as HttpException;
Response.Clear();
Server.ClearError();
var routeData = new RouteData();
routeData.Values["controller"] = "ErrorManager";
routeData.Values["action"] = "Fire404Error";
routeData.Values["exception"] = exception;
Response.StatusCode = 500;
if (httpException != null)
{
Response.StatusCode = httpException.GetHttpCode();
switch (Response.StatusCode)
{
case 404:
routeData.Values["action"] = "Fire404Error";
break;
}
}
// Avoid IIS7 getting in the middle
Response.TrySkipIisCustomErrors = true;
IController errormanagerController = new ErrorManagerController();
HttpContextWrapper wrapper = new HttpContextWrapper(Context);
var rc = new RequestContext(wrapper, routeData);
errormanagerController.Execute(rc);
}
}
and inside my ErrorManagerController :
public void Fire404Error(HttpException exception)
{
//you can place any other error handling code here
throw new PageNotFoundException("page or resource");
}
Now, in my Action, I am throwing a Custom Exception that I have created. And my Controller is inheriting from a custom Controller Based class that I have created. The Custom Base Controller was created to override error handling. Here is my custom Base Controller class:
public class MyBasePageController : Controller
{
protected override void OnException(ExceptionContext filterContext)
{
filterContext.GetType();
filterContext.ExceptionHandled = true;
this.View("ErrorManager", filterContext).ExecuteResult(this.ControllerContext);
base.OnException(filterContext);
}
}
The "ErrorManager" in the above code is just a view that is using a Model based on ExceptionContext
My solution works perfectly and I am able to handle ANY error on my website and display different messages based on ANY exception type.
Below steps fixed this issue for me, I was trying to create setup with cython extension.
For some reason distutils expects the vcvarsall.bat file to be within VC dir, but VC++ for python tools has it in the root of 9.0 To fix this, remove "VC" from the path.join (roughly around line 247)
#productdir = os.path.join(toolsdir, os.pardir, os.pardir, "VC")
productdir = os.path.join(toolsdir, os.pardir, os.pardir)
The above steps fixed the issue for me.
You can also follow the "official" way. Run "sdkmanager --licenses" within tools/bin folder of Android SDK installation and accept all licenses. Done!
c:\android-sdk\tools\bin>sdkmanager --licenses
For macOS or Linux it's the same command.
I had just the same trouble with fedora 26 and LVM partitions, it seems I forgot check something during the installation, So, my 15G root directory has been increased to 227G like I needed.
I posted the steps I followed here:
resize2fs: Bad magic number in super-block while trying to open
0) #df -h
Filesystem Size Used Avail Use% Mounted on
devtmpfs 1.9G 0 1.9G 0% /dev
tmpfs 1.9G 0 1.9G 0% /dev/shm
tmpfs 1.9G 824K 1.9G 1% /run
tmpfs 1.9G 0 1.9G 0% /sys/fs/cgroup
/dev/mapper/fedora-root 15G 2.1G 13G 14% /
tmpfs 1.9G 0 1.9G 0% /tmp
/dev/md126p1 976M 119M 790M 14% /boot
tmpfs 388M 0 388M 0% /run/user/0
1) # vgs
VG #PV #LV #SN Attr VSize VFree
fedora 1 2 0 wz--n- 231.88g 212.96g
2) # vgdisplay
--- Volume group ---
VG Name fedora
System ID
Format lvm2
Metadata Areas 1
Metadata Sequence No 3
VG Access read/write
VG Status resizable
MAX LV 0
Cur LV 2
Open LV 2
Max PV 0
Cur PV 1
Act PV 1
VG Size 231.88 GiB
PE Size 4.00 MiB
Total PE 59361
Alloc PE / Size 4844 / 18.92 GiB
Free PE / Size 54517 / 212.96 GiB
VG UUID 9htamV-DveQ-Jiht-Yfth-OZp7-XUDC-tWh5Lv
3) # lvextend -l +100%FREE /dev/mapper/fedora-root
Size of logical volume fedora/root changed from 15.00 GiB (3840 extents) to 227.96 GiB (58357 extents).
Logical volume fedora/root successfully resized.
4) #lvdisplay
5) #fd -h
6) # xfs_growfs /dev/mapper/fedora-root
meta-data=/dev/mapper/fedora-root isize=512 agcount=4, agsize=983040 blks
= sectsz=512 attr=2, projid32bit=1
= crc=1 finobt=1 spinodes=0 rmapbt=0
= reflink=0
data = bsize=4096 blocks=3932160, imaxpct=25
= sunit=0 swidth=0 blks
naming =version 2 bsize=4096 ascii-ci=0 ftype=1
log =internal bsize=4096 blocks=2560, version=2
= sectsz=512 sunit=0 blks, lazy-count=1
realtime =none extsz=4096 blocks=0, rtextents=0
data blocks changed from 3932160 to 59757568
7) #df -h
Filesystem Size Used Avail Use% Mounted on
devtmpfs 1.9G 0 1.9G 0% /dev
tmpfs 1.9G 0 1.9G 0% /dev/shm
tmpfs 1.9G 828K 1.9G 1% /run
tmpfs 1.9G 0 1.9G 0% /sys/fs/cgroup
/dev/mapper/fedora-root 228G 2.3G 226G 2% /
tmpfs 1.9G 0 1.9G 0% /tmp
/dev/md126p1 976M 119M 790M 14% /boot
tmpfs 388M 0 388M 0% /run/user/0
Best regards,
If there is no authentication enabled (username/password) and still unable to connect. Just use localhost and default port. Click Test and Save, if test connection is successful.
Regards Jagdish
cmd
Tunnel all your internet traffic through a socks proxy:
netsh winhttp set proxy proxy-server="socks=localhost:9090" bypass-list="localhost"
View the current proxy settings:
netsh winhttp show proxy
Clear all proxy settings:
netsh winhttp reset proxy
i hope this code is work well,try this.
add css file.
.scrollbar {
height: auto;
max-height: 180px;
overflow-x: hidden;
}
HTML code:
<div class="col-sm-2 scrollable-menu" role="menu">
<div>
<ul>
<li><a class="active" href="#home">Tutorials</a></li>
<li><a href="#news">News</a></li>
<li><a href="#contact">Contact</a></li>
<li><a href="#about">About</a></li>
<li><a href="#news">News</a></li>
<li><a href="#contact">Contact</a></li>
<li><a href="#about">About</a></li>
<li><a href="#news">News</a></li>
<li><a href="#contact">Contact</a></li>
<li><a href="#about">About</a></li>
<li><a href="#news">News</a></li>
<li><a href="#contact">Contact</a></li>
<li><a href="#about">About</a></li>
<li><a href="#news">News</a></li>
<li><a href="#contact">Contact</a></li>
<li><a href="#about">About</a></li>
</ul>
</div>
</div>
For handling line-breaks specifically, I tried a number of options before finally settling for this:
{% set list1 = data.split('\n') %}
{% for item in list1 %}
{{ item }}
{% if not loop.last %}
<br/>
{% endif %}
{% endfor %}
The nice thing about this approach is that it's compatible with the auto-escaping, leaving everything nice and safe. It can also be combined with filters, like urlize.
Of course it's similar to Helge's answer, but doesn't need a macro (relying instead on Jinja's built-in split
function) and also doesn't add an unnecesssary <br/>
after the last item.
try this:
import time
import os
n = 0
for x in range(10): #enter your value here
print(n)
time.sleep(1) #to wait a second
os.system('cls') #to clear previous number
#use ('clear') if you are using linux or mac!
n = n + 1
If you are interested, RubyLearning offers a course on FXRuby and Shoes. Actually, the Shoes course is being conducted currently.
Probably the easiest is Shoes. As an assistant teacher at RubyLearning, I hope that we will have better courses for learners.
Some people got stuck in installing FXRuby. But Shoes has an installer for any platforms (Windows, Mac and Linux).
When I just run this as a page
<?php
echo '<script language="javascript">';
echo 'alert("message successfully sent")';
echo '</script>';
exit;
it works fine.
What version of PHP are you running?
Could you try echoing something else after: $testObject->split_for_sms($Chat);
Maybe it doesn't get to that part of the code? You could also try these with the other function calls to check where your program stops/is getting to.
Hope you get a bit further with this.
Here's a better option:
git remote set-head -a origin
From the documentation:
With -a, the remote is queried to determine its HEAD, then $GIT_DIR/remotes//HEAD is set to the same branch. e.g., if the remote HEAD is pointed at next, "git remote set-head origin -a" will set $GIT_DIR/refs/remotes/origin/HEAD to refs/remotes/origin/next. This will only work if refs/remotes/origin/next already exists; if not it must be fetched first.
This has actually been around quite a while (since v1.6.3); not sure how I missed it!
Turns out for me that SET NOCOUNT ON
was set in the stored procedure script (by default on SQL Server Management Studio) and SqlCommand.ExecuteNonQuery();
always returned -1.
I just set it off: SET NOCOUNT OFF
without needing to use @@ROWCOUNT
.
More details found here : SqlCommand.ExecuteNonQuery() returns -1 when doing Insert / Update / Delete
I just put --password
flag into my command and after hitting Enter it asked me for password, which I supplied.
In Java 7 you have the new Paths api. The modern and cleanest solution is:
Paths.get("C:/aaa/bbb/ccc/ddd/test.java").getParent().getFileName();
Result would be:
C:/aaa/bbb/ccc/ddd
The questioner needs to learn the difference between an empty value provided and null.
Others have posted the right basic answer: A provided value, including a null, is something and therefore it's used. Default ONLY provides a value when none is provided. But the real problem here is lack of understanding of the value of null.
.
Try negation operator !
before $(this)
:
if (!$(this).parent().next().is('ul')){
To properly display one div on top of another, we need to use the property position
as follows:
position: relative
position: absolute
I found a good example here:
.dvContainer {_x000D_
position: relative;_x000D_
display: inline-block;_x000D_
width: 300px;_x000D_
height: 200px;_x000D_
background-color: #ccc;_x000D_
}_x000D_
_x000D_
.dvInsideTL {_x000D_
position: absolute;_x000D_
left: 0;_x000D_
top: 0;_x000D_
width: 150px;_x000D_
height: 100px;_x000D_
background-color: #ff751a;_x000D_
opacity: 0.5;_x000D_
}
_x000D_
<div class="dvContainer">_x000D_
<table style="width:100%;height:100%;">_x000D_
<tr>_x000D_
<td style="width:50%;text-align:center">Top Left</td>_x000D_
<td style="width:50%;text-align:center">Top Right</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td style="width:50%;text-align:center">Bottom Left</td>_x000D_
<td style="width:50%;text-align:center">Bottom Right</td>_x000D_
</tr>_x000D_
</table>_x000D_
<div class="dvInsideTL">_x000D_
</div>_x000D_
</div>
_x000D_
I hope this helps,
Zag.
Chrome is preflighting the request to look for CORS headers. If the request is acceptable, it will then send the real request. If you're doing this cross-domain, you will simply have to deal with it or else find a way to make the request non-cross-domain. This is why the jQuery bug was closed as won't-fix. This is by design.
Unlike simple requests (discussed above), "preflighted" requests first send an HTTP request by the OPTIONS method to the resource on the other domain, in order to determine whether the actual request is safe to send. Cross-site requests are preflighted like this since they may have implications to user data. In particular, a request is preflighted if:
- It uses methods other than GET, HEAD or POST. Also, if POST is used to send request data with a Content-Type other than application/x-www-form-urlencoded, multipart/form-data, or text/plain, e.g. if the POST request sends an XML payload to the server using application/xml or text/xml, then the request is preflighted.
- It sets custom headers in the request (e.g. the request uses a header such as X-PINGOTHER)
file = open("filename.txt", newline='')
for row in self.data:
print(row)
Save data to a variable(file
), so you need a with
.
Maybe the simplest way is:
public MyFragment getVisibleFragment(){
FragmentManager fragmentManager = MainActivity.this.getSupportFragmentManager();
List<Fragment> fragments = fragmentManager.getFragments();
for(Fragment fragment : fragments){
if(fragment != null && fragment.getUserVisibleHint())
return (MyFragment)fragment;
}
return null;
}
It worked for me
If you have the option pre-existing in a fixed-with <select>
, and you don't want to change the width programmatically, you could be out of luck unless you get a little creative.
title
attribute to each option. This is non-standard HTML (if you care for this minor infraction here), but IE (and Firefox as well) will display the entire text in a mouse popup on mouse hover.If you are adding a long option later through JavaScript, look here: How to update HTML “select” box dynamically in IE
You cannot push anything that hasn't been committed yet. The order of operations is:
git add
- this stages your changes for committinggit commit
- this commits your staged changes locallygit push
- this pushes your committed changes to a remoteIf you push without committing, nothing gets pushed. If you commit without adding, nothing gets committed. If you add without committing, nothing at all happens, git merely remembers that the changes you added should be considered for the following commit.
The message you're seeing (your branch is ahead by 1 commit) means that your local repository has one commit that hasn't been pushed yet.
In other words: add
and commit
are local operations, push
, pull
and fetch
are operations that interact with a remote.
Since there seems to be an official source control workflow in place where you work, you should ask internally how this should be handled.
I believe that you will have to drop the foreign key constraints first. Then update all of the appropriate tables and remap them as they were.
ALTER TABLE [dbo.Details_tbl] DROP CONSTRAINT [FK_Details_tbl_User_tbl];
-- Perform more appropriate alters
ALTER TABLE [dbo.Details_tbl] ADD FOREIGN KEY (FK_Details_tbl_User_tbl)
REFERENCES User_tbl(appId);
-- Perform all appropriate alters to bring the key constraints back
However, unless memory is a really big issue, I would keep the identity as an INT. Unless you are 100% positive that your keys will never grow past the TINYINT restraints. Just a word of caution :)
SELECT @variable1 = col1, @variable2 = col2
FROM table1
I found these lines in one of the .sql files
"To connect with a manager that does not use port 3306
, you must specify the port number:
$mysqli = new mysqli('127.0.0.0.1','user','password','database','3307');
or, in procedural terms:
$mysqli = mysqli_connect('127.0.0.0.1','user','password','database','3307');"
It resolved the error for me . So i will suggest must use port number while making connection to server to resolve the error 1049
(unknown database).
This code work as well, instead eval the html i'm going to append the script to the head
function RunJS(objID) {
//alert(http_request.responseText);
var c="";
var ob = document.getElementById(objID).getElementsByTagName("script");
for (var i=0; i < ob.length - 1; i++) {
if (ob[i + 1].text != null)
c+=ob[i + 1].text;
}
var s = document.createElement("script");
s.type = "text/javascript";
s.text = c;
document.getElementsByTagName("head")[0].appendChild(s);
}
Yet another option is to use QTextStream and the <<
operator in much the same way as you would use cout
in C++:
QPoint point(5,1);
QString str;
QTextStream(&str) << "Mouse click: (" << point.x() << ", " << point.y() << ").";
// OUTPUT:
// Mouse click: (5, 1).
Because operator <<()
has been overloaded, you can use it for multiple types, not just int
. QString::arg()
is overloaded, for example arg(int a1, int a2)
, but there is no arg(int a1, QString a2)
, so using QTextStream()
and operator <<
is convenient when formatting longer strings with mixed types.
Caution: You might be tempted to use the sprintf()
facility to mimic C style printf()
statements, but it is recommended to use QTextStream
or arg()
because they support Unicode string
s.
Look here http://docs.oracle.com/javase/6/docs/api/java/awt/Font.html#deriveFont%28float%29
JComponent has a setFont() method. You will control the font there, not on the String.
Such as
JButton b = new JButton();
b.setFont(b.getFont().deriveFont(18.0f));
/* Teaser image swap function */
$('img.swap').hover(function () {
this.src = '/images/signup_big_hover.png';
}, function () {
this.src = '/images/signup_big.png';
});
public class UserCustomAdapter extends ArrayAdapter<User> {
Context context;
int layoutResourceId;
ArrayList<User> data = new ArrayList<User>();
public UserCustomAdapter(Context context, int layoutResourceId,
ArrayList<User> data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
UserHolder holder = null;
if (row == null) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new UserHolder();
holder.textName = (TextView) row.findViewById(R.id.textView1);
holder.textAddress = (TextView) row.findViewById(R.id.textView2);
holder.textLocation = (TextView) row.findViewById(R.id.textView3);
holder.btnEdit = (Button) row.findViewById(R.id.button1);
holder.btnDelete = (Button) row.findViewById(R.id.button2);
row.setTag(holder);
} else {
holder = (UserHolder) row.getTag();
}
User user = data.get(position);
holder.textName.setText(user.getName());
holder.textAddress.setText(user.getAddress());
holder.textLocation.setText(user.getLocation());
holder.btnEdit.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Log.i("Edit Button Clicked", "**********");
Toast.makeText(context, "Edit button Clicked",
Toast.LENGTH_LONG).show();
}
});
holder.btnDelete.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Log.i("Delete Button Clicked", "**********");
Toast.makeText(context, "Delete button Clicked",
Toast.LENGTH_LONG).show();
}
});
return row;
}
static class UserHolder {
TextView textName;
TextView textAddress;
TextView textLocation;
Button btnEdit;
Button btnDelete;
}
}
Hey Please have a look here-
I have same answer here on my blog ..
Have you already looked at adding a check constraint
on that column which would restrict values? Something like:
CREATE TABLE SomeTable
(
Id int NOT NULL,
Frequency varchar(200),
CONSTRAINT chk_Frequency CHECK (Frequency IN ('Daily', 'Weekly', 'Monthly', 'Yearly'))
)
To select by class
, you can do this:
$("input.className:checkbox:not(:checked)")
I had the problem with Tomcat running on Ubuntu. The issue was selinux was enabled and for some reason it would not let Eclipse connect to the debugging port. Disabling selinux or putting it in permissive mode solved the issue for me.
If you are using AWS Lambda with SprintBoot, then you must declare the following under environment variables:
key: JAVA_TOOL_OPTIONS & value: -Dspring.profiles.active=dev
Detecting mobile devices
Related answer: https://stackoverflow.com/a/13805337/1306809
There's no single approach that's truly foolproof. The best bet is to mix and match a variety of tricks as needed, to increase the chances of successfully detecting a wider range of handheld devices. See the link above for a few different options.
You could always check out JMF (Java Media Framework). It is pretty old and abandoned, but it works and I've used it for apps before. Looks like it handles what you're asking for.
private void Registration_Load(object sender, EventArgs e)
{
//hiding data grid view coloumn
datagridview1.AutoGenerateColumns = true;
datagridview1.DataSource =dataSet;
datagridview1.DataMember = "users"; // users is table name
datagridview1.Columns[0].Visible = false;//hiding 1st coloumn coloumn
datagridview1.Columns[2].Visible = false; hiding 2nd coloumn
datagridview1.Columns[3].Visible = false; hiding 3rd coloumn
//end of hiding datagrid view coloumns
}
}
Into phpmyadmin database's create that table, there miskta on name of that table it may be pma_table_uiprefs
and not pma__table_uiprefs
CREATE TABLE IF NOT EXISTS
pma_table_uiprefs
(username
varchar(64) NOT NULL,db_name
varchar(64) NOT NULL,table_name
varchar(64) NOT NULL,prefs
text NOT NULL,last_update
timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, PRIMARY KEY (username
,db_name
,table_name
) ) COMMENT='Tables'' UI preferences' DEFAULT CHARACTER SET utf8 COLLATE utf8_bin;
Conditional statements are used to perform different actions based on different conditions.
Use if
to specify a block of code to be executed, if a specified condition is true
Use else
to specify a block of code to be executed, if the same condition is false
Use else if
to specify a new condition to test, if the first condition is false
For swift 3 purposes
theImageView.image = theImageView.image!.withRenderingMode(.alwaysTemplate)
theImageView.tintColor = UIColor.red
$('.navbar-toggle').trigger('click');
You can get the first column as a Series by following code:
x[x.columns[0]]
You should add mode history to your router like the below
export default new Router({
mode: 'history',
routes: [
{
...
}
]
})
Thanks I have added below snippet in POM.xml file and Mp problem resolved and create fat jar file that include all dependent jars.
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
<configuration>
<descriptorRefs>
<descriptorRef>dependencies</descriptorRef>
</descriptorRefs>
</configuration>
</plugin>
</plugins>
For better understanding why wait() and notify() method belongs to Object class, I'll give you a real life example: Suppose a gas station has a single toilet, the key for which is kept at the service desk. The toilet is a shared resource for passing motorists. To use this shared resource the prospective user must acquire a key to the lock on the toilet. The user goes to the service desk and acquires the key, opens the door, locks it from the inside and uses the facilities.
Meanwhile, if a second prospective user arrives at the gas station he finds the toilet locked and therefore unavailable to him. He goes to the service desk but the key is not there because it is in the hands of the current user. When the current user finishes, he unlocks the door and returns the key to the service desk. He does not bother about waiting customers. The service desk gives the key to the waiting customer. If more than one prospective user turns up while the toilet is locked, they must form a queue waiting for the key to the lock. Each thread has no idea who is in the toilet.
Obviously in applying this analogy to Java, a Java thread is a user and the toilet is a block of code which the thread wishes to execute. Java provides a way to lock the code for a thread which is currently executing it using the synchronized keyword, and making other threads that wish to use it wait until the first thread is finished. These other threads are placed in the waiting state. Java is NOT AS FAIR as the service station because there is no queue for waiting threads. Any one of the waiting threads may get the monitor next, regardless of the order they asked for it. The only guarantee is that all threads will get to use the monitored code sooner or later.
Finally the answer to your question: the lock could be the key object or the service desk. None of which is a Thread.
However, these are the objects that currently decide whether the toilet is locked or open. These are the objects that are in a position to notify that the bathroom is open (“notify”) or ask people to wait when it is locked wait.
Note:
1) $.browser appears to be dropped in jQuery 1.9+ (as noted by Mandeep Jain). It is recommended to use .support instead.
2) $.browser.version can return "7" in IE >7 when the browser is in "compatibility" mode.
3) As of IE 10, conditional comments will no longer work.
4) jQuery 2.0+ will drop support for IE 6/7/8
5) document.documentMode appears to be defined only in Internet Explorer 8+ browsers. The value returned will tell you in what "compatibility" mode Internet Explorer is running. Still not a good solution though.
I tried numerous .support() options, but it appears that when an IE browser (9+) is in compatibility mode, it will simply behave like IE 7 ... :(
So far I only found this to work (kind-a):
(if documentMode is not defined and htmlSerialize and opacity are not supported, then you're very likely looking at IE <8 ...)
if(!document.documentMode && !$.support.htmlSerialize && !$.support.opacity)
{
// IE 6/7 code
}
It's built in from Sublime Editor 2 at least. Just press the following and it balances the HTML-tag
Shortcut (Mac): Shift + Command + A
Shortcut (Windows): Control + Alt + A
According to VBA help on SET statement it sets a reference to an object.so if you change a property the actual object will also changes.
Dim newObj as Object
Set var1=Object1(same type as Object)
Set var2=Object1(same type as Object)
Set var3=Object1(same type as Object)
Set var4=Object1(same type as Object)
Var1.property1=NewPropertyValue
the other Vars properties also changes,so:
Var1.property1=Var2.property1=Var3.property1=Var4.property1=Object1.Property1=NewpropertyValue`
actualy all vars are the same!
your panel class don't have a constructor that accepts a string
try change
RLS_strid_panel p = new RLS_strid_panel(namn1);
to
RLS_strid_panel p = new RLS_strid_panel();
p.setName1(name1);
Why not serialize the whole list at once?
FileOutputStream fout = new FileOutputStream("G:\\address.ser");
ObjectOutputStream oos = new ObjectOutputStream(fout);
oos.writeObject(MyClassList);
Assuming, of course, that MyClassList is an ArrayList
or LinkedList
, or another Serializable
collection.
In the case of reading it back, in your code you ready only one item, there is no loop to gather all the item written.
Yes, you can achieve it by find_elements_by_css_selector("*")
or find_elements_by_xpath(".//*")
.
However, this doesn't sound like a valid use case to find all children of an element. It is an expensive operation to get all direct/indirect children. Please further explain what you are trying to do. There should be a better way.
from selenium import webdriver
driver = webdriver.Firefox()
driver.get("http://www.stackoverflow.com")
header = driver.find_element_by_id("header")
# start from your target element, here for example, "header"
all_children_by_css = header.find_elements_by_css_selector("*")
all_children_by_xpath = header.find_elements_by_xpath(".//*")
print 'len(all_children_by_css): ' + str(len(all_children_by_css))
print 'len(all_children_by_xpath): ' + str(len(all_children_by_xpath))
A simple and better way for your exemple is:
BigDecimal price;
if(BigDecimal.ZERO.compareTo(price) == 0){
//Returns TRUE
}
I think the best method out there is to implement the SIGAR API by Hyperic. It works for most of the major operating systems ( darn near anything modern ) and is very easy to work with. The developer(s) are very responsive on their forum and mailing lists. I also like that it is GPL2 Apache licensed. They provide a ton of examples in Java too!
I guess the proper solution is:
(1) backup your-file/your-directory
(2) svn revert your-file/your-directory
(3) svn update your-file/your-directory
(4) Merge the backup your-file/your-directory to the updated one.
(5) svn ci -m "My work here is done"
In Kotlin, if
statements are expressions. So the following code is equivalent:
if (a) b else c
The distinction between expression and statement is important here. In Java/C#/JavaScript, if
forms a statement, meaning that it does not resolve to a value. More concretely, you can't assign it to a variable.
// Valid Kotlin, but invalid Java/C#/JavaScript
var v = if (a) b else c
If you're coming from a language where if
is a statement, this might seem unnatural but that feeling should soon subside.
Please see http://msdn.microsoft.com/en-us/library/aa260631(v=SQL.80).aspx In SQL server a timestamp is not the same as a DateTime column. This is used to uniquely identify a row in a database, not just a table but the entire database. This can be used for optimistic concurrency. for example UPDATE [Job] SET [Name]=@Name, [XCustomData]=@XCustomData WHERE ([ModifiedTimeStamp]=@Original_ModifiedTimeStamp AND [GUID]=@Original_GUID
the ModifiedTimeStamp ensures that you are updating the original data and will fail if another update has occurred to the row.
I ran into an issue with floats and decimals using the implementation selected as the answer above.
This test fails (floats; hash is the same even though I switched 2 values to be negative):
var obj1 = new { A = 100m, B = 100m, C = 100m, D = 100m};
var obj2 = new { A = 100m, B = 100m, C = -100m, D = -100m};
var hash1 = ComputeHash(obj1.A, obj1.B, obj1.C, obj1.D);
var hash2 = ComputeHash(obj2.A, obj2.B, obj2.C, obj2.D);
Assert.IsFalse(hash1 == hash2, string.Format("Hashcode values should be different hash1:{0} hash2:{1}",hash1,hash2));
But this test passes (with ints):
var obj1 = new { A = 100m, B = 100m, C = 100, D = 100};
var obj2 = new { A = 100m, B = 100m, C = -100, D = -100};
var hash1 = ComputeHash(obj1.A, obj1.B, obj1.C, obj1.D);
var hash2 = ComputeHash(obj2.A, obj2.B, obj2.C, obj2.D);
Assert.IsFalse(hash1 == hash2, string.Format("Hashcode values should be different hash1:{0} hash2:{1}",hash1,hash2));
I changed my implementation to not use GetHashCode for the primitive types and it seems to work better
private static int InternalComputeHash(params object[] obj)
{
unchecked
{
var result = (int)SEED_VALUE_PRIME;
for (uint i = 0; i < obj.Length; i++)
{
var currval = result;
var nextval = DetermineNextValue(obj[i]);
result = (result * MULTIPLIER_VALUE_PRIME) + nextval;
}
return result;
}
}
private static int DetermineNextValue(object value)
{
unchecked
{
int hashCode;
if (value is short
|| value is int
|| value is byte
|| value is sbyte
|| value is uint
|| value is ushort
|| value is ulong
|| value is long
|| value is float
|| value is double
|| value is decimal)
{
return Convert.ToInt32(value);
}
else
{
return value != null ? value.GetHashCode() : 0;
}
}
}
if x
is a vector with raw scores then scale(x)
is a vector with standardized scores.
Or manually: (x-mean(x))/sd(x)
String query = "INSERT INTO ....";
PreparedStatement preparedStatement = connection.prepareStatement(query, PreparedStatement.RETURN_GENERATED_KEYS);
preparedStatement.setXXX(1, VALUE);
preparedStatement.setXXX(2, VALUE);
....
preparedStatement.executeUpdate();
ResultSet rs = preparedStatement.getGeneratedKeys();
int key = rs.next() ? rs.getInt(1) : 0;
if(key!=0){
System.out.println("Generated key="+key);
}
I have disabled Instant Run feature from the preferences and the issue was solved.
In my case the solution was simple:
I have defined the route at the very start of the route.php
file.
After moving the named route to the bottom, my app finally saw it. It means that somehow the route was defined too early.
Languages like scala&python give to you very powerful stuff like patternMatching, unfortunately this is still a missing-feature in Java...
but there is a solution (which I don't like in most of the cases), you can do something like this:
final int s1Value = 0;
final int s2Value = 0;
final String s1 = "a";
final String s2 = "g";
switch (s1 + s2 + s1Value + s2Value){
case "ag00": return true;
default: return false;
}
you can use numpy.argsort
or you can do:
test = [2,3,1,4,5]
idxs = list(zip(*sorted([(val, i) for i, val in enumerate(test)])))[1]
zip
will rearange the list so that the first element is test
and the second is the idxs
.
It could be you haven't setup PHP~!
Bootstrap v4 introduces flexbox support
<div class="d-flex justify-content-end">
<div class="mr-auto p-2">Flex item</div>
<div class="p-2">Flex item</div>
<div class="p-2">Flex item</div>
</div>
Learn more at https://v4-alpha.getbootstrap.com/utilities/flexbox/
If you are able to use a NSString
only.
It's pretty similar to objective-c. All the data type are there but require the as NSString
addition
var x = "400.0" as NSString
x.floatValue //string to float
x.doubleValue // to double
x.boolValue // to bool
x.integerValue // to integer
x.intValue // to int
Also we have an toInt()
function added See Apple Inc. “The Swift Programming Language.” iBooks. https://itun.es/us/jEUH0.l page 49
x.toInt()
File 1
class ClassA {
public $name = 'A';
public function getName(){
return $this->name;
}
}
File 2
include("file1.php");
class ClassB {
public $name = 'B';
public function getName(){
return $this->name;
}
public function callA(){
$a = new ClassA();
return $a->getName();
}
public static function callAStatic(){
$a = new ClassA();
return $a->getName();
}
}
$b = new ClassB();
echo $b->callA();
echo $b->getName();
echo ClassB::callAStatic();
I think the best solution, though not exactly the same as Eclipse/Netbeans, is to change the 'Optimize Imports' settings.
Under Preferences > Editor > General > Auto Import
Set Add unambiguous imports on the fly
Edit: Using this method, when there are ambiguous imports, IntelliJ will let you know, and you can then use Alt + Enter method outlined in the answer by Wuaner
I find that, almost always, the most appropriate Import is at the top of the list.
If you are using Anaconda's Python distribution,
you can install it through pip
pip install setuptools
and then execute it as a module
python -m easy_install
I always just convert a matrix:
x <- as.data.frame(matrix(nrow = 100, ncol = 10))
First off: a List
is a Collection
. It is a specialized Collection
, however.
A Collection
is just that: a collection of items. You can add stuff, remove stuff, iterate over stuff and query how much stuff is in there.
A List
adds the information about a defined sequence of stuff to it: You can get the element at position n, you can add an element at position n, you can remove the element at position n.
In a Collection
you can't do that: "the 5th element in this collection" isn't defined, because there is no defined order.
There are other specialized Collections as well, for example a Set
which adds the feature that it will never contain the same element twice.
Create a linked server to your document
http://www.excel-sql-server.com/excel-import-to-sql-server-using-linked-servers.htm
Then use ordinary INSERT or SELECT INTO. If you want to get fancy, you can use ADO.NET's SqlBulkCopy, which takes just about any data source that you can get a DataReader from and is pretty quick on insert, although the reading of the data won't be esp fast.
You could also take the time to transform an excel spreadsheet into a text delimited file or other bcp supported format and then use BCP.
All the answers here are wrong, they missing important piece, the height
.container{
width:200px;
height:600px;
background:red
}
.title {
overflow: hidden;
line-height: 20px;
height: 40px;
text-overflow: ellipsis;
display: -webkit-box;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
}
<div class="container">
<div class="title">this is a long text you cant cut it in half</div>
</div>
Simply call list
on the generator.
lst = list(gen)
lst
Be aware that this affects the generator which will not return any further items.
You also cannot directly call list
in IPython, as it conflicts with a command for listing lines of code.
Tested on this file:
def gen():
yield 1
yield 2
yield 3
yield 4
yield 5
import ipdb
ipdb.set_trace()
g1 = gen()
text = "aha" + "bebe"
mylst = range(10, 20)
which when run:
$ python code.py
> /home/javl/sandbox/so/debug/code.py(10)<module>()
9
---> 10 g1 = gen()
11
ipdb> n
> /home/javl/sandbox/so/debug/code.py(12)<module>()
11
---> 12 text = "aha" + "bebe"
13
ipdb> lst = list(g1)
ipdb> lst
[1, 2, 3, 4, 5]
ipdb> q
Exiting Debugger.
There are debugger commands p
and pp
that will print
and prettyprint
any expression following them.
So you could use it as follows:
$ python code.py
> /home/javl/sandbox/so/debug/code.py(10)<module>()
9
---> 10 g1 = gen()
11
ipdb> n
> /home/javl/sandbox/so/debug/code.py(12)<module>()
11
---> 12 text = "aha" + "bebe"
13
ipdb> p list(g1)
[1, 2, 3, 4, 5]
ipdb> c
There is also an exec
command, called by prefixing your expression with !
, which forces debugger to take your expression as Python one.
ipdb> !list(g1)
[]
For more details see help p
, help pp
and help exec
when in debugger.
ipdb> help exec
(!) statement
Execute the (one-line) statement in the context of
the current stack frame.
The exclamation point can be omitted unless the first word
of the statement resembles a debugger command.
To assign to a global variable you must always prefix the
command with a 'global' command, e.g.:
(Pdb) global list_options; list_options = ['-l']
It should be well noted that the use of live()
in jQuery has been deprecated since version 1.7
and has been removed in jQuery 1.9
. Instead, the use of on()
is recommended.
I would highly suggest the following methodology for binding, as it solves the following potential challenges:
document.body
and passing $selector as the second argument to on()
, elements can be attached, detached, added or removed from the DOM without needing to deal with re-binding or double-binding events. This is because the event is attached to document.body
rather than $selector
directly, which means $selector
can be added, removed and added again and will never load the event bound to it.off()
before on()
, this script can live either within within the main body of the page, or within the body of an AJAX call, without having to worry about accidentally double-binding events.$(function() {...})
, this script can again be loaded by either the main body of the page, or within the body of an AJAX call. $(document).ready()
does not get fired for AJAX requests, while $(function() {...})
does.Here is an example:
<!DOCTYPE html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
var $selector = $('textarea');
// Prevent double-binding
// (only a potential issue if script is loaded through AJAX)
$(document.body).off('keyup', $selector);
// Bind to keyup events on the $selector.
$(document.body).on('keyup', $selector, function(event) {
if(event.keyCode == 13) { // 13 = Enter Key
alert('enter key pressed.');
}
});
});
</script>
</head>
<body>
</body>
</html>
With Winforms you can use Form.BackColor to do this.
From within the Form's code:
BackColor = Color.LightPink;
If you mean a WPF Window you can use the Background property.
From within the Window's code:
Background = Brushes.LightPink;
Path.GetDirectoryName(Context.Parameters["assemblypath"])
Swift 4.2 updated code is
let storyboard = UIStoryboard(name: "StoryboardNameHere", bundle: nil)
let controller = storyboard.instantiateViewController(withIdentifier: "ViewControllerNameHere")
self.present(controller, animated: true, completion: nil)
Does an implicit conversion occur between Task<> and int?
Nope. This is just part of how async
/await
works.
Any method declared as async
has to have a return type of:
void
(avoid if possible)Task
(no result beyond notification of completion/failure)Task<T>
(for a logical result of type T
in an async manner)The compiler does all the appropriate wrapping. The point is that you're asynchronously returning urlContents.Length
- you can't make the method just return int
, as the actual method will return when it hits the first await
expression which hasn't already completed. So instead, it returns a Task<int>
which will complete when the async method itself completes.
Note that await
does the opposite - it unwraps a Task<T>
to a T
value, which is how this line works:
string urlContents = await getStringTask;
... but of course it unwraps it asynchronously, whereas just using Result
would block until the task had completed. (await
can unwrap other types which implement the awaitable pattern, but Task<T>
is the one you're likely to use most often.)
This dual wrapping/unwrapping is what allows async to be so composable. For example, I could write another async method which calls yours and doubles the result:
public async Task<int> AccessTheWebAndDoubleAsync()
{
var task = AccessTheWebAsync();
int result = await task;
return result * 2;
}
(Or simply return await AccessTheWebAsync() * 2;
of course.)
Thanks to Andrey Egorov, in my case with python setAttribute
not working, but I found I can set the property directly,
Try this code:
driver.execute_script("document.getElementById('q').value='value here'")
MSYS has not been updated a long time, MSYS2 is more active, you can download from MSYS2, it has both mingw
and cygwin fork
package.
To install the MinGW-w64 toolchain (Reference):
pacman -Sy pacman
to update the package databasepacman -Syu
to update the package database and core system packagespacman -Su
to update the restpacman -S mingw-w64-i686-toolchain
pacman -S mingw-w64-x86_64-toolchain
make
, run pacman -S make
\r
= CR (Carriage Return) → Used as a new line character in Mac OS before X\n
= LF (Line Feed) → Used as a new line character in Unix/Mac OS X\r\n
= CR + LF → Used as a new line character in WindowsIf you want to copy a one-dimensional list, use
b = a[:]
However, if a
is a 2-dimensional list, this is not going to work for you. That is, any changes in a
will also be reflected in b
. In that case, use
b = [[a[x][y] for y in range(len(a[0]))] for x in range(len(a))]
You do not define a binding in your service's config, so you are getting the default values for wsHttpBinding
, and the default value for securityMode\transport
for that binding is Message
.
Try copying your binding configuration from the client's config to your service config and assign that binding to the endpoint via the bindingConfiguration
attribute:
<bindings>
<wsHttpBinding>
<binding name="ota2010AEndpoint"
.......>
<readerQuotas maxDepth="32" ... />
<reliableSession ordered="true" .... />
<security mode="Transport">
<transport clientCredentialType="None" proxyCredentialType="None"
realm="" />
<message clientCredentialType="Windows" negotiateServiceCredential="true"
establishSecurityContext="true" />
</security>
</binding>
</wsHttpBinding>
</bindings>
(Snipped parts of the config to save space in the answer).
<service name="Synxis" behaviorConfiguration="SynxisWCF">
<endpoint address="" name="wsHttpEndpoint"
binding="wsHttpBinding"
bindingConfiguration="ota2010AEndpoint"
contract="Synxis" />
This will then assign your defined binding (with Transport security) to the endpoint.
U can do it easier than this answers :
Uri Selected_Image_Uri = data.getData();
ImageView imageView = (ImageView) findViewById(R.id.loadedimg);
imageView.setImageURI(Selected_Image_Uri);
Let me quote the official documentation:
Important gotcha on spying real objects!
Sometimes it's impossible to use when(Object) for stubbing spies. Example:
List list = new LinkedList(); List spy = spy(list); // Impossible: real method is called so spy.get(0) throws IndexOutOfBoundsException (the list is yet empty) when(spy.get(0)).thenReturn("foo"); // You have to use doReturn() for stubbing doReturn("foo").when(spy).get(0);
In your case it goes something like:
doReturn(resultsIWant).when(myClassSpy).method1();
Before Execute query I put the statement as below and it resolved my error. Just FYI in case it will help someone.
ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072; ctx.ExecuteQuery();
Two possible answers:
1- You did not include spring-beans and spring-context jars in your lib. If you are using maven (which will help a lot) those two lines will be enough
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>3.1.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>3.1.0.RELEASE</version>
</dependency>
2- The necessary jars are in your classpath but are not deployed on tomcat.
all zeros would probably be the most obvious that it wasn't a real SSN.
If you are using System.Text.Json
then you can use [JsonIgnore]
.
FQ: System.Text.Json.Serialization.JsonIgnoreAttribute
Official Microsoft Docs: JsonIgnoreAttribute
As stated here:
The library is built-in as part of the .NET Core 3.0 shared framework.
For other target frameworks, install the System.Text.Json NuGet package. The package supports:
- .NET Standard 2.0 and later versions
- .NET Framework 4.6.1 and later versions
- .NET Core 2.0, 2.1, and 2.2
create shake.xml in anim folder
<?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
android:fromXDelta="0"
android:toXDelta="10"
android:duration="1000"
android:interpolator="@anim/cycle" />
and cycle.xml in anim folder
<?xml version="1.0" encoding="utf-8"?>
<cycleInterpolator xmlns:android="http://schemas.android.com/apk/res/android"
android:cycles="4" />
now add animation on your code
Animation shake = AnimationUtils.loadAnimation(this, R.anim.shake);
anyview.startAnimation(shake);
If you want vertical animation, change fromXdelta and toXdelta value to fromYdelta and toYdelta value
Visit https://play.golang.org/p/dx6PTtuBXQW
package main
import (
"fmt"
"sort"
)
func main() {
mapEg := map[string]string{"c":"a","a":"c","b":"b"}
keys := make([]string, 0, len(mapEg))
for k := range mapEg {
keys = append(keys, k)
}
sort.Strings(keys)
fmt.Println(keys)
}
You can use the DataTables api to filter the table. So all you need is your own input field with a keyup event that triggers the filter function to DataTables. With css or jquery you can hide/remove the existing search input field. Or maybe DataTables has a setting to remove/not-include it.
Checkout the Datatables API documentation on this.
Example:
HTML
<input type="text" id="myInputTextField">
JS
oTable = $('#myTable').DataTable(); //pay attention to capital D, which is mandatory to retrieve "api" datatables' object, as @Lionel said
$('#myInputTextField').keyup(function(){
oTable.search($(this).val()).draw() ;
})
Use:
if (isset($_POST['user'])) {
//do something
}
But you probably should be using some more proper validation. Try a simple regex or a rock-solid implementation from Zend Framework or Symfony.
http://framework.zend.com/manual/en/zend.validate.introduction.html
http://symfony.com/doc/current/book/validation.html
Or even the built-in filter extension:
http://php.net/manual/en/function.filter-var.php
Never trust user input, be smart. Don't trust anything. Always make sure what you receive is really what you expect. If it should be a number, make SURE it's a number.
Much improved code:
$user = filter_var($_POST['user'], FILTER_SANITIZE_STRING);
$isValid = filter_var($user, FILTER_VALIDATE_REGEXP, array('options' => array('regexp' => "/^[a-zA-Z0-9]+$/")));
if ($isValid) {
// do something
}
Sanitization and validation.
You don't need to specify both at the same time, unless you're specifically restricting the other verbs (i.e. you don't want PUT or DELETE, etc).
Contrary to some of the comments, I was also unable to use both Attributes [HttpGet, HttpPost]
at the same time, but was able to specify both verbs instead.
private ActionResult testResult(int id)
{
return Json(new {
// user input
input = id,
// just so there's different content in the response
when = DateTime.Now,
// type of request
req = this.Request.HttpMethod,
// differentiate calls in response, for matching up
call = new StackTrace().GetFrame(1).GetMethod().Name
},
JsonRequestBehavior.AllowGet);
}
public ActionResult Test(int id)
{
return testResult(id);
}
[HttpGet]
public ActionResult TestGetOnly(int id)
{
return testResult(id);
}
[HttpPost]
public ActionResult TestPostOnly(int id)
{
return testResult(id);
}
[HttpPost, HttpGet]
public ActionResult TestBoth(int id)
{
return testResult(id);
}
[AcceptVerbs(HttpVerbs.Get | HttpVerbs.Post)]
public ActionResult TestVerbs(int id)
{
return testResult(id);
}
via POSTMAN, formatting by markdowntables
| Method | URL | Response |
|-------- |---------------------- |---------------------------------------------------------------------------------------- |
| GET | /ctrl/test/5 | { "input": 5, "when": "/Date(1408041216116)/", "req": "GET", "call": "Test" } |
| POST | /ctrl/test/5 | { "input": 5, "when": "/Date(1408041227561)/", "req": "POST", "call": "Test" } |
| PUT | /ctrl/test/5 | { "input": 5, "when": "/Date(1408041252646)/", "req": "PUT", "call": "Test" } |
| GET | /ctrl/testgetonly/5 | { "input": 5, "when": "/Date(1408041335907)/", "req": "GET", "call": "TestGetOnly" } |
| POST | /ctrl/testgetonly/5 | 404 |
| PUT | /ctrl/testgetonly/5 | 404 |
| GET | /ctrl/TestPostOnly/5 | 404 |
| POST | /ctrl/TestPostOnly/5 | { "input": 5, "when": "/Date(1408041464096)/", "req": "POST", "call": "TestPostOnly" } |
| PUT | /ctrl/TestPostOnly/5 | 404 |
| GET | /ctrl/TestBoth/5 | 404 |
| POST | /ctrl/TestBoth/5 | 404 |
| PUT | /ctrl/TestBoth/5 | 404 |
| GET | /ctrl/TestVerbs/5 | { "input": 5, "when": "/Date(1408041709606)/", "req": "GET", "call": "TestVerbs" } |
| POST | /ctrl/TestVerbs/5 | { "input": 5, "when": "/Date(1408041831549)/", "req": "POST", "call": "TestVerbs" } |
| PUT | /ctrl/TestVerbs/5 | 404 |
You don't import scripts in Python you import modules. Some python modules are also scripts that you can run directly (they do some useful work at a module-level).
In general it is preferable to use absolute imports rather than relative imports.
toplevel_package/
+-- __init__.py
+-- moduleA.py
+-- subpackage
+-- __init__.py
+-- moduleB.py
In moduleB
:
from toplevel_package import moduleA
If you'd like to run moduleB.py
as a script then make sure that parent directory for toplevel_package
is in your sys.path
.
class Node:
rChild,lChild,data = None,None,None
This is wrong - it makes your variables class variables - that is, every instance of Node uses the same values (changing rChild of any node changes it for all nodes!). This is clearly not what you want; try
class Node:
def __init__(self, key):
self.rChild = None
self.lChild = None
self.data = key
now each node has its own set of variables. The same applies to your definition of Tree,
class Tree:
root,size = None,0 # <- lose this line!
def __init__(self):
self.root = None
self.size = 0
Further, each class should be a "new-style" class derived from the "object" class and should chain back to object.__init__():
class Node(object):
def __init__(self, data, rChild=None, lChild=None):
super(Node,self).__init__()
self.data = data
self.rChild = rChild
self.lChild = lChild
class Tree(object):
def __init__(self):
super(Tree,self).__init__()
self.root = None
self.size = 0
Also, main() is indented too far - as shown, it is a method of Tree which is uncallable because it does not accept a self argument.
Also, you are modifying the object's data directly (t.root = Node(4)
) which kind of destroys encapsulation (the whole point of having classes in the first place); you should be doing something more like
def main():
t = Tree()
t.add(4) # <- let the tree create a data Node and insert it
t.add(5)
It's generally a bad idea to write your own cryptography unless you have experience breaking other peoples' cryptography implementations.
None of the examples here authenticate the ciphertext, which leaves them vulnerable to bit-rewriting attacks.
<?php
// PECL libsodium 0.2.1 and newer
/**
* Encrypt a message
*
* @param string $message - message to encrypt
* @param string $key - encryption key
* @return string
*/
function safeEncrypt($message, $key)
{
$nonce = \Sodium\randombytes_buf(
\Sodium\CRYPTO_SECRETBOX_NONCEBYTES
);
return base64_encode(
$nonce.
\Sodium\crypto_secretbox(
$message,
$nonce,
$key
)
);
}
/**
* Decrypt a message
*
* @param string $encrypted - message encrypted with safeEncrypt()
* @param string $key - encryption key
* @return string
*/
function safeDecrypt($encrypted, $key)
{
$decoded = base64_decode($encrypted);
$nonce = mb_substr($decoded, 0, \Sodium\CRYPTO_SECRETBOX_NONCEBYTES, '8bit');
$ciphertext = mb_substr($decoded, \Sodium\CRYPTO_SECRETBOX_NONCEBYTES, null, '8bit');
return \Sodium\crypto_secretbox_open(
$ciphertext,
$nonce,
$key
);
}
Then to test it out:
<?php
// This refers to the previous code block.
require "safeCrypto.php";
// Do this once then store it somehow:
$key = \Sodium\randombytes_buf(\Sodium\CRYPTO_SECRETBOX_KEYBYTES);
$message = 'We are all living in a yellow submarine';
$ciphertext = safeEncrypt($message, $key);
$plaintext = safeDecrypt($ciphertext, $key);
var_dump($ciphertext);
var_dump($plaintext);
This can be used in any situation where you are passing data to the client (e.g. encrypted cookies for sessions without server-side storage, encrypted URL parameters, etc.) with a reasonably high degree of certainty that the end user cannot decipher or reliably tamper with it.
Since libsodium is cross-platform, this also makes it easier to communicate with PHP from, e.g. Java applets or native mobile apps.
Note: If you specifically need to add encrypted cookies powered by libsodium to your app, my employer Paragon Initiative Enterprises is developing a library called Halite that does all of this for you.
Set MaintainScrollPositionOnPostBack="true"
in the page declaration:
<%@ Page Language="C#" MaintainScrollPositionOnPostBack="true" Title="Home" %>
For fellow googlers using Anaconda, install the ffmpeg package:
conda install -c conda-forge ffmpeg
This works on Windows too.
(Original answer used menpo
package owner but as mentioned by @harsh their version is a little behind at time of writing)
I had the same issue and I solved by adding an empty class annotated with SpringBootApplication
in the root package of the folder src/test/java
package org.enricogiurin.core;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class CoreTestConfiguration {}
you can do it by following way too ..
create table #test (a int, b char(1))
select * From #test
exec tempdb..sp_columns '#test'
$(document).keydown(function(e){
if (e.which == 37) {
alert("left pressed");
return false;
}
});
Character codes:
37 - left
38 - up
39 - right
40 - down
You can do this via the information_schema tables. For example:
SELECT
tc.table_schema,
tc.constraint_name,
tc.table_name,
kcu.column_name,
ccu.table_schema AS foreign_table_schema,
ccu.table_name AS foreign_table_name,
ccu.column_name AS foreign_column_name
FROM
information_schema.table_constraints AS tc
JOIN information_schema.key_column_usage AS kcu
ON tc.constraint_name = kcu.constraint_name
AND tc.table_schema = kcu.table_schema
JOIN information_schema.constraint_column_usage AS ccu
ON ccu.constraint_name = tc.constraint_name
AND ccu.table_schema = tc.table_schema
WHERE tc.constraint_type = 'FOREIGN KEY' AND tc.table_name='mytable';
Create system user some_user
if it doesn't exist
if [[ $(getent passwd some_user) = "" ]]; then
sudo adduser --no-create-home --force-badname --disabled-login --disabled-password --system some_user
fi
Well...
? (Optional) indicates your variable may contain a nil value while ! (unwrapper) indicates your variable must have a memory (or value) when it is used (tried to get a value from it) at runtime.
The main difference is that optional chaining fails gracefully when the optional is nil, whereas forced unwrapping triggers a runtime error when the optional is nil.
To reflect the fact that optional chaining can be called on a nil value, the result of an optional chaining call is always an optional value, even if the property, method, or subscript you are querying returns a nonoptional value. You can use this optional return value to check whether the optional chaining call was successful (the returned optional contains a value), or did not succeed due to a nil value in the chain (the returned optional value is nil).
Specifically, the result of an optional chaining call is of the same type as the expected return value, but wrapped in an optional. A property that normally returns an Int will return an Int? when accessed through optional chaining.
var defaultNil : Int? // declared variable with default nil value
println(defaultNil) >> nil
var canBeNil : Int? = 4
println(canBeNil) >> optional(4)
canBeNil = nil
println(canBeNil) >> nil
println(canBeNil!) >> // Here nil optional variable is being unwrapped using ! mark (symbol), that will show runtime error. Because a nil optional is being tried to get value using unwrapper
var canNotBeNil : Int! = 4
print(canNotBeNil) >> 4
var cantBeNil : Int = 4
cantBeNil = nil // can't do this as it's not optional and show a compile time error
Here is basic tutorial in detail, by Apple Developer Committee: Optional Chaining
Off the top of my head I think it should be done like this:
var veggies = "carrot";
var fruitvegbasket = [];
fruitvegbasket.push(veggies);
If you have a reporting services infrastructure available to you, use it. You will find RDL development to be a bit more pleasant. You can preview the report, easily setup parameters, etc.
I would take a different tack entirely. Don't RETURN in the middle of the method/function. Instead, just put the return value in a local variable and send it at the end.
Personally, I find the following to be more readable:
String result = "";
switch (something) {
case 0:
result = "blah";
break;
case 1:
result = "foo";
break;
}
return result;
Please, be aware, that this error appears when your server is under attack. Just found that redis fails to write to '/etc/cron.d/web' where after correcting of permissions, new file consisting of mining algorithm with some hiding options was added.
A post back is anything that cause the page from the client's web browser to be pushed back to the server.
There's alot of info out there, search google for postbacks.
Most of the time, any ASP control will cause a post back (button/link click) but some don't unless you tell them to (checkbox/combobox)
The @Context
annotation (see answers in this question :What does context annotation do in Spring?) will cause it to be injected for you.
I had to use
@Context
private HttpServletRequest request;
I'd a similar problem in WebAPI (related MVC).
I fixed with:
Adding ".Global" to inherits in .asax file (not asax.cs)
Inherits="mynamespace.WebAPI.Global"
and changing the public class (asax.cs)
public class Global : System.Web.HttpApplication
I have seen people use Throwable to catch some errors that might happen due to infra failure/ non availability.
Sorry to resurrect this answer, but in iOS 10 things kinda changed, and now cancelling is possible and you can even cancel gracefully!
After iOS 10 you can cancel animations with UIViewPropertyAnimator!
UIViewPropertyAnimator(duration: 2, dampingRatio: 0.4, animations: {
view.backgroundColor = .blue
})
animator.stopAnimation(true)
If you pass true it cancels the animation and it stops right where you cancelled it. The completion method will not be called. However, if you pass false you are responsible for finishing the animation:
animator.finishAnimation(.start)
You can finish your animation and stay in the current state (.current) or go to the initial state (.start) or to the end state (.end)
By the way, you can even pause and restart later...
animator.pauseAnimation()
animator.startAnimation()
Note: If you don't want an abrupt cancelling you can reverse your animation or even change your animation after you pause it!
Along with the above answers , you can do this too
=> [*'1'.."5"] #remember *
=> ["1", "2", "3", "4", "5"]
Simply using re.sub
might also work instead of str.maketrans
. And this would also work in python 2.x
>>> print(re.sub(r'(\-|\]|\^|\$|\*|\.|\\)',lambda m:{'-':'\-',']':'\]','\\':'\\\\','^':'\^','$':'\$','*':'\*','.':'\.'}[m.group()],"^stack.*/overflo\w$arr=1"))
\^stack\.\*/overflo\\w\$arr=1
Which worked for me: ("üzüm baglari" is the correct written in Turkish)
Convert ISO-8859-1 to UTF-8:
String encodedWithISO88591 = "üzüm baÄları";
String decodedToUTF8 = new String(encodedWithISO88591.getBytes("ISO-8859-1"), "UTF-8");
//Result, decodedToUTF8 --> "üzüm baglari"
Convert UTF-8 to ISO-8859-1
String encodedWithUTF8 = "üzüm baglari";
String decodedToISO88591 = new String(encodedWithUTF8.getBytes("UTF-8"), "ISO-8859-1");
//Result, decodedToISO88591 --> "üzüm baÄları"
var randomNums = function(amount, limit) {
var result = [],
memo = {};
while(result.length < amount) {
var num = Math.floor((Math.random() * limit) + 1);
if(!memo[num]) { memo[num] = num; result.push(num); };
}
return result; }
This seems to work, and its constant lookup for duplicates.
great answer from @David, here is for Python 3 without the generic try-except:
def send_email(user, password, recipient, subject, body):
gmail_user = user
gmail_pwd = password
FROM = user
TO = recipient if type(recipient) is list else [recipient]
SUBJECT = subject
TEXT = body
# Prepare actual message
message = """From: %s\nTo: %s\nSubject: %s\n\n%s
""" % (FROM, ", ".join(TO), SUBJECT, TEXT)
server = smtplib.SMTP("smtp.gmail.com", 587)
server.ehlo()
server.starttls()
server.login(gmail_user, gmail_pwd)
server.sendmail(FROM, TO, message)
server.close()
Since I found Darko's answer very helpful in colorizing custom pins for mapView annotations, but had to do some conversions for Swift 3, thought I'd share the updated code along with my recommendation for his answer:
extension UIImage {
func maskWithColor(color: UIColor) -> UIImage {
var maskImage = self.CGImage
let width = self.size.width
let height = self.size.height
let bounds = CGRect(x: 0, y: 0, width: width, height: height)
let colorSpace = CGColorSpaceCreateDeviceRGB()
let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedLast.rawValue)
let bitmapContext = CGContext(data: nil, width: Int(width), height: Int(height), bitsPerComponent: 8, bytesPerRow: 0, space: colorSpace, bitmapInfo: bitmapInfo.rawValue)
bitmapContext!.clip(to: bounds, mask: maskImage!)
bitmapContext!.setFillColor(color.cgColor)
bitmapContext!.fill(bounds)
let cImage = bitmapContext!.makeImage()
let coloredImage = UIImage(CGImage: cImage)
return coloredImage!
}
}
One easy step:
$ npm i -g npm-check-updates && ncu -u && npm i
That is all. All of the package versions in package.json
will be the latest major versions.
Edit:
What is happening here?
Installing a package that checks updates for you.
Use this package to update all package versions in your
package.json
(-u is short for --updateAll).Install all of the new versions of the packages.
Here is my solution, also does touppercase by the use of an argument and checks for other possible white-spaces and capitalisation in the supplied string.
var a = "rgb(10, 128, 255)";
var b = "rgb( 10, 128, 255)";
var c = "rgb(10, 128, 255 )";
var d = "rgb ( 10, 128, 255 )";
var e = "RGB ( 10, 128, 255 )";
var f = "rgb(10,128,255)";
var g = "rgb(10, 128,)";
var rgbToHex = (function () {
var rx = /^rgb\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)$/i;
function pad(num) {
if (num.length === 1) {
num = "0" + num;
}
return num;
}
return function (rgb, uppercase) {
var rxArray = rgb.match(rx),
hex;
if (rxArray !== null) {
hex = pad(parseInt(rxArray[1], 10).toString(16)) + pad(parseInt(rxArray[2], 10).toString(16)) + pad(parseInt(rxArray[3], 10).toString(16));
if (uppercase === true) {
hex = hex.toUpperCase();
}
return hex;
}
return;
};
}());
console.log(rgbToHex(a));
console.log(rgbToHex(b, true));
console.log(rgbToHex(c));
console.log(rgbToHex(d));
console.log(rgbToHex(e));
console.log(rgbToHex(f));
console.log(rgbToHex(g));
On jsfiddle
Speed comparison on jsperf
A further improvement could be to trim()
the rgb
string
var rxArray = rgb.trim().match(rx),
While I know many architectures like ASP.NET MVC have built-in functionality to handle JSON.stringify as the contentType my situation is a little different so maybe this may help someone in the future. I know it would have saved me hours!
Since my http requests are being handled by a CGI API from IBM (AS400 environment) on a different subdomain these requests are cross origin, hence the jsonp. I actually send my ajax via javascript object(s). Here is an example of my ajax POST:
var data = {USER : localProfile,
INSTANCE : "HTHACKNEY",
PAGE : $('select[name="PAGE"]').val(),
TITLE : $("input[name='TITLE']").val(),
HTML : html,
STARTDATE : $("input[name='STARTDATE']").val(),
ENDDATE : $("input[name='ENDDATE']").val(),
ARCHIVE : $("input[name='ARCHIVE']").val(),
ACTIVE : $("input[name='ACTIVE']").val(),
URGENT : $("input[name='URGENT']").val(),
AUTHLST : authStr};
//console.log(data);
$.ajax({
type: "POST",
url: "http://www.domian.com/webservicepgm?callback=?",
data: data,
dataType:'jsonp'
}).
done(function(data){
//handle data.WHATEVER
});
if (empty($_FILES['cover_image']['name']))