@erdna Please refer my below code.May be it will become helpful to you.
int firstVisibleItem, visibleItemCount, totalItemCount;
recyclerView.setOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
visibleItemCount = layoutManager.getChildCount();
totalItemCount = layoutManager.getItemCount();
firstVisibleItem = layoutManager.findFirstVisibleItemPosition();
Log.e("firstVisibleItem", firstVisibleItem + "");
Log.e("visibleItemCount", visibleItemCount + "");
Log.e("totalItemCount", totalItemCount + "");
if (page != total_page_index) {
if (loading) {
if ((visibleItemCount + firstVisibleItem) >= totalItemCount) {
Log.e("page", String.valueOf(page));
page=page+1;
new GetSummary().execute(String.valueOf(page), "");
loading = false;
}
}
}
}
});
Reading quickly through the source it seems that you're not far off. The following link should help (I did something similar but for FTP). For a file send from server to client, you start off with a file instance and an array of bytes. You then read the File into the byte array and write the byte array to the OutputStream which corresponds with the InputStream on the client's side.
http://www.rgagnon.com/javadetails/java-0542.html
Edit: Here's a working ultra-minimalistic file sender and receiver. Make sure you understand what the code is doing on both sides.
package filesendtest;
import java.io.*;
import java.net.*;
class TCPServer {
private final static String fileToSend = "C:\\test1.pdf";
public static void main(String args[]) {
while (true) {
ServerSocket welcomeSocket = null;
Socket connectionSocket = null;
BufferedOutputStream outToClient = null;
try {
welcomeSocket = new ServerSocket(3248);
connectionSocket = welcomeSocket.accept();
outToClient = new BufferedOutputStream(connectionSocket.getOutputStream());
} catch (IOException ex) {
// Do exception handling
}
if (outToClient != null) {
File myFile = new File( fileToSend );
byte[] mybytearray = new byte[(int) myFile.length()];
FileInputStream fis = null;
try {
fis = new FileInputStream(myFile);
} catch (FileNotFoundException ex) {
// Do exception handling
}
BufferedInputStream bis = new BufferedInputStream(fis);
try {
bis.read(mybytearray, 0, mybytearray.length);
outToClient.write(mybytearray, 0, mybytearray.length);
outToClient.flush();
outToClient.close();
connectionSocket.close();
// File sent, exit the main method
return;
} catch (IOException ex) {
// Do exception handling
}
}
}
}
}
package filesendtest;
import java.io.*;
import java.io.ByteArrayOutputStream;
import java.net.*;
class TCPClient {
private final static String serverIP = "127.0.0.1";
private final static int serverPort = 3248;
private final static String fileOutput = "C:\\testout.pdf";
public static void main(String args[]) {
byte[] aByte = new byte[1];
int bytesRead;
Socket clientSocket = null;
InputStream is = null;
try {
clientSocket = new Socket( serverIP , serverPort );
is = clientSocket.getInputStream();
} catch (IOException ex) {
// Do exception handling
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
if (is != null) {
FileOutputStream fos = null;
BufferedOutputStream bos = null;
try {
fos = new FileOutputStream( fileOutput );
bos = new BufferedOutputStream(fos);
bytesRead = is.read(aByte, 0, aByte.length);
do {
baos.write(aByte);
bytesRead = is.read(aByte);
} while (bytesRead != -1);
bos.write(baos.toByteArray());
bos.flush();
bos.close();
clientSocket.close();
} catch (IOException ex) {
// Do exception handling
}
}
}
}
Related
Byte array of unknown length in java
Edit: The following could be used to fingerprint small files before and after transfer (use SHA if you feel it's necessary):
public static String md5String(File file) {
try {
InputStream fin = new FileInputStream(file);
java.security.MessageDigest md5er = MessageDigest.getInstance("MD5");
byte[] buffer = new byte[1024];
int read;
do {
read = fin.read(buffer);
if (read > 0) {
md5er.update(buffer, 0, read);
}
} while (read != -1);
fin.close();
byte[] digest = md5er.digest();
if (digest == null) {
return null;
}
String strDigest = "0x";
for (int i = 0; i < digest.length; i++) {
strDigest += Integer.toString((digest[i] & 0xff)
+ 0x100, 16).substring(1).toUpperCase();
}
return strDigest;
} catch (Exception e) {
return null;
}
}
modify() in your example is a private function, that won't be accessible from anywhere but within your A, B or C definition. You would need to declare it as
this.modify = function(){}
C has no reference to its parents, unless you pass it to C. If C is set up to inherit from A or B, it will inherit its public methods (not its private functions like you have modify() defined). Once C inherits methods from its parent, you can override the inherited methods.
The problem in this case is that onchange-event does not fire until the input looses focus, so you will probably want to listen for the keyup-event instead, which is fired on every keystroke.
Also, I would prefer not using inline-javascript, but rather catch the event using jQuery instead.
$("#txtConfirmPassword").keyup(checkPasswordMatch);
Note that the selected answer cannot be applied to your context directly before some modification, if you are trying to remove some entries from the map while iterating the map just like me.
I just give my working example here for newbies to save their time:
HashMap<Character,Integer> map=new HashMap();
//adding some entries to the map
...
int threshold;
//initialize the threshold
...
Iterator it=map.entrySet().iterator();
while(it.hasNext()){
Map.Entry<Character,Integer> item=(Map.Entry<Character,Integer>)it.next();
//it.remove() will delete the item from the map
if((Integer)item.getValue()<threshold){
it.remove();
}
So, rather return the whole object
first, just wrap it to json_encode
and then return it. This will return a proper and valid object.
public function id($id){
$promotion = Promotion::find($id);
return json_encode($promotion);
}
Or, For DB this will be just like,
public function id($id){
$promotion = DB::table('promotions')->first();
return json_encode($promotion);
}
I think it may help someone else.
This exception says that you are trying to deserialize the object "Address" from string "\"\"" instead of an object description like "{…}". The deserializer can't find a constructor of Address with String argument. You have to replace "" by {} to avoid this error.
The $(window).load()
is NOT available in jQuery 3.0
$( window ).load(function() {
// Handler for .load() called.
});
To get around it, you can use it as an "Event Handler Attachment"
$( window ).on("load", function() {
// Handler for .load() called.
});
Check out this article. I believe it should help you get what you are wanting. If your table already exists, and it has data in it already, the error you are getting may be due to the auto_increment trying to assign a value that already exists for other records.
In short, as others have already mentioned in comments, sequences, as they are thought of and handled in Oracle, do not exist in MySQL. However, you can likely use auto_increment to accomplish what you want.
Without additional details on the specific error, it is difficult to provide more specific help.
UPDATE
CREATE TABLE ORD (
ORDID INT NOT NULL AUTO_INCREMENT,
//Rest of table code
PRIMARY KEY (ordid)
)
AUTO_INCREMENT = 622;
This link is also helpful for describing usage of auto_increment. Setting the AUTO_INCREMENT value appears to be a table option, and not something that is specified as a column attribute specifically.
Also, per one of the links from above, you can alternatively set the auto increment start value via an alter to your table.
ALTER TABLE ORD AUTO_INCREMENT = 622;
UPDATE 2
Here is a link to a working sqlfiddle example, using auto increment.
I hope this info helps.
I have written a quick example to demonstrate how to create a layout programmatically.
public class CodeLayout extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Creating a new RelativeLayout
RelativeLayout relativeLayout = new RelativeLayout(this);
// Defining the RelativeLayout layout parameters.
// In this case I want to fill its parent
RelativeLayout.LayoutParams rlp = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.FILL_PARENT,
RelativeLayout.LayoutParams.FILL_PARENT);
// Creating a new TextView
TextView tv = new TextView(this);
tv.setText("Test");
// Defining the layout parameters of the TextView
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
lp.addRule(RelativeLayout.CENTER_IN_PARENT);
// Setting the parameters on the TextView
tv.setLayoutParams(lp);
// Adding the TextView to the RelativeLayout as a child
relativeLayout.addView(tv);
// Setting the RelativeLayout as our content view
setContentView(relativeLayout, rlp);
}
}
In theory everything should be clear as it is commented. If you don't understand something just tell me.
Check your project's properties. On the "Application" tab, select your Program
class as the Startup object:
To whom its just not working to (like me) no matter what you tried:
<element onscroll="myFunction()"></element>
works like a charm
exactly as they explain in W3 schools https://www.w3schools.com/tags/ev_onscroll.asp
Go File > Invalidate Caches / Restart... > Click at Invalidate and Restart
This really works for me. source: https://code.google.com/p/android/issues/detail?id=61844#c4
I had the same problem but mine worked fine. Turn off your firewall, antivirus. Make sure your port 80 is enabled and both pcs are set to be remotely accessed. In each pc under users, add new user using the host ip address of the other pc. Restart all services. Put your wampserver online. It should connect
IF you want more data in you confusion matrix, including "totals column" and "totals line", and percents (%) in each cell, like matlab default (see image below)
including the Heatmap and other options...
You should have fun with the module above, shared in the github ; )
https://github.com/wcipriano/pretty-print-confusion-matrix
This module can do your task easily and produces the output above with a lot of params to customize your CM:
I think your best bet here may be to define a single global-scoped variable, and dumping your variables there:
var MyApp = {}; // Globally scoped object
function foo(){
MyApp.color = 'green';
}
function bar(){
alert(MyApp.color); // Alerts 'green'
}
No one should yell at you for doing something like the above.
If you use a CSS sprite for the background images, you could bump the background offset +/- n pixels depending on whether you were expanding or collapsing. Not a toggle, but closer to it than having to switch background image URLs.
I solved problem for UTF8 using https://github.com/neitanod/forceutf8
use ForceUTF8\Encoding;
$string = Encoding::fixUTF8($string);
The reason to make an App with no activity or service could be making a Homescreen Widget app that doesn't need to be started.
Once you start a project don't create any activities. After you created the project just hit run. Android studio will say No default activity found
.
Click Edit Configuration (From the Run menu) and in the Launch option part set the Launch value to Nothing.
Then click ok and run the App.
(Since there is no launcher activity, No app will be show in the Apps menu.).
Gone through the already posted answers. Just thought it would be better if I add an answer with actual example.
Let' say you have 3 Django models which are related.
class M1(models.Model):
name = models.CharField(max_length=10)
class M2(models.Model):
name = models.CharField(max_length=10)
select_relation = models.ForeignKey(M1, on_delete=models.CASCADE)
prefetch_relation = models.ManyToManyField(to='M3')
class M3(models.Model):
name = models.CharField(max_length=10)
Here you can query M2
model and its relative M1
objects using select_relation
field and M3
objects using prefetch_relation
field.
However as we've mentioned M1
's relation from M2
is a ForeignKey
, it just returns only 1 record for any M2
object. Same thing applies for OneToOneField
as well.
But M3
's relation from M2
is a ManyToManyField
which might return any number of M1
objects.
Consider a case where you have 2 M2
objects m21
, m22
who have same 5 associated M3
objects with IDs 1,2,3,4,5
. When you fetch associated M3
objects for each of those M2
objects, if you use select related, this is how it's going to work.
Steps:
m21
object.M3
objects related to m21
object whose IDs are 1,2,3,4,5
.m22
object and all other M2
objects.As we have same 1,2,3,4,5
IDs for both m21
, m22
objects, if we use select_related option, it's going to query the DB twice for the same IDs which were already fetched.
Instead if you use prefetch_related, when you try to get M2
objects, it will make a note of all the IDs that your objects returned (Note: only the IDs) while querying M2
table and as last step, Django is going to make a query to M3
table with the set of all IDs that your M2
objects have returned. and join them to M2
objects using Python instead of database.
This way you're querying all the M3
objects only once which improves performance.
AF_INET = Address Format, Internet = IP Addresses
PF_INET = Packet Format, Internet = IP, TCP/IP or UDP/IP
AF_INET is the address family that is used for the socket you're creating (in this case an Internet Protocol address). The Linux kernel, for example, supports 29 other address families such as UNIX sockets and IPX, and also communications with IRDA and Bluetooth (AF_IRDA and AF_BLUETOOTH, but it is doubtful you'll use these at such a low level).
For the most part sticking with AF_INET for socket programming over a network is the safest option.
Meaning, AF_INET refers to addresses from the internet, IP addresses specifically.
PF_INET refers to anything in the protocol, usually sockets/ports.
I was getting the same UnicodeEncodeError
when saving scraped web content to a file. To fix it I replaced this code:
with open(fname, "w") as f:
f.write(html)
with this:
import io
with io.open(fname, "w", encoding="utf-8") as f:
f.write(html)
Using io
gives you backward compatibility with Python 2.
If you only need to support Python 3 you can use the builtin open
function instead:
with open(fname, "w", encoding="utf-8") as f:
f.write(html)
Rda is just a short name for RData. You can just save(), load(), attach(), etc. just like you do with RData.
Rds stores a single R object. Yet, beyond that simple explanation, there are several differences from a "standard" storage. Probably this R-manual Link to readRDS() function clarifies such distinctions sufficiently.
So, answering your questions:
From the link Jweede posted:
exception socket.timeout:
This exception is raised when a timeout occurs on a socket which has had timeouts enabled via a prior call to settimeout(). The accompanying value is a string whose value is currently always “timed out”.
Here are the demo server and client programs for the socket module from the python docs
# Echo server program
import socket
HOST = '' # Symbolic name meaning all available interfaces
PORT = 50007 # Arbitrary non-privileged port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(1)
conn, addr = s.accept()
print 'Connected by', addr
while 1:
data = conn.recv(1024)
if not data: break
conn.send(data)
conn.close()
And the client:
# Echo client program
import socket
HOST = 'daring.cwi.nl' # The remote host
PORT = 50007 # The same port as used by the server
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
s.send('Hello, world')
data = s.recv(1024)
s.close()
print 'Received', repr(data)
On the docs example page I pulled these from, there are more complex examples that employ this idea, but here is the simple answer:
Assuming you're writing the client program, just put all your code that uses the socket when it is at risk of being dropped, inside a try block...
try:
s.connect((HOST, PORT))
s.send("Hello, World!")
...
except socket.timeout:
# whatever you need to do when the connection is dropped
You may try to write app
in use
uppercase, so App
. Worked for me.
It may come when the API(you are consuming) is not sending the corresponding JSON. You may experience the response as 404 page or something like HTML/XML response.
You would need to decompile the apk as Davis suggested, can use tools such as apkTool , then if you need to change the source code you would need other tools to do that.
You would then need to put the apk back together and sign it, if you don't have the original key used to sign the apk this means the new apk will have a different signature.
If the developer employed any obfuscation or other techniques to protect the app then it gets more complicated.
In short its a pretty complex and technical procedure, so if the developer is really just out of reach, its better to wait until he is in reach. And ask for the source code next time.
I think it's local to the file you declared offset. Consider every file to be a method itself.
Maybe put the whole thing into a class and then make offset a class variable with @@offset = Point.new(100, 200);
?
Is http://api.xxx.com/
part of your domain? If not, you are being blocked by the same origin policy.
You may want to check out the following Stack Overflow post for a few possible workarounds:
At the time of writing, and as previously mentioned by @Bosh, html5mode
must be true
in order to be able to set $location.search()
and have it be reflected back into the window’s visual URL.
See https://github.com/angular/angular.js/issues/1521 for more info.
But if html5mode
is true
you can easily clear the URL’s query string with:
$location.search('');
or
$location.search({});
This will also alter the window’s visual URL.
(Tested in AngularJS version 1.3.0-rc.1
with html5Mode(true)
.)
Try this:
Custom formula is
=countif(A:A,A1)>1
(or change A
to your chosen column)A1:A100
).Anything written in the A1:A100 cells will be checked, and if there is a duplicate (occurs more than once) then it'll be coloured.
For locales using comma (,
) as a decimal separator, the argument separator is most likely a semi-colon (;
). That is, try: =countif(A:A;A1)>1
, instead.
For multiple columns, use countifs
.
Check with starting mysql in terminal. Use below command
mysql-ctl start
In my case its worked
Going further with the rev-list
option, if you want to find the most recent merge commit from your master branch into your production branch (as a purely hypothetical example):
git checkout `git rev-list -n 1 --merges --first-parent --before="2012-01-01" production`
I needed to find the code that was on the production servers as of a given date. This found it for me.
If you define operator<<
as a member function it will have a different decomposed syntax than if you used a non-member operator<<
. A non-member operator<<
is a binary operator, where a member operator<<
is a unary operator.
// Declarations
struct MyObj;
std::ostream& operator<<(std::ostream& os, const MyObj& myObj);
struct MyObj
{
// This is a member unary-operator, hence one argument
MyObj& operator<<(std::ostream& os) { os << *this; return *this; }
int value = 8;
};
// This is a non-member binary-operator, 2 arguments
std::ostream& operator<<(std::ostream& os, const MyObj& myObj)
{
return os << myObj.value;
}
So.... how do you really call them? Operators are odd in some ways, I'll challenge you to write the operator<<(...)
syntax in your head to make things make sense.
MyObj mo;
// Calling the unary operator
mo << std::cout;
// which decomposes to...
mo.operator<<(std::cout);
Or you could attempt to call the non-member binary operator:
MyObj mo;
// Calling the binary operator
std::cout << mo;
// which decomposes to...
operator<<(std::cout, mo);
You have no obligation to make these operators behave intuitively when you make them into member functions, you could define operator<<(int)
to left shift some member variable if you wanted to, understand that people may be a bit caught off guard, no matter how many comments you may write.
Almost lastly, there may be times where both decompositions for an operator call are valid, you may get into trouble here and we'll defer that conversation.
Lastly, note how odd it might be to write a unary member operator that is supposed to look like a binary operator (as you can make member operators virtual..... also attempting to not devolve and run down this path....)
struct MyObj
{
// Note that we now return the ostream
std::ostream& operator<<(std::ostream& os) { os << *this; return os; }
int value = 8;
};
This syntax will irritate many coders now....
MyObj mo;
mo << std::cout << "Words words words";
// this decomposes to...
mo.operator<<(std::cout) << "Words words words";
// ... or even further ...
operator<<(mo.operator<<(std::cout), "Words words words");
Note how the cout
is the second argument in the chain here.... odd right?
As part of my undergraduate CompSci degree, we were assigned the problem of finding optimal jvm flags for the Jikes research virtual machine. This was evaluated using the Dicappo benchmark suite which returns a time to the console. I wrote a distributed gentic alogirthm that switched these flags to improve the runtime of the benchmark suite, although it took days to run to compensate for hardware jitter affecting the results. The only problem was I didn't properly learn about the compiler theory (which was the intent of the assignment).
I could have seeded the initial population with the exisiting default flags, but what was interesting was that the algorithm found a very similar configuration to the O3 optimisation level (but was actually faster in many tests).
Edit: Also I wrote my own genetic algorithm framework in Python for the assignment, and just used the popen commands to run the various benchmarks, although if it wasn't an assessed assignment I would have looked at pyEvolve.
I may be late to the party, but this is something which bugged me for too long. In my experience, I would rather want to see which changes are pending than update my working copy and deal with those changes.
This goes in the ~/.gitconfig
file:
[alias]
diffpull=!git fetch && git diff HEAD..@{u}
It fetches the current branch, then does a diff between the working copy and this fetched branch. So you should only see the changes that would come with git pull
.
If you're using SSMS (or old school Enterprise Manager) to edit the table directly, press CTRL+0 to add a null.
I find the quickest way to locate a global function is simply:
System.out.println
System
is a class in the java.lang
package.
out
is a static
data member of the System
class and references a variable of the PrintStream
class.
You can change the value of a bool all you want. As for an if:
if randombool == True:
works, but you can also use:
if randombool:
If you want to test whether something is false you can use:
if randombool == False
but you can also use:
if not randombool:
If you want to look at the actual GNU implementation of those functions in C, check out the latest trunk of glibc. See the GNU C Library.
If the error you are facing is "unable to connect to remote server" as was mine, then it would benefit you to have this check as well in addition to the checks provided in the above comments.
I saw that there were 2 NUGET Package Sources from which the packages could be downloaded (within Tools->Nuget Package Manager->Packager Manager Settings). One of the Package Source's was not functioning and Nuget was trying to download from that source only.
Things fell into place once I changed the package source to download from: https://www.nuget.org/api/v2/ EXPLICTLY in the settings
Webkit browsers support the ability to add "stroke" to fonts. This bit of style makes fonts look thinner (assuming a white background):
-webkit-text-stroke: 2px white;
Example on codepen here: http://codepen.io/mackdoyle/pen/yrgEH Some people are using SVG for a cross-platform "stroke" solution: http://codepen.io/CrocoDillon/pen/dGIsK
I found this query which helped me find my locked table and query causing the issue.
SELECT L.request_session_id AS SPID,
DB_NAME(L.resource_database_id) AS DatabaseName,
O.Name AS LockedObjectName,
P.object_id AS LockedObjectId,
L.resource_type AS LockedResource,
L.request_mode AS LockType,
ST.text AS SqlStatementText,
ES.login_name AS LoginName,
ES.host_name AS HostName,
TST.is_user_transaction as IsUserTransaction,
AT.name as TransactionName,
CN.auth_scheme as AuthenticationMethod
FROM sys.dm_tran_locks L
JOIN sys.partitions P ON P.hobt_id = L.resource_associated_entity_id
JOIN sys.objects O ON O.object_id = P.object_id
JOIN sys.dm_exec_sessions ES ON ES.session_id = L.request_session_id
JOIN sys.dm_tran_session_transactions TST ON ES.session_id = TST.session_id
JOIN sys.dm_tran_active_transactions AT ON TST.transaction_id = AT.transaction_id
JOIN sys.dm_exec_connections CN ON CN.session_id = ES.session_id
CROSS APPLY sys.dm_exec_sql_text(CN.most_recent_sql_handle) AS ST
WHERE resource_database_id = db_id()
ORDER BY L.request_session_id
There's a change_column method, just execute it in your migration with datetime as a new type.
change_column(:my_table, :my_column, :my_new_type)
foreach($array as $item=>$values){
echo $values->filepath;
}
You can use :nth-child(N) CSS selector like :
table td:first-child {} //1
table td:nth-child(2) {} //2
table td:nth-child(3) {} //3
table td:last-child {} //4
You can determine if as certain word is found in a cell by using
If InStr(cell.Value, "Word1") > 0 Then
If Word1 is found in the string the InStr()
function will return the location of the first character of Word1 in the string.
Linq-to-SQL
It is provider it supports SQL Server only. It's a mapping technology to map SQL Server database tables to .NET objects. Is Microsoft's first attempt at an ORM - Object-Relational Mapper.
Linq-to-Entities
Is the same idea, but using Entity Framework in the background, as the ORM - again from Microsoft, It supporting multiple database main advantage of entity framework is developer can work on any database no need to learn syntax to perform any operation on different different databases
According to my personal experience Ef is better (if you have no idea about SQL) performance in LINQ is little bit faster as compare to EF reason LINQ language written in lambda.
While size(A,2)
is correct, I find it's much more readable to first define
rows = @(x) size(x,1);
cols = @(x) size(x,2);
and then use, for example, like this:
howManyColumns_in_A = cols(A)
howManyRows_in_A = rows(A)
It might appear as a small saving, but size(.., 1)
and size(.., 2)
must be some of the most commonly used functions, and they are not optimally readable as-is.
Safe navigation operator or Existential Operator or Null Propagation Operator is supported in Angular Template. Suppose you have Component class
myObj:any = {
doSomething: function () { console.log('doing something'); return 'doing something'; },
};
myArray:any;
constructor() { }
ngOnInit() {
this.myArray = [this.myObj];
}
You can use it in template html file as following:
<div>test-1: {{ myObj?.doSomething()}}</div>
<div>test-2: {{ myArray[0].doSomething()}}</div>
<div>test-3: {{ myArray[2]?.doSomething()}}</div>
If using Mule, below are the steps.
Follow below steps.
Enable streaming in the connector i.e. progressiveStreaming=2
Typecast DB2 returned CLOB to java.sql.Clob (IBM Supports this type cast)
Convert that to character stream (ASCII stream sometimes may not support some special characters). So you may to use getCharacterStream()
That will return a "reader" object which can be converted to "String" using common-io (IOUtils).
So in short, use groovy component and add below code.
clobTest = (java.sql.Clob)payload.field1
bodyText = clobTest.getCharacterStream()
targetString = org.apache.commons.io.IOUtils.toString(bodyText)
payload.PAYLOADHEADERS=targetString return payload
Note: Here I'm assuming "payload.field1" is holding clob data.
That's it!
Regards Naveen
var1 = var1 or 4
The only issue this might have is that if var1 is a falsey value, like False or 0 or [], it will choose 4 instead. That might be an issue.
Suppose the DataFrames you want to join are df1 and df2, and you are joining them on column 'a', then you have 2 methods
Method 1
df1.join(df2,'a','left_outer')
This is an awsome method and it is highly recommended.
Method 2
df1.join(df2,df1.a == df2.a,'left_outer').drop(df2.a)
You can use DISTINCT inside the COUNT like what milkovsky said
in my case:
select COUNT(distinct user_id) from answers_votes where answer_id in (694,695);
This will pull the count of answer votes considered the same user_id as one count
Be careful with this. There are a number of different 'contexts' within an HTML document: Inside an element, quoted attribute value, unquoted attribute value, URL attribute, javascript, CSS, etc... You'll need to use a different encoding method for each of these to prevent Cross-Site Scripting (XSS). Check the OWASP XSS Prevention Cheat Sheet for details on each of these contexts. You can find escaping methods for each of these contexts in the OWASP ESAPI library -- https://github.com/ESAPI/esapi-java-legacy.
angular.module('app').directive('conversation', function() {
return {
restrict: 'E',
link: function ($scope, $elm, $attr) {
$scope.$watch("some_prop", function (newValue, oldValue) {
var typeId = $attr.type-id;
// Your logic.
});
}
};
}
From APUE, Section 5.14 :
char good_template[] = "/tmp/dirXXXXXX"; /* right way */
char *bad_template = "/tmp/dirXXXXXX"; /* wrong way*/
... For the first template, the name is allocated on the stack, because we use an array variable. For the second name, however, we use a pointer. In this case, only the memory for the pointer itself resides on the stack; the compiler arranges for the string to be stored in the read-only segment of the executable. When the
mkstemp
function tries to modify the string, a segmentation fault occurs.
The quoted text matches @Ciro Santilli 's explanation.
function callServlet()
{
document.getElementById("adminForm").action="./Administrator";
document.getElementById("adminForm").method = "GET";
document.getElementById("adminForm").submit();
}
<button type="submit" onclick="callServlet()" align="center"> Register</button>
I can't reproduce this issue in a simple .NET 4.0 console application:
static class Program
{
static void Main(string[] args)
{
var myDict = new Dictionary<string, string>
{
{ "key1", "value1" },
{ "key2", "value2" }
};
Console.ReadKey();
}
}
Can you try to reproduce it in a simple Console application and go from there? It seems likely that you're targeting .NET 2.0 (which doesn't support it) or client profile framework, rather than a version of .NET that supports initialization syntax.
Although this isn't using the np array format, (to lazy to modify my code) this should do what you want... If, you truly want a column vector you will want to transpose the vector result. It all depends on how you are planning to use this.
def getVector(data_array,col):
vector = []
imax = len(data_array)
for i in range(imax):
vector.append(data_array[i][col])
return ( vector )
a = ([1,2,3], [4,5,6])
b = getVector(a,1)
print(b)
Out>[2,5]
So if you need to transpose, you can do something like this:
def transposeArray(data_array):
# need to test if this is a 1D array
# can't do a len(data_array[0]) if it's 1D
two_d = True
if isinstance(data_array[0], list):
dimx = len(data_array[0])
else:
dimx = 1
two_d = False
dimy = len(data_array)
# init output transposed array
data_array_t = [[0 for row in range(dimx)] for col in range(dimy)]
# fill output transposed array
for i in range(dimx):
for j in range(dimy):
if two_d:
data_array_t[j][i] = data_array[i][j]
else:
data_array_t[j][i] = data_array[j]
return data_array_t
Do you mean that for a select element with an id of "next" you need to perform some specific script?
$("#next").change(function(){
//enter code here
});
If anyone would like the answer in Swift :
var blurEffect = UIBlurEffect(style: UIBlurEffectStyle.Dark) // Change .Dark into .Light if you'd like.
var blurView = UIVisualEffectView(effect: blurEffect)
blurView.frame = theImage.bounds // 'theImage' is an image. I think you can apply this to the view too!
Update :
As of now, it's available under the IB so you don't have to code anything for it :)
Calling presentViewController
presents the view controller modally, outside the existing navigation stack; it is not contained by your UINavigationController or any other. If you want your new view controller to have a navigation bar, you have two main options:
Option 1. Push the new view controller onto your existing navigation stack, rather than presenting it modally:
let VC1 = self.storyboard!.instantiateViewControllerWithIdentifier("MyViewController") as! ViewController
self.navigationController!.pushViewController(VC1, animated: true)
Option 2. Embed your new view controller into a new navigation controller and present the new navigation controller modally:
let VC1 = self.storyboard!.instantiateViewControllerWithIdentifier("MyViewController") as! ViewController
let navController = UINavigationController(rootViewController: VC1) // Creating a navigation controller with VC1 at the root of the navigation stack.
self.present(navController, animated:true, completion: nil)
Bear in mind that this option won't automatically include a "back" button. You'll have to build in a close mechanism yourself.
Which one is best for you is a human interface design question, but it's normally clear what makes the most sense.
The only way would be to convert your text field into an nvarchar field.
Select Cast(notes as nvarchar(4000)) + 'SomeText'
From NotesTable a
Otherwise, I suggest doing the concatenation in your application.
I was looking for a resolution to this issue in Windows, and it seems to be that if you don't have the environments vars ok, you need to put the complete directory. For eg. with a file in the same directory than PHP:
F:\myfolder\php\php.exe -f F:\myfolder\php\script.php
try using math ceil function that makes rounding up. Math Ceil !
All of the functionality of our lightweight IDEs can be found within IntelliJ IDEA (you need to install the corresponding plug-ins from the repository).
It includes support for all technologies developed for our more specific products such as Web/PhpStorm, RubyMine and PyCharm.
The specific feature missing from IntelliJ IDEA is simplified project creation ("Open Directory") used in lighter products as it is not applicable to the IDE that support such a wide range of languages and technologies. It also means that you can't create projects directly from the remote hosts in IDEA.
If you are missing any other feature that is available in lighter products, but is not available in IntelliJ IDEA Ultimate, you are welcome to report it and we'll consider adding it.
While PHP, Python and Ruby IDEA plug-ins are built from the same source code as used in PhpStorm, PyCharm and RubyMine, product release cycles are not synchronized. It means that some features may be already available in the lighter products, but not available in IDEA plug-ins at certain periods, they are added with the plug-in and IDEA updates later.
The folder containing your Anaconda installation contains a subfolder called conda-meta
with json files for all installed packages, including one for Anaconda itself. Look for anaconda-<version>-<build>.json
.
My file is called anaconda-5.0.1-py27hdb50712_1.json
, and at the bottom is more info about the version:
"installed_by": "Anaconda2-5.0.1-Windows-x86_64.exe",
"link": { "source": "C:\\ProgramData\\Anaconda2\\pkgs\\anaconda-5.0.1-py27hdb50712_1" },
"name": "anaconda",
"platform": "win",
"subdir": "win-64",
"url": "https://repo.continuum.io/pkgs/main/win-64/anaconda-5.0.1-py27hdb50712_1.tar.bz2",
"version": "5.0.1"
(Slightly edited for brevity.)
The output from conda -V
is the conda version.
Here's another way: this adds a circle to the current axes, plot or image or whatever :
from matplotlib.patches import Circle # $matplotlib/patches.py
def circle( xy, radius, color="lightsteelblue", facecolor="none", alpha=1, ax=None ):
""" add a circle to ax= or current axes
"""
# from .../pylab_examples/ellipse_demo.py
e = Circle( xy=xy, radius=radius )
if ax is None:
ax = pl.gca() # ax = subplot( 1,1,1 )
ax.add_artist(e)
e.set_clip_box(ax.bbox)
e.set_edgecolor( color )
e.set_facecolor( facecolor ) # "none" not None
e.set_alpha( alpha )
(The circles in the picture get squashed to ellipses because imshow aspect="auto"
).
if you have array of object and you would like to deserialize them in compoent
get example() { this.arrayOfObject.map(i => JSON.stringify (i) ) };
then in template
<ul>
<li *ngFor="obj of example">{{obj}}</li>
</ul>
Instead of using "", use 0. Then use conditional formating to color 0 to the backgrounds color, so that it appears blank.
Since blank cells and 0 will have the same behavior in most situations, this may solve the issue.
I faced this issue, I was not able to copy zeppelin [1GB] directory into docker container and was getting issue
COPY failed: stat /var/lib/docker/tmp/docker-builder977188321/zeppelin-0.7.2-bin-all: no such file or directory
I am using docker Version: 17.09.0-ce and resolved the issue with the following steps.
Step 1: copy zeppelin directory [which i want to copy into docker package]into directory contain "Dockfile"
Step 2: edit Dockfile and add command [location where we want to copy] ADD ./zeppelin-0.7.2-bin-all /usr/local/
Step 3: go to directory which contain DockFile and run command [alternatives also available] docker build
Step 4: docker image created Successfully with logs
Step 5/9 : ADD ./zeppelin-0.7.2-bin-all /usr/local/ ---> 3691c902d9fe
Step 6/9 : WORKDIR $ZEPPELIN_HOME ---> 3adacfb024d8 .... Successfully built b67b9ea09f02
ActionListener gets fired first, with an option to modify the response, before Action gets called and determines the location of the next page.
If you have multiple buttons on the same page which should go to the same place but do slightly different things, you can use the same Action for each button, but use a different ActionListener to handle slightly different functionality.
Here is a link that describes the relationship:
function loadData(callback) {
//execute other requirement
if(callback && typeof callback == "function"){
callback();
}
}
loadData(function(){
//execute callback
});
As at MVC 5, if you wish to add any attributes you can simply do
@Html.EditorFor(m => m.Name, new { htmlAttributes = new { @required = "true", @anotherAttribute = "whatever" } })
Information found from this blog
If you have some image files, just upload them to a public folder on your Google Drive, copy its folder ID from the address bar (e.g. 0B0Gi4v5omoZUVXhCT2kta1l0ZG8) and paste it into a form at GDrives, then choose your own alias (e.g. myimgs) and voila! You can access the images one by one using e.g. http://gdriv.es/myimgs/myimage.jpg.
If you want to embed a whole folder on your website (in a frame), you can use one of the following URLs, replacing [folderID] with your own ID:
If you prefer to get the file list in XML or JSON, you can use YQL.
Note: You can use Google+ Photos to host ans embed your images as well.
I had the same error code when I used @Transaction
on a wrong method/actionlevel.
methodWithANumberOfDatabaseActions() {
methodA( ...)
methodA( ...)
}
@Transactional
void methodA( ...) {
... ERROR message
}
I had to place the @Transactional
just above the method methodWithANumberOfDatabaseActions()
, of course.
That solved the error message in my case.
C++11 override
keyword when used with the function declaration inside the derived class, it forces the compiler to check that the declared function is actually overriding some base class function. Otherwise, the compiler will throw an error.
Hence you can use override
specifier to ensure dynamic polymorphism (function overriding).
class derived: public base{
public:
virtual void func_name(int var_name) override {
// statement
}
};
Do you have something against splitting it up?
...FROM <blah>
WHERE
(fieldA LIKE '%THIS%' OR fieldA LIKE '%THAT%')
AND something = else
There are two kinds of cascades in Doctrine:
1) ORM level - uses cascade={"remove"}
in the association - this is a calculation that is done in the UnitOfWork and does not affect the database structure. When you remove an object, the UnitOfWork will iterate over all objects in the association and remove them.
2) Database level - uses onDelete="CASCADE"
on the association's joinColumn - this will add On Delete Cascade to the foreign key column in the database:
@ORM\JoinColumn(name="father_id", referencedColumnName="id", onDelete="CASCADE")
I also want to point out that the way you have your cascade={"remove"} right now, if you delete a Child object, this cascade will remove the Parent object. Clearly not what you want.
As always when you ask about fastest: Measure! Using the Methods above (on a Mac using Clang):
Method | executable size | Time Taken (in sec) |
| -O0 | -O3 | -O0 | -O3 |
------------|---------|---------|-----------|----------|
1. memset | 17 kB | 8.6 kB | 0.125 | 0.124 |
2. fill | 19 kB | 8.6 kB | 13.4 | 0.124 |
3. manual | 19 kB | 8.6 kB | 14.5 | 0.124 |
4. assign | 24 kB | 9.0 kB | 1.9 | 0.591 |
using 100000 iterations on an vector of 10000 ints.
Edit: If changeing this numbers plausibly changes the resulting times you can have some confidence (not as good as inspecting the final assembly code) that the artificial benchmark has not been optimized away entirely. Of course it is best to messure the performance under real conditions. end Edit
for reference the used code:
#include <vector>
#define TEST_METHOD 1
const size_t TEST_ITERATIONS = 100000;
const size_t TEST_ARRAY_SIZE = 10000;
int main(int argc, char** argv) {
std::vector<int> v(TEST_ARRAY_SIZE, 0);
for(size_t i = 0; i < TEST_ITERATIONS; ++i) {
#if TEST_METHOD == 1
memset(&v[0], 0, v.size() * sizeof v[0]);
#elif TEST_METHOD == 2
std::fill(v.begin(), v.end(), 0);
#elif TEST_METHOD == 3
for (std::vector<int>::iterator it=v.begin(), end=v.end(); it!=end; ++it) {
*it = 0;
}
#elif TEST_METHOD == 4
v.assign(v.size(),0);
#endif
}
return EXIT_SUCCESS;
}
Conclusion: use std::fill
(because, as others have said its most idiomatic)!
On Linux it's Monospace
10 pt. (the exact monospace font used may vary on different Linux distributions or versions), on Windows it's Consolas
10 pt., and on OS X it's Menlo Regular
12 pt.
(The color scheme is Neon
, the syntax highlighting is from PackageDev
, and the font is Liberation Mono
This information is found in the Packages/Default
directory (where Packages
is the directory opened by the Preferences ? Browse Packages...
menu option), in the Preferences (OS).sublime-settings
file where OS
is one of Windows
, Linux
, or OSX
.
You should only customize the font (or any other setting) in Packages/User/Preferences.sublime-settings
, opened by Preferences ? Settings—User
, as Settings—Default
is over-written on upgrade, and also serves as a backup in case you really screw something up in your user settings. This is the case for both the main Sublime settings as well as those for extra packages/plugins.
These default fonts are the same in Sublime Text 2, Sublime Text 3, and the new version currently in development.
If you want to round off then use the round function. Use ceiling function when you want to get the smallest integer just greater than your argument.
For ex: select round(843.4923423423,0) from dual gives you 843 and
select round(843.6923423423,0) from dual gives you 844
What about constructing the element using jQuery? e.g.
$("<div></div>")
creates a new div element, ready to be added to the page. Can be shortened further to
$("<div>")
then you can chain on commands that you need, set up event handlers and append it to the DOM. For example
$('<div id="myid">Div Content</div>')
.bind('click', function(e) { /* event handler here */ })
.appendTo('#myOtherDiv');
Use atoi() from <stdlib.h>
http://linux.die.net/man/3/atoi
Or, write your own atoi()
function which will convert char*
to int
int a2i(const char *s)
{
int sign=1;
if(*s == '-'){
sign = -1;
s++;
}
int num=0;
while(*s){
num=((*s)-'0')+num*10;
s++;
}
return num*sign;
}
If your ISP/hosting service has installed ImageMagick and put its location in the PATH environment variable, you can find what versions are installed and where using:
<?php
echo "<pre>";
system("type -a convert");
echo "</pre>";
?>
in
wins hands-down, not just in elegance (and not being deprecated;-) but also in performance, e.g.:
$ python -mtimeit -s'd=dict.fromkeys(range(99))' '12 in d'
10000000 loops, best of 3: 0.0983 usec per loop
$ python -mtimeit -s'd=dict.fromkeys(range(99))' 'd.has_key(12)'
1000000 loops, best of 3: 0.21 usec per loop
While the following observation is not always true, you'll notice that usually, in Python, the faster solution is more elegant and Pythonic; that's why -mtimeit
is SO helpful -- it's not just about saving a hundred nanoseconds here and there!-)
You can't decode a unicode
, and you can't encode a str
. Try doing it the other way around.
Angular 4 empty data if else
if(this.data == 0)
{
alert("Null data");
}
else
{
//some logic
}
Which Mac version are you using? try these paths
/System/Library/Frameworks/JavaVM.framework/ OR
/usr/libexec/java_home
This link might help - How To Set $JAVA_HOME Environment Variable On Mac OS X
Source from: http://getbootstrap.com/getting-started/#disable-responsive
<meta>
mentioned in the CSS docswidth
on the .container
for each grid tier with a single width, for example width: 970px !important;
Be sure that this comes after the default Bootstrap CSS. You can optionally avoid the !important
with media queries or some selector-fu..col-xs-*
classes in addition to, or in place of, the medium/large ones. Don't worry, the extra-small device grid scales to all resolutions.Not 100% sure as the question is missing some details but if you are using JAX-WS RI, then have a look at Adding SOAP headers when sending requests:
The portable way of doing this is that you create a
SOAPHandler
and mess with SAAJ, but the RI provides a better way of doing this.When you create a proxy or dispatch object, they implement
BindingProvider
interface. When you use the JAX-WS RI, you can downcast toWSBindingProvider
which defines a few more methods provided only by the JAX-WS RI.This interface lets you set an arbitrary number of Header object, each representing a SOAP header. You can implement it on your own if you want, but most likely you'd use one of the factory methods defined on
Headers
class to create one.import com.sun.xml.ws.developer.WSBindingProvider; HelloPort port = helloService.getHelloPort(); // or something like that... WSBindingProvider bp = (WSBindingProvider)port; bp.setOutboundHeader( // simple string value as a header, like <simpleHeader>stringValue</simpleHeader> Headers.create(new QName("simpleHeader"),"stringValue"), // create a header from JAXB object Headers.create(jaxbContext,myJaxbObject) );
Update your code accordingly and try again. And if you're not using JAX-WS RI, please update your question and provide more context information.
Update: It appears that the web service you want to call is secured with WS-Security/UsernameTokens. This is a bit different from your initial question. Anyway, to configure your client to send usernames and passwords, I suggest to check the great post Implementing the WS-Security UsernameToken Profile for Metro-based web services (jump to step 4). Using NetBeans for this step might ease things a lot.
One more place where this can go wrong is in the project specific settings, in Eclipse.
project properties: click your project and one of the following:
click on "Java Compiler"
Because of client requirements we had them enabled to keep our projects in 1.6. When it was needed to upgrade to 1.7, we had a hard time because we needed to change the java version all over the place:
Here is a complete example showing how to use the **
operator to pass values from a dictionary as keyword arguments.
>>> def f(x=2):
... print(x)
...
>>> new_x = {'x': 4}
>>> f() # default value x=2
2
>>> f(x=3) # explicit value x=3
3
>>> f(**new_x) # dictionary value x=4
4
Primary keys always need to be unique, foreign keys need to allow non-unique values if the table is a one-to-many relationship. It is perfectly fine to use a foreign key as the primary key if the table is connected by a one-to-one relationship, not a one-to-many relationship. If you want the same user record to have the possibility of having more than 1 related profile record, go with a separate primary key, otherwise stick with what you have.
Try this. Just pass in the param you want to remove from the URL and the original URL value, and the function will strip it out for you.
function removeParam(key, sourceURL) {
var rtn = sourceURL.split("?")[0],
param,
params_arr = [],
queryString = (sourceURL.indexOf("?") !== -1) ? sourceURL.split("?")[1] : "";
if (queryString !== "") {
params_arr = queryString.split("&");
for (var i = params_arr.length - 1; i >= 0; i -= 1) {
param = params_arr[i].split("=")[0];
if (param === key) {
params_arr.splice(i, 1);
}
}
if (params_arr.length) rtn = rtn + "?" + params_arr.join("&");
}
return rtn;
}
To use it, simply do something like this:
var originalURL = "http://yourewebsite.com?id=10&color_id=1";
var alteredURL = removeParam("color_id", originalURL);
The var alteredURL
will be the output you desire.
Hope it helps!
This works with all objects and arrays :)
ex:
if( obj._has( "something.['deep']['under'][1][0].item" ) ) {
//do something
}
this is my improved version of Brian's answer
I used _has as the property name because it can conflict with existing has property (ex: maps)
Object.defineProperty( Object.prototype, "_has", { value: function( needle ) {
var obj = this;
var needles = needle.split( "." );
var needles_full=[];
var needles_square;
for( var i = 0; i<needles.length; i++ ) {
needles_square = needles[i].split( "[" );
if(needles_square.length>1){
for( var j = 0; j<needles_square.length; j++ ) {
if(needles_square[j].length){
needles_full.push(needles_square[j]);
}
}
}else{
needles_full.push(needles[i]);
}
}
for( var i = 0; i<needles_full.length; i++ ) {
var res = needles_full[i].match(/^((\d+)|"(.+)"|'(.+)')\]$/);
if (res != null) {
for (var j = 0; j < res.length; j++) {
if (res[j] != undefined) {
needles_full[i] = res[j];
}
}
}
if( typeof obj[needles_full[i]]=='undefined') {
return false;
}
obj = obj[needles_full[i]];
}
return true;
}});
Here's the fiddle
I'm using Tomcat through XAMPP which might have been the cause of this problem. When I changed appBase="C:/Java Project/"
, for example, I kept getting "This localhost page can't be found"
in the browser.
I had to add a folder called ROOT inside the Java Project folder and then it worked. Any files you're working on have to be inside this ROOT folder but you need to leave appBase="C:/Java Project/"
as changing it to appBase="C:/Java Project/ROOT"
will cause "This localhost page can't be found"
to be displayed again.
Maybe needing the ROOT folder is obvious to more experienced Java developers but it wasn't for me so hopefully this helps anyone else encountering the same problem.
Follow these steps if you're on openSuse or SUSE.
Install php7 if it's not already installed.
zypper in php7
If you have php7 installed, update it with:
zypper update php7
Install php7-sockets
zypper in php7-sockets
Make sure your Facebook application is published. In order to receive data for email, public_profile and user_friends your app must be made available to public.
You can disable it later for development purposes and still get email field.
Here's another way of doing it, add in app\Providers\AppServiceProvider.php
use Illuminate\Support\Str;
...
public function boot()
{
// add Str::currency macro
Str::macro('currency', function ($price)
{
return number_format($price, 2, '.', '\'');
});
}
Then use Str::currency() in the blade templates or directly in the Expense model.
@foreach ($Expenses as $Expense)
<tr>
<td>{{{ $Expense->type }}}</td>
<td>{{{ $Expense->narration }}}</td>
<td>{{{ Str::currency($Expense->price) }}}</td>
<td>{{{ $Expense->quantity }}}</td>
<td>{{{ Str::currency($Expense->amount) }}}</td>
</tr>
@endforeach
Write below code in your MainActivity.java file instead of your code.
public class MainActivity extends Activity implements OnClickListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button mBtn1 = (Button) findViewById(R.id.mBtn1);
mBtn1.setOnClickListener(this);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
@Override
public void onClick(View v) {
Log.i("clicks","You Clicked B1");
Intent i=new Intent(MainActivity.this, MainActivity2.class);
startActivity(i);
}
}
And Declare MainActivity2 into your Androidmanifest.xml file using below code.
<activity
android:name=".MainActivity2"
android:label="@string/title_activity_main">
</activity>
"Windows could not start the Apache Tomcat 6 on Local Computer. For more information, review the System Event Log. If this is a non-Microsoft service, contact the service vendor, and refer to service-specific error code 0"
When an error of this sort come. please go to start -> configure tomcat -> startup -> Mode -> java similarly start -> configure tomcat -> shutdown -> Mode -> java
You can simple use a function:
function hello() {
alert("RINSE");
alert("LATHER");
hello();
}
Here is the complete xml with gradient, stoke & circular shape.
<?xml version="1.0" encoding="utf-8"?>
<shape
xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval" >
<!-- You can use gradient with below attributes-->
<gradient
android:angle="90"
android:centerColor="#555994"
android:endColor="#b5b6d2"
android:startColor="#555994"
android:type="linear" />
<!-- You can omit below tag if you don't need stroke -->
<stroke android:color="#3b91d7" android:width="5dp"/>
<!-- Set the same value for both width and height to get a circular shape -->
<size android:width="200dp" android:height="200dp"/>
<!--if you need only a single color filled shape-->
<solid android:color="#e42828"/>
</shape>
If you are using vue-router
, you should use router.go(path)
to navigate to any particular route. The router can be accessed from within a component using this.$router
.
Otherwise, window.location.href = 'some url';
works fine for non single-page apps.
EDIT: router.go()
changed in VueJS 2.0. You can use router.push({ name: "yourroutename"})
or just router.push("yourroutename")
now to redirect.
P.S: In controllers use: this.$router.push({ name: 'routename' })
********** Easiest way for Xcode 11 and above ***********
Add this to info.plist before </dict></plist>
<key>UIUserInterfaceStyle</key>
<string>Light</string>
There you go:
String tempNames = jsonObj.names().toString();
String[] types = tempNames.substring(1, tempNames.length()-1).split(","); //remove [ and ] , then split by ','
They are already in arrays: $name
is an array, as is $email
So all you need to do is add a bit of processing to attack both arrays:
$name = $_POST['name'];
$email = $_POST['account'];
foreach( $name as $key => $n ) {
print "The name is ".$n." and email is ".$email[$key].", thank you\n";
}
To handle more inputs, just extend the pattern:
$name = $_POST['name'];
$email = $_POST['account'];
$location = $_POST['location'];
foreach( $name as $key => $n ) {
print "The name is ".$n.", email is ".$email[$key].
", and location is ".$location[$key].". Thank you\n";
}
My solution is modify or make new AndroidManifest.xml in android/app/src/debug:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
<application android:usesCleartextTraffic="true" tools:targetApi="28" tools:ignore="GoogleAppIndexingWarning" />
</manifest>
I am using React Native version: 0.61.5
You can use DbContext.Database.CommandTimeout = 180; // seconds
It's pretty simple and no cast required.
Remember that .text()
strips out markup, thus I don't believe you're going to find
in a non-markup result.
Made in to an answer....
var p = $('<p>').html(' ');
if (p.text() == String.fromCharCode(160) && p.text() == '\xA0')
alert('Character 160');
Shows an alert, as the ASCII equivalent of the markup is returned instead.
There is no need to know where the files are, because when you launch a bat file the working directory is the directory where it was launched (the "master folder"), so if you have this structure:
.\mydocuments\folder\mybat.bat
.\mydocuments\folder\subfolder\file.txt
And the user starts the "mybat.bat", the working directory is ".\mydocuments\folder", so you only need to write the subfolder name in your script:
@Echo OFF
REM Do anything with ".\Subfolder\File1.txt"
PUSHD ".\Subfolder"
Type "File1.txt"
Pause&Exit
Anyway, the working directory is stored in the "%CD%" variable, and the directory where the bat was launched is stored on the argument 0. Then if you want to know the working directory on any computer you can do:
@Echo OFF
Echo Launch dir: "%~dp0"
Echo Current dir: "%CD%"
Pause&Exit
Type in your URL localhost/[name of your folder in htdocs]
http://en.wikipedia.org/wiki/Stirling%27s_approximation Stirling approximation might help you. It is really helpful in dealing with problems on factorials related to huge numbers of the order of 10^10 and above.
I know you wanted "free", but I'd seriously consider getting the data from csidata.com for about $300/year, if I were you.
It's what yahoo uses to supply their data.
It comes with a decent API, and the data is (as far as I can tell) very clean.
You get 10 years of history when you subscribe, and then nightly updates afterward.
They also take care of all sorts of nasty things like splits and dividends for you. If you haven't yet discovered the joy that is data-cleaning, you won't realize how much you need this, until the first time your ATS (Automated Trading System) thinks some stock is really really cheap, only because it split 2:1 and you didn't notice.
.get responses are cached by default. Therefore you really need to do nothing to get the desired results.
I have to disagree one of the comments in one point:
[ "$x" == "valid" ] && echo "valid" || echo "invalid"
It's just it looks like one to, hmm, the uninitiated...
It uses common patterns as a language, in a way;
And after you learned the language.
It is a simple logical expression, with one special part: lazy evaluation of the logic operators.
[ "$x" == "valid" ] && echo "valid" || echo "invalid"
Each part is a logical expression; the first may be true or false, the other two are always true.
(
[ "$x" == "valid" ]
&&
echo "valid"
)
||
echo "invalid"
Now, when it is evaluated, the first is checked. If it is false, than the second operand of the logic and &&
after it is not relevant. The first is not true, so it can not be the first and the second be true, anyway.
Now, in this case is the the first side of the logic or ||
false, but it could be true if the other side - the third part - is true.
So the third part will be evaluated - mainly writing the message as a side effect. (It has the result 0
for true, which we do not use here)
The other cases are similar, but simpler - and - I promise! are - can be - easy to read!
(I don't have one, but I think being a UNIX veteran with grey beard helps a lot with this.)
We can also do in-place remove all using either del
or pop
:
import random
def remove_values_from_list(lst, target):
if type(lst) != list:
return lst
i = 0
while i < len(lst):
if lst[i] == target:
lst.pop(i) # length decreased by 1 already
else:
i += 1
return lst
remove_values_from_list(None, 2)
remove_values_from_list([], 2)
remove_values_from_list([1, 2, 3, 4, 2, 2, 3], 2)
lst = remove_values_from_list([random.randrange(0, 10) for x in range(1000000)], 2)
print(len(lst))
Now for the efficiency:
In [21]: %timeit -n1 -r1 x = random.randrange(0,10)
1 loop, best of 1: 43.5 us per loop
In [22]: %timeit -n1 -r1 lst = [random.randrange(0, 10) for x in range(1000000)]
g1 loop, best of 1: 660 ms per loop
In [23]: %timeit -n1 -r1 lst = remove_values_from_list([random.randrange(0, 10) for x in range(1000000)]
...: , random.randrange(0,10))
1 loop, best of 1: 11.5 s per loop
In [27]: %timeit -n1 -r1 x = random.randrange(0,10); lst = [a for a in [random.randrange(0, 10) for x in
...: range(1000000)] if x != a]
1 loop, best of 1: 710 ms per loop
As we see that in-place version remove_values_from_list()
does not require any extra memory, but it does take so much more time to run:
Here is a Github link to a lightweight and very easy to integrate library that enables you to play with borders as you want for any widget you want, simply based on a FrameLayout widget.
Here is a quick sample code for you to see how easy it is, but you will find more information on the link.
<com.khandelwal.library.view.BorderFrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
app:leftBorderColor="#00F0F0"
app:leftBorderWidth="10dp"
app:topBorderColor="#F0F000"
app:topBorderWidth="15dp"
app:rightBorderColor="#F000F0"
app:rightBorderWidth="20dp"
app:bottomBorderColor="#000000"
app:bottomBorderWidth="25dp" >
</com.khandelwal.library.view.BorderFrameLayout>
So, if you don't want borders on bottom, delete the two lines about bottom in this custom widget, and that's done.
And no, I'm neither the author of this library nor one of his friend ;-)
After doing what's referred in [this answer]: https://stackoverflow.com/a/24592192/82788
Select the module(since it's still visible on the Project view),pressing Delete button on the keyboard can delete this module on disk.(Before doing what's referred in that answer, the Delete button has no effect.)
$mydatetime = "2012-04-02 02:57:54";
$datetimearray = explode(" ", $mydatetime);
$date = $datetimearray[0];
$time = $datetimearray[1];
$reformatted_date = date('d-m-Y',strtotime($date));
$reformatted_time = date('Gi.s',strtotime($time));
In C++ you can overload operator<<
for ostream
and your custom class:
class A {
public:
int i;
};
std::ostream& operator<<(std::ostream &strm, const A &a) {
return strm << "A(" << a.i << ")";
}
This way you can output instances of your class on streams:
A x = ...;
std::cout << x << std::endl;
In case your operator<<
wants to print out internals of class A
and really needs access to its private and protected members you could also declare it as a friend function:
class A {
private:
friend std::ostream& operator<<(std::ostream&, const A&);
int j;
};
std::ostream& operator<<(std::ostream &strm, const A &a) {
return strm << "A(" << a.j << ")";
}
Also websocket scope is added:
Scopes a single bean definition to the lifecycle of a WebSocket. Only valid in the context of a web-aware Spring ApplicationContext.
As the per the content of the documentation, there is also thread scope, that is not registered by default.
I think the simplest way might be:
values.reduce(function(a, b){return a+b;})
There are already many answers to this question, and most of them are based on the similar custom directive idea. The problem with this approach is that one have to pass a method function to the directive, and cannot directly write code as in other events.
I created a new package vue-on-clickout
that is different. Check it out at:
It allows one to write v-on:clickout
just like any other events. For example, you can write
<div v-on:clickout="myField=value" v-on:click="myField=otherValue">...</div>
and it works.
vue-on-clickout
now supports Vue 3!
vue-on-clickout
is now replaced by a new package Clickout-Event
which works for any front-end framework (or vanilla)!
Can with defaulth value (T-SQL)
ALTER TABLE
Regions
ADD
HasPhotoInReadyStorage BIT NULL, --this column is nullable
HasPhotoInWorkStorage BIT NOT NULL, --this column is not nullable
HasPhotoInMaterialStorage BIT NOT NULL DEFAULT(0) --this column default value is false
GO
Solves the above problem, It solved mine!
HydTechie
in O(m+n)
complexity
def merge_sorted_list(nums1: list, nums2:list) -> list:
m = len(nums1)
n = len(nums2)
nums1 = nums1.copy()
nums2 = nums2.copy()
nums1.extend([0 for i in range(n)])
while m > 0 and n > 0:
if nums1[m-1] >= nums2[n-1]:
nums1[m+n-1] = nums1[m-1]
m -= 1
else:
nums1[m+n-1] = nums2[n-1]
n -= 1
if n > 0:
nums1[:n] = nums2[:n]
return nums1
l1 = [1, 3, 4, 7]
l2 = [0, 2, 5, 6, 8, 9]
print(merge_sorted_list(l1, l2))
output
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
I also bump into kind of problem, all I just had to do is delete the .dll (can be found in reference) that causing the error and add it again.
Works like a charm.
From that error, I would say that your code is fine, at least the part that calls the webservice. The error seems to be in the actual web service.
To get the error from the web server, add a try catch and catch a WebException. A WebException has a property called Response which is a HttpResponse. you can then log anything that is returned, and upload you code. Check back later in the logs and see what is actually being returned.
function formatTime(date){
d = new Date(date);
var h=d.getHours(),m=d.getMinutes(),l="AM";
if(h > 12){
h = h - 12;
}
if(h < 10){
h = '0'+h;
}
if(m < 10){
m = '0'+m;
}
if(d.getHours() >= 12){
l="PM"
}else{
l="AM"
}
return h+':'+m+' '+l;
}
Usage & result:
var formattedTime=formatTime(new Date('2020 15:00'));
// Output: "03:00 PM"
Underscore.js is great for this kind of thing. You can use _.countBy()
to get the counts per name
:
data = [{"id":11,"name":"ajax","subject":"OR","mark":63},
{"id":12,"name":"javascript","subject":"OR","mark":63},
{"id":13,"name":"jquery","subject":"OR","mark":63},
{"id":14,"name":"ajax","subject":"OR","mark":63},
{"id":15,"name":"jquery","subject":"OR","mark":63},
{"id":16,"name":"ajax","subject":"OR","mark":63},
{"id":20,"name":"ajax","subject":"OR","mark":63}]
_.countBy(data, function(data) { return data.name; });
Gives:
{ajax: 4, javascript: 1, jquery: 2}
For an array of the keys just use _.keys()
_.keys(_.countBy(data, function(data) { return data.name; }));
Gives:
["ajax", "javascript", "jquery"]
If you're using Eclipse Collections, you can use the anySatisfy()
method. Either adapt your List
in a ListAdapter
or change your List
into a ListIterable
if possible.
ListIterable<MyObject> list = ...;
boolean result =
list.anySatisfy(myObject -> myObject.getName().equals("John"));
If you'll do operations like this frequently, it's better to extract a method which answers whether the type has the attribute.
public class MyObject
{
private final String name;
public MyObject(String name)
{
this.name = name;
}
public boolean named(String name)
{
return Objects.equals(this.name, name);
}
}
You can use the alternate form anySatisfyWith()
together with a method reference.
boolean result = list.anySatisfyWith(MyObject::named, "John");
If you cannot change your List
into a ListIterable
, here's how you'd use ListAdapter
.
boolean result =
ListAdapter.adapt(list).anySatisfyWith(MyObject::named, "John");
Note: I am a committer for Eclipse ollections.
I just done multi level sorting based on custom requirement.
//sort the values
[arrItem sortUsingComparator:^NSComparisonResult (id a, id b){
ItemDetail * itemA = (ItemDetail*)a;
ItemDetail* itemB =(ItemDetail*)b;
//item price are same
if (itemA.m_price.m_selling== itemB.m_price.m_selling) {
NSComparisonResult result= [itemA.m_itemName compare:itemB.m_itemName];
//if item names are same, then monogramminginfo has to come before the non monograme item
if (result==NSOrderedSame) {
if (itemA.m_monogrammingInfo) {
return NSOrderedAscending;
}else{
return NSOrderedDescending;
}
}
return result;
}
//asscending order
return itemA.m_price.m_selling > itemB.m_price.m_selling;
}];
https://sites.google.com/site/greateindiaclub/mobil-apps/ios/multilevelsortinginiosobjectivec
Take a look at the approach this question used:
How do I detect a click outside an element?
Attach a click event to the document body which closes the window. Attach a separate click event to the window which stops propagation to the document body.
$('html').click(function() {
//Hide the menus if visible
});
$('#menucontainer').click(function(event){
event.stopPropagation();
});
It's a lambda expression.
It means that, from the listOfCars, arg0 is one of the items of that list. With that item he is going to do, hence the ->, whatever is inside of the brackets.
In this example, he's going to return a list of cars that fit the condition
Car.SEDAN == ((Car)arg0).getStyle();
Use $ne
instead of $not
http://docs.mongodb.org/manual/reference/operator/ne/#op._S_ne
db.collections.find({"name": {$ne: ""}});
It may be considered quick and dirty, but my own personal preference is to use a function/method like this:
public function getVarName($var) {
$tmp = array($var => '');
$keys = array_keys($tmp);
return trim($keys[0]);
}
basically it just creates an associative array containing one null/empty element, using as a key the variable for which you want the name.
we then get the value of that key using array_keys and return it.
obviously this gets messy quick and wouldn't be desirable in a production environment, but it works for the problem presented.
A variant of @YannDroneaud answer valid for x==1
, only for x86 plateforms, compilers, gcc or clang:
__attribute__ ((const))
static inline uint32_t p2(uint32_t x)
{
#if 0
assert(x > 0);
assert(x <= ((UINT32_MAX/2) + 1));
#endif
int clz;
uint32_t xm1 = x-1;
asm(
"lzcnt %1,%0"
:"=r" (clz)
:"rm" (xm1)
:"cc"
);
return 1 << (32 - clz);
}
Simply changing HTTP to HTTPS solved this issue for me.
WRONG :
<script src="http://code.jquery.com/jquery-3.5.1.js"></script>
CORRECT :
<script src="https://code.jquery.com/jquery-3.5.1.js"></script>
array_values does the job :
$myArray = array_values($myArray);
Also some other php function do not preserve the keys, i.e. reset the index.
All javascript methods are applicable with angularjs because angularjs itself is a javascript framework so you can use indexOf() inside angular directives
<li ng-repeat="select in Items">
<foo ng-repeat="newin select.values">
<span ng-if="newin.label.indexOf(x) !== -1">{{newin.label}}</span></foo>
</li>
//where x is your character to be found
if you are just getting a single value out of either (not in a loop) then both do bounds checking (you're in managed code remember) it's just the list does it twice. See the notes later for why this is likely not a big deal.
If you are using your own for(int int i = 0; i < x.[Length/Count];i++) then the key difference is as follows:
If you are using foreach then the key difference is as follows:
The bounds checking is often no big deal (especially if you are on a cpu with a deep pipeline and branch prediction - the norm for most these days) but only your own profiling can tell you if that is an issue. If you are in parts of your code where you are avoiding heap allocations (good examples are libraries or in hashcode implementations) then ensuring the variable is typed as List not IList will avoid that pitfall. As always profile if it matters.
VLOOKUP deosnt work for String literals
If this is a record of possible occurences of this error then:
I just got this error on WAS (8.5.0.1), during the CXF (2.6.0) loading of the spring (3.1.1_release) configuration where a BeanInstantiationException rolled up a CXF ExtensionException, rolling up a IncompatibleClassChangeError. The following snippet shows the gist of the stack trace:
Caused by: org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [org.apache.cxf.bus.spring.SpringBus]: Constructor threw exception; nested exception is org.apache.cxf.bus.extension.ExtensionException
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:162)
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:76)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:990)
... 116 more
Caused by: org.apache.cxf.bus.extension.ExtensionException
at org.apache.cxf.bus.extension.Extension.tryClass(Extension.java:167)
at org.apache.cxf.bus.extension.Extension.getClassObject(Extension.java:179)
at org.apache.cxf.bus.extension.ExtensionManagerImpl.activateAllByType(ExtensionManagerImpl.java:138)
at org.apache.cxf.bus.extension.ExtensionManagerBus.<init>(ExtensionManagerBus.java:131)
[etc...]
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:147)
... 118 more
Caused by: java.lang.IncompatibleClassChangeError:
org.apache.neethi.AssertionBuilderFactory
at java.lang.ClassLoader.defineClassImpl(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:284)
[etc...]
at com.ibm.ws.classloader.CompoundClassLoader.loadClass(CompoundClassLoader.java:586)
at java.lang.ClassLoader.loadClass(ClassLoader.java:658)
at org.apache.cxf.bus.extension.Extension.tryClass(Extension.java:163)
... 128 more
In this case, the solution was to change the classpath order of the module in my war file. That is, open up the war application in the WAS console under and select the client module(s). In the module configuration, set the class-loading to be "parent last".
This is found in the WAS console:
To answer your updated question you can do
String[] lines = ("Name = Bob\n" +
"Age = 27\n" +
"Occupation = Student\n" +
"Status = Single").split("\n");
for (String line : lines) {
String[] parts = line.split(" = +");
System.out.printf("%-19s %s%n", parts[0] + " =", parts[1]);
}
prints
Name = Bob
Age = 27
Occupation = Student
Status = Single
you can do a multi div layout like this
<div class="fieldcontainer">
<div class="label"></div>
<div class="field"></div>
</div>
where .fieldcontainer { clear: both; } .label { float: left; width: ___ } .field { float: left; }
Or, I actually prefer tables for forms like this. This is very much tabular data and it comes out very clean. Both will work though.
Two things:
Use offset()
function of jQuery
. Here it would be:
$container.offset({
'left': 100,
'top': mouse.y - ( event_state.mouse_y - event_state.container_top )
});
You can access the inactive tags array with (assuming $myArray contains the array)
$myArray['inactiveTags'];
Your question doesn't seem to go beyond accessing the contents of the inactiveTags key so I can only speculate with what your final goal is.
The first key:value pair in the inactiveTags array is
array ('195' => array(
'id' => 195,
'tag' => 'auto')
)
To access the tag value, you would use
$myArray['inactiveTags'][195]['tag']; // auto
If you want to loop through each inactiveTags element, I would suggest:
foreach($myArray['inactiveTags'] as $value) {
print $value['id'];
print $value['tag'];
}
This will print all the id and tag values for each inactiveTag
Edit:: For others to see, here is a var_dump of the array provided in the question since it has not readible
array 'languages' => array 76 => array 'id' => string '76' (length=2) 'tag' => string 'Deutsch' (length=7) 'targets' => array 81 => array 'id' => string '81' (length=2) 'tag' => string 'Deutschland' (length=11) 'tags' => array 7866 => array 'id' => string '7866' (length=4) 'tag' => string 'automobile' (length=10) 17800 => array 'id' => string '17800' (length=5) 'tag' => string 'seat leon' (length=9) 17801 => array 'id' => string '17801' (length=5) 'tag' => string 'seat leon cupra' (length=15) 'inactiveTags' => array 195 => array 'id' => string '195' (length=3) 'tag' => string 'auto' (length=4) 17804 => array 'id' => string '17804' (length=5) 'tag' => string 'coupès' (length=6) 17805 => array 'id' => string '17805' (length=5) 'tag' => string 'fahrdynamik' (length=11) 901 => array 'id' => string '901' (length=3) 'tag' => string 'fahrzeuge' (length=9) 17802 => array 'id' => string '17802' (length=5) 'tag' => string 'günstige neuwagen' (length=17) 1991 => array 'id' => string '1991' (length=4) 'tag' => string 'motorsport' (length=10) 2154 => array 'id' => string '2154' (length=4) 'tag' => string 'neuwagen' (length=8) 10660 => array 'id' => string '10660' (length=5) 'tag' => string 'seat' (length=4) 17803 => array 'id' => string '17803' (length=5) 'tag' => string 'sportliche ausstrahlung' (length=23) 74 => array 'id' => string '74' (length=2) 'tag' => string 'web 2.0' (length=7) 'categories' => array 16082 => array 'id' => string '16082' (length=5) 'tag' => string 'Auto & Motorrad' (length=15) 51 => array 'id' => string '51' (length=2) 'tag' => string 'Blogosphäre' (length=11) 66 => array 'id' => string '66' (length=2) 'tag' => string 'Neues & Trends' (length=14) 68 => array 'id' => string '68' (length=2) 'tag' => string 'Privat' (length=6)
Possibly too late to be of benefit now, but is this not the easiest way to do things?
SELECT empName, projIDs = replace
((SELECT Surname AS [data()]
FROM project_members
WHERE empName = a.empName
ORDER BY empName FOR xml path('')), ' ', REQUIRED SEPERATOR)
FROM project_members a
WHERE empName IS NOT NULL
GROUP BY empName
You should be aware that in C, unlike Java or C#, there is absolutely no possibility to successfully "guess" the type of object a void*
pointer points at. Something similar to getClass()
simply doesn't exist, since this information is nowhere to be found. For that reason, the kind of "generic" you are looking for always comes with explicit metainformation, like the int b
in your example or the format string in the printf
family of functions.
It is easier to compare dates using the java.util.Calendar
.
Here is what you might do:
Calendar toDate = Calendar.getInstance();
Calendar nowDate = Calendar.getInstance();
toDate.set(<set-year>,<set-month>,<set-day>);
if(!toDate.before(nowDate)) {
//display your report
} else {
// don't display the report
}
I found a solution for ajax issue noted by Lion_cl.
global.asax:
protected void Application_Error()
{
if (HttpContext.Current.Request.IsAjaxRequest())
{
HttpContext ctx = HttpContext.Current;
ctx.Response.Clear();
RequestContext rc = ((MvcHandler)ctx.CurrentHandler).RequestContext;
rc.RouteData.Values["action"] = "AjaxGlobalError";
// TODO: distinguish between 404 and other errors if needed
rc.RouteData.Values["newActionName"] = "WrongRequest";
rc.RouteData.Values["controller"] = "ErrorPages";
IControllerFactory factory = ControllerBuilder.Current.GetControllerFactory();
IController controller = factory.CreateController(rc, "ErrorPages");
controller.Execute(rc);
ctx.Server.ClearError();
}
}
ErrorPagesController
public ActionResult AjaxGlobalError(string newActionName)
{
return new AjaxRedirectResult(Url.Action(newActionName), this.ControllerContext);
}
AjaxRedirectResult
public class AjaxRedirectResult : RedirectResult
{
public AjaxRedirectResult(string url, ControllerContext controllerContext)
: base(url)
{
ExecuteResult(controllerContext);
}
public override void ExecuteResult(ControllerContext context)
{
if (context.RequestContext.HttpContext.Request.IsAjaxRequest())
{
JavaScriptResult result = new JavaScriptResult()
{
Script = "try{history.pushState(null,null,window.location.href);}catch(err){}window.location.replace('" + UrlHelper.GenerateContentUrl(this.Url, context.HttpContext) + "');"
};
result.ExecuteResult(context);
}
else
{
base.ExecuteResult(context);
}
}
}
AjaxRequestExtension
public static class AjaxRequestExtension
{
public static bool IsAjaxRequest(this HttpRequest request)
{
return (request.Headers["X-Requested-With"] != null && request.Headers["X-Requested-With"] == "XMLHttpRequest");
}
}
Mac already has Python and a package manager called easy_install
, so open Terminal and type
sudo easy_install selenium
With image class name:
$('.img_class').hide(); // to hide image
$('.img_class').show(); // to show image
With image Id :
$('#img_id').hide(); // to hide image
$('#img_id').show(); // to show image
UPDATE totals
SET total = total + 1
WHERE name = 'bill';
If you want to make sure the current value is indeed 203 (and not accidently increase it again) you can also add another condition:
UPDATE totals
SET total = total + 1
WHERE name = 'bill'
AND total = 203;
$ echo -e '1\n2\n2\n3\n3\n3\n4\n4\n4\n4\n5' |sed -nr '$!N;/^(.*)\n\1$/!P;D'
1
2
3
4
5
the core idea is:
print ONLY once of each duplicate consecutive lines at its LAST appearance and use D command to implement LOOP.
Explains:
$!N;
: if current line is NOT the last line, use N
command to read the next line into pattern space
./^(.*)\n\1$/!P
: if the contents of current pattern space
is two duplicate string
separated by \n
, which means the next line is the same
with current line, we can NOT print it according to our core idea; otherwise, which means current line is the LAST appearance of all of its duplicate consecutive lines, we can now use P
command to print the chars in current pattern space
util \n
(\n
also printed).D
: we use D
command to delete the chars in current pattern space
util \n
(\n
also deleted), then the content of pattern space
is the next line.D
command will force sed
to jump to its FIRST
command $!N
, but NOT read the next line from file or standard input stream.$ echo -e '1\n2\n2\n3\n3\n3\n4\n4\n4\n4\n5' |sed -nr 'p;:loop;$!N;s/^(.*)\n\1$/\1/;tloop;D'
1
2
3
4
5
the core idea is:
print ONLY once of each duplicate consecutive lines at its FIRST appearance and use : command & t command to implement LOOP.
Explains:
:loop
command set a label
named loop
.N
to read next line into the pattern space
.s/^(.*)\n\1$/\1/
to delete current line if the next line is same with current line, we use s
command to do the delete
action.s
command is executed successfully, then use tloop
command force sed
to jump to the label
named loop
, which will do the same loop to the next lines util there are no duplicate consecutive lines of the line which is latest printed
; otherwise, use D
command to delete
the line which is the same with thelatest-printed line
, and force sed
to jump to first command, which is the p
command, the content of current pattern space
is the next new line.If I understand well, you want to Join ScheduleRequest
with User
and apply the in
clause to the userName
property of the entity User
.
I'd need to work a bit on this schema. But you can try with this trick, that is much more readable than the code you posted, and avoids the Join
part (because it handles the Join
logic outside the Criteria Query).
List<String> myList = new ArrayList<String> ();
for (User u : usersList) {
myList.add(u.getUsername());
}
Expression<String> exp = scheduleRequest.get("createdBy");
Predicate predicate = exp.in(myList);
criteria.where(predicate);
In order to write more type-safe code you could also use Metamodel by replacing this line:
Expression<String> exp = scheduleRequest.get("createdBy");
with this:
Expression<String> exp = scheduleRequest.get(ScheduleRequest_.createdBy);
If it works, then you may try to add the Join
logic into the Criteria Query
. But right now I can't test it, so I prefer to see if somebody else wants to try.
Not a perfect answer though may be code snippets might help.
public <T> List<T> findListWhereInCondition(Class<T> clazz,
String conditionColumnName, Serializable... conditionColumnValues) {
QueryBuilder<T> queryBuilder = new QueryBuilder<T>(clazz);
addWhereInClause(queryBuilder, conditionColumnName,
conditionColumnValues);
queryBuilder.select();
return queryBuilder.getResultList();
}
private <T> void addWhereInClause(QueryBuilder<T> queryBuilder,
String conditionColumnName, Serializable... conditionColumnValues) {
Path<Object> path = queryBuilder.root.get(conditionColumnName);
In<Object> in = queryBuilder.criteriaBuilder.in(path);
for (Serializable conditionColumnValue : conditionColumnValues) {
in.value(conditionColumnValue);
}
queryBuilder.criteriaQuery.where(in);
}
In Angular 6, .angular-cli.json
has been replaced with angular.json
For Angular < 6:
Create a new file with name '.angular-cli.json' and add this file in your main directory.
{
"$schema": "./node_modules/@angular/cli/lib/config/schema.json",
"project": {
"name": "my-app"
},
"apps": [
{
"root": "src",
"outDir": "dist",
"assets": [
"assets",
"favicon.ico"
],
"index": "index.html",
"main": "main.ts",
"polyfills": "polyfills.ts",
"test": "test.ts",
"tsconfig": "tsconfig.app.json",
"testTsconfig": "tsconfig.spec.json",
"prefix": "app",
"styles": [
"styles.css"
],
"scripts": [],
"environmentSource": "environments/environment.ts",
"environments": {
"dev": "environments/environment.ts",
"prod": "environments/environment.prod.ts"
}
}
],
"e2e": {
"protractor": {
"config": "./protractor.conf.js"
}
},
"lint": [
{
"project": "src/tsconfig.app.json",
"exclude": "**/node_modules/**"
},
{
"project": "src/tsconfig.spec.json",
"exclude": "**/node_modules/**"
},
{
"project": "e2e/tsconfig.e2e.json",
"exclude": "**/node_modules/**"
}
],
"test": {
"karma": {
"config": "./karma.conf.js"
}
},
"defaults": {
"styleExt": "css",
"component": {}
}
}
I strip before and after data.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Text.RegularExpressions;
namespace testApp
{
class Program
{
static void Main(string[] args)
{
string tempString = "morenonxmldata<tag1>0002</tag1>morenonxmldata";
tempString = Regex.Replace(tempString, "[\\s\\S]*<tag1>", "");//removes all leading data
tempString = Regex.Replace(tempString, "</tag1>[\\s\\S]*", "");//removes all trailing data
Console.WriteLine(tempString);
Console.ReadLine();
}
}
}
Package Explorer / View Menu / Package Presentation... / Hierarchical
The "View Menu" can be opened with Ctrl + F10, or the small arrow-down icon in the top-right corner of the Package Explorer.
You can update your constraint with a smooth animation if you want, see the chunk of code below:
heightOrWidthConstraint.constant = 100
UIView.animate(withDuration: animateTime, animations:{
self.view.layoutIfNeeded()
})
Try this code:
$('#iframe').contents().find("html").html();
This will return all the html in your iframe. Instead of .find("html")
you can use any selector you want eg: .find('body')
,.find('div#mydiv')
.
Convert the UTC datetime to America/Denver
// create a $dt object with the UTC timezone
$dt = new DateTime('2016-12-12 12:12:12', new DateTimeZone('UTC'));
// change the timezone of the object without changing it's time
$dt->setTimezone(new DateTimeZone('America/Denver'));
// format the datetime
$dt->format('Y-m-d H:i:s T');
time()
returns the unix timestamp, which is a number, it has no timezone.
date('Y-m-d H:i:s T')
returns the date in the current locale timezone.
gmdate('Y-m-d H:i:s T')
returns the date in UTC
date_default_timezone_set()
changes the current locale timezone
to change a time in a timezone
// create a $dt object with the America/Denver timezone
$dt = new DateTime('2016-12-12 12:12:12', new DateTimeZone('America/Denver'));
// change the timezone of the object without changing it's time
$dt->setTimezone(new DateTimeZone('UTC'));
// format the datetime
$dt->format('Y-m-d H:i:s T');
here you can see all the available timezones
https://en.wikipedia.org/wiki/List_of_tz_database_time_zones
here are all the formatting options
http://php.net/manual/en/function.date.php
Update PHP timezone DB (in linux)
sudo pecl install timezonedb
In objective C variables with no value were equal to 'nil'(it was also possible to use 'nil' values same as 0 and false), hence it was possible to use variables in conditional statements (Variables having values are same as 'TRUE' and those with no values were equal to 'FALSE').
Swift provides type safety by providing 'optional value'. i.e. It prevents errors formed from assigning variables of different types.
So in Swift, only booleans can be provided on conditional statements.
var hw = "Hello World"
Here, even-though 'hw' is a string, it can't be used in an if statement like in objective C.
//This is an error
if hw
{..}
For that it needs to be created as,
var nhw : String? = "Hello World"
//This is correct
if nhw
{..}
Check out the slice()
method:
I tested below code with SQL Server 2008 R2 Express and I believe we should have solution for all 6 steps you outlined. Let's take on them one-by-one:
We can enable TCP/IP protocol with WMI:
set wmiComputer = GetObject( _
"winmgmts:" _
& "\\.\root\Microsoft\SqlServer\ComputerManagement10")
set tcpProtocols = wmiComputer.ExecQuery( _
"select * from ServerNetworkProtocol " _
& "where InstanceName = 'SQLEXPRESS' and ProtocolName = 'Tcp'")
if tcpProtocols.Count = 1 then
' set tcpProtocol = tcpProtocols(0)
' I wish this worked, but unfortunately
' there's no int-indexed Item property in this type
' Doing this instead
for each tcpProtocol in tcpProtocols
dim setEnableResult
setEnableResult = tcpProtocol.SetEnable()
if setEnableResult <> 0 then
Wscript.Echo "Failed!"
end if
next
end if
I believe your solution will work, just make sure you specify the right port. I suggest we pick a different port than 1433 and make it a static port SQL Server Express will be listening on. I will be using 3456 in this post, but please pick a different number in the real implementation (I feel that we will see a lot of applications using 3456 soon :-)
We can use WMI again. Since we are using static port 3456, we just need to update two properties in IPAll section: disable dynamic ports and set the listening port to 3456
:
set wmiComputer = GetObject( _
"winmgmts:" _
& "\\.\root\Microsoft\SqlServer\ComputerManagement10")
set tcpProperties = wmiComputer.ExecQuery( _
"select * from ServerNetworkProtocolProperty " _
& "where InstanceName='SQLEXPRESS' and " _
& "ProtocolName='Tcp' and IPAddressName='IPAll'")
for each tcpProperty in tcpProperties
dim setValueResult, requestedValue
if tcpProperty.PropertyName = "TcpPort" then
requestedValue = "3456"
elseif tcpProperty.PropertyName ="TcpDynamicPorts" then
requestedValue = ""
end if
setValueResult = tcpProperty.SetStringValue(requestedValue)
if setValueResult = 0 then
Wscript.Echo "" & tcpProperty.PropertyName & " set."
else
Wscript.Echo "" & tcpProperty.PropertyName & " failed!"
end if
next
Note that I didn't have to enable any of the individual addresses to make it work, but if it is required in your case, you should be able to extend this script easily to do so.
Just a reminder that when working with WMI, WBEMTest.exe is your best friend!
I wish we could use WMI again, but unfortunately this setting is not exposed through WMI. There are two other options:
Use LoginMode
property of Microsoft.SqlServer.Management.Smo.Server
class, as described here.
Use LoginMode value in SQL Server registry, as described in this post. Note that by default the SQL Server Express instance is named SQLEXPRESS
, so for my SQL Server 2008 R2 Express instance the right registry key was
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\MSSQL10_50.SQLEXPRESS\MSSQLServer
.
You got this one covered.
Since we are using a static port assigned to our SQL Server Express instance, there's no need to use instance name in the server address anymore.
SQLCMD -U sa -P newPassword -S 192.168.0.120,3456
Please let me know if this works for you (fingers crossed!).
$('.modal-backdrop').hide(); // for black background
$('body').removeClass('modal-open'); // For scroll run
$('#modal').modal('hide');
There are two parts in building barcode scanning feature, one capturing barcode image using camera and second extracting barcode value from the image.
Barcode image can be captured from your app using camera app and barcode value can be extracted using Firebase Machine Learning Kit barcode scanning API.
Here is an example app https://www.zoftino.com/android-barcode-scanning-example
if you dont wanna use DISTINCT use GROUP BY
SELECT * FROM myTABLE GROUP BY EmailAddress
If you want to check if a string contains substring or not using regex, the closest you can do is by using find() -
private static final validPattern = "\\bstores\\b.*\\bstore\\b.*\\bproduct\\b"
Pattern pattern = Pattern.compile(validPattern);
Matcher matcher = pattern.matcher(inputString);
System.out.print(matcher.find()); // should print true or false.
Note the difference between matches() and find(), matches() return true if the whole string matches the given pattern. find() tries to find a substring that matches the pattern in a given input string. Also by using find() you don't have to add extra matching like - (?s).* at the beginning and .* at the end of your regex pattern.
This is a bit nasty, but:
from datetime import datetime, timedelta
now = datetime.now().time()
# Just use January the first, 2000
d1 = datetime(2000, 1, 1, now.hour, now.minute, now.second)
d2 = d1 + timedelta(hours=1, minutes=23)
print d2.time()
The only way to project a collection that is not linear time is to do so lazily, where the resulting "vector" is actually a subtype which delegates to the original collection. For example, Scala's List#subseq
method create a sub-sequence in constant time. However, this only works if the collection is immutable and if the underlying language sports garbage collection.
Here is a good starting point.
HTML:
<div class="containing-table">
<div class="centre-align">
<div class="content"></div>
</div>
</div>
CSS:
.containing-table {
display: table;
width: 100%;
height: 400px; /* for demo only */
border: 1px dotted blue;
}
.centre-align {
padding: 10px;
border: 1px dashed gray;
display: table-cell;
text-align: center;
vertical-align: middle;
}
.content {
width: 50px;
height: 50px;
background-color: red;
display: inline-block;
vertical-align: top; /* Removes the extra white space below the baseline */
}
See demo at: http://jsfiddle.net/audetwebdesign/jSVyY/
.containing-table
establishes the width and height context for .centre-align
(the table-cell).
You can apply text-align
and vertical-align
to alter .centre-align
as needed.
Note that .content
needs to use display: inline-block
if it is to be centered horizontally using the text-align property.
If you're displaying a user-readable file name, you do not want to use lastPathComponent
. Instead, pass the full path to NSFileManager's displayNameAtPath:
method. This basically does does the same thing, only it correctly localizes the file name and removes the extension based on the user's preferences.
SELECT DISTINCT table_name,
constraint_name,
column_name,
r_table_name,
position,
constraint_type
FROM (SELECT uc.table_name,
uc.constraint_name,
cols.column_name,
(SELECT table_name
FROM user_constraints
WHERE constraint_name = uc.r_constraint_name) r_table_name,
(SELECT column_name
FROM user_cons_columns
WHERE constraint_name = uc.r_constraint_name
AND position = cols.position) r_column_name,
cols.position,
uc.constraint_type
FROM user_constraints uc
inner join user_cons_columns cols
ON uc.constraint_name = cols.constraint_name
WHERE constraint_type != 'C')
START WITH table_name = '&&tableName'
AND column_name = '&&columnName'
CONNECT BY NOCYCLE PRIOR table_name = r_table_name
AND PRIOR column_name = r_column_name;
Just for the sake of completeness, since I noticed no one suggested this simple approach:
>>> print("%.0f%%" % (100 * 1.0/3))
33%
Details:
%.0f
stands for "print a float with 0 decimal places", so %.2f
would print 33.33
%%
prints a literal %
. A bit cleaner than your original +'%'
1.0
instead of 1
takes care of coercing the division to float, so no more 0.0
Following is an example. You can see the details http://jkssweetlife.com/configure-slf4j-working-various-logging-frameworks/ and download the full codes here.
Add following dependency to your pom if you are using maven, otherwise, just download the jar files and put on your classpath
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.7</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.7</version>
</dependency>
Configure log4j.properties
log4j.rootLogger=TRACE, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd'T'HH:mm:ss.SSS} %-5p [%c] - %m%n
Java example
public class Slf4jExample {
public static void main(String[] args) {
Logger logger = LoggerFactory.getLogger(Slf4jExample.class);
final String message = "Hello logging!";
logger.trace(message);
logger.debug(message);
logger.info(message);
logger.warn(message);
logger.error(message);
}
}
Old question but nowadays CSS3 makes vertical alignment really simple!
Just add to #abc
the following css:
display:flex;
align-items:center;
Original question demo updated
Simple Example:
.vertical-align-content {_x000D_
background-color:#f18c16;_x000D_
height:150px;_x000D_
display:flex;_x000D_
align-items:center;_x000D_
/* Uncomment next line to get horizontal align also */_x000D_
/* justify-content:center; */_x000D_
}
_x000D_
<div class="vertical-align-content">_x000D_
Hodor!_x000D_
</div>
_x000D_
1. solution
delete from emp
where rowid not in
(select max(rowid) from emp group by empno);
2. sloution
delete from emp where rowid in
(
select rid from
(
select rowid rid,
row_number() over(partition by empno order by empno) rn
from emp
)
where rn > 1
);
3.solution
delete from emp e1
where rowid not in
(select max(rowid) from emp e2
where e1.empno = e2.empno );
4. solution
delete from emp where rowid in
(
select rid from
(
select rowid rid,
dense_rank() over(partition by empno order by rowid
) rn
from emp
)
where rn > 1
);
I have tried several solutions proposed above without success.
So, I have installed the last ruby version 2.7.2 with rbenv, and upgraded my app.
Then I had a PG::ConnectionBad error.
I ran
brew postgresql-upgrade-database.
And now It’s working fine.
here more details about what I tried.
You can remove them from /Library/Developer/CoreSimulator/Profiles/Runtimes
(Not ~/Library
!):
Why not try find /usr/include/X11 -name Xlib.h
If there is a hit, you have Xlib.h
If not install it using sudo apt-get install libx11-dev
and you are good to go :)
If you know part of the subnet (i.e. 10.3 in this example), then this will grab any addresses that are in the given subnet:
PS C:\> [System.Net.Dns]::GetHostAddresses("MyPC") | foreach { $_.IPAddressToString | findstr "10.3."}
%02x
means print at least 2 digits, prepend it with 0
's if there's less. In your case it's 7 digits, so you get no extra 0
in front.
Also, %x
is for int, but you have a long. Try %08lx
instead.
If you don't care about dirty reads (i.e. in a predominately READ situation), then NOLOCK
is fine.
BUT, be aware that the majority of locking problems are due to not having the 'correct' indexes for your query workload (assuming the hardware is up to the task).
And the guru's explanation was correct. It is usually a band-aid solution to a more serious problem.
Edit: I'm definitely not suggesting that NOLOCK should be used. I guess I should have made that obviously clear. (I would only ever use it, in extreme circumstances where I had analysed that it was OK). AS an example, a while back I worked on some TSQL that had been sprinkled with NOLOCK to try and alleviate locking problems. I removed them all, implemented the correct indexes, and ALL of the deadlocks went away.
A simple solution to exclude everything but integer numbers
<input
type="number"
min="1"
step="1"
onkeypress="return event.keyCode === 8 || event.charCode >= 48 && event.charCode <= 57">
_x000D_
Try this one -
CREATE PROCEDURE sp_ADD_USER_EXTRANET_CLIENT_INDEX_PHY
AS
BEGIN
DECLARE @ParLngId INT
SELECT TOP 1 @ParLngId = ParLngId
FROM dbo.T_Param
WHERE ParStrNom = 'Extranet Client'
IF (@ParLngId = 0)
BEGIN
INSERT INTO dbo.T_Param
VALUES ('PHY', 'Extranet Client', NULL, NULL, 'T', 0, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 1, NULL, NULL, NULL)
RETURN SCOPE_IDENTITY()
END
ELSE BEGIN
RETURN @ParLngId
END
END
First check for an error (N/A value) and then try the comparisation against cvErr(). You are comparing two different things, a value and an error. This may work, but not always. Simply casting the expression to an error may result in similar problems because it is not a real error only the value of an error which depends on the expression.
If IsError(ActiveWorkbook.Sheets("Publish").Range("G4").offset(offsetCount, 0).Value) Then
If (ActiveWorkbook.Sheets("Publish").Range("G4").offset(offsetCount, 0).Value <> CVErr(xlErrNA)) Then
'do something
End If
End If
Another option is to use linear-gradient()
to cover up the edges of your image. Note that this is a stupid solution, so I'm not going to put much effort into explaining it...
.flair {_x000D_
min-width: 50px; /* width larger than sprite */_x000D_
text-indent: 60px;_x000D_
height: 25px;_x000D_
display: inline-block;_x000D_
background:_x000D_
linear-gradient(#F00, #F00) 50px 0/999px 1px repeat-y,_x000D_
url('https://championmains.github.io/dynamicflairs/riven/spritesheet.png') #F00;_x000D_
}_x000D_
_x000D_
.flair-classic {_x000D_
background-position: 50px 0, 0 -25px;_x000D_
}_x000D_
_x000D_
.flair-r2 {_x000D_
background-position: 50px 0, -50px -175px;_x000D_
}_x000D_
_x000D_
.flair-smite {_x000D_
text-indent: 35px;_x000D_
background-position: 25px 0, -50px -25px;_x000D_
}
_x000D_
<img src="https://championmains.github.io/dynamicflairs/riven/spritesheet.png" alt="spritesheet" /><br />_x000D_
<br />_x000D_
<span class="flair flair-classic">classic sprite</span><br /><br />_x000D_
<span class="flair flair-r2">r2 sprite</span><br /><br />_x000D_
<span class="flair flair-smite">smite sprite</span><br /><br />
_x000D_
I'm using this method on this page: https://championmains.github.io/dynamicflairs/riven/ and can't use ::before
or ::after
elements because I'm already using them for another hack.
An important difference between a 'typedef struct' and a 'struct' in C++ is that inline member initialisation in 'typedef structs' will not work.
// the 'x' in this struct will NOT be initialised to zero
typedef struct { int x = 0; } Foo;
// the 'x' in this struct WILL be initialised to zero
struct Foo { int x = 0; };
I tried above answers and particularly Gajus's but none works. Finally I found the answer below to solve the problem such that only the main body doesn't scroll but other scrolling sections inside my web app all work fine. Simply set position fixed for your body:
body {
height: 100%;
overflow: hidden;
width: 100%;
position: fixed;
}