I find the adding <br>
does what is wanted.
There is also a great open source tool called clink, which extends cmd by many features. One of them is being able to use ctrl+v to insert text.
In dashboard you can see running word press version at "At a Glance"
Reference types do not store the object directly into the variable to which it is assigned, so the object variable in the example below, doesn’t actually contain the object instance. Instead, it holds a pointer (or reference) to the location in memory, where the object exists.
var object = new Object();
if you assign one reference typed variable to another, each variable gets a copy of the pointer, and both still reference to the same object in memory.
var object1 = new Object();
var object2 = object1;
JavaScript is a garbage-collected language, so you don’t really need to worry about memory allocations when you use reference types. However, it’s best to dereference objects that you no longer need so that the garbage collector can free up that memory. The best way to do this is to set the object variable to null.
var object1 = new Object();
// do something
object1 = null; // dereference
Dereferencing objects is especially important in very large applications that use millions of objects.
from The Principles of Object-Oriented JavaScript - NICHOLAS C. ZAKAS
It might be useful to somebody:
I was having the issue that formdata was not being sent for my request
In my case it was a combination of following headers that were also causing the issue and the wrong Content-Type.
So I was sending these two headers with the request and it wasn't sending the formdata when I removed the headers that worked.
"X-Prototype-Version" : "1.6.1", "X-Requested-With" : "XMLHttpRequest"
Also as other answers suggest that the Content-Type header needs to be correct.
For my request the correct Content-Type header was:
"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8"
So bottom line if your formdata is not being attached to the Request then it could potentially be your headers. Try bringing your headers to a minimum and then try adding them one by one to see if your problem is rsolved.
You need to run the ng server from the c:\project\angular-src location. Not just the root of your project.
You could implement a JavaScript block which contains a function with your needs.
<div style="position: absolute; left: 10px; top: 40px;">
<img src="logg.png" width="114" height="38" onclick="DoSomething();" />
</div>
SELECT * FROM a WHERE a.group_id IN
(SELECT group_id FROM b WHERE b.user_id!=$_SESSION{'[user_id']} AND b.group_id = a.group_id)
WHERE a.keyword LIKE '%".$keyword."%';
This is not possible from HTML on. The closest what you can get is the accept-charset
attribute of the <form>
. Only MSIE browser adheres that, but even then it is doing it wrong (e.g. CP1252 is actually been used when it says that it has sent ISO-8859-1). Other browsers are fully ignoring it and they are using the charset as specified in the Content-Type
header of the response. Setting the character encoding right is basically fully the responsiblity of the server side. The client side should just send it back in the same charset as the server has sent the response in.
To the point, you should really configure the character encoding stuff entirely from the server side on. To overcome the inability to edit URIEncoding
attribute, someone here on SO wrote a (complex) filter: Detect the URI encoding automatically in Tomcat. You may find it useful as well (note: I haven't tested it).
Update:
Noted should be that the meta tag as given in your question is ignored when the content is been transferred over HTTP. Instead, the HTTP response Content-Type
header will be used to determine the content type and character encoding. You can determine the HTTP header with for example Firebug, in the Net panel.
Try doing this :
awk '{print substr($0, 1, length($0)-1)}' file.txt
This is more generic than just removing the final comma but any last character
If you'd want to only remove the last comma with awk :
awk '{gsub(/,$/,""); print}' file.txt
I find solution that instead of using ListBox I used ListView.It allows to change list items BackColor.
private void listView1_Refresh()
{
for (int i = 0; i < listView1.Items.Count; i++)
{
listView1.Items[i].BackColor = Color.Red;
for (int j = 0; j < existingStudents.Count; j++)
{
if (listView1.Items[i].ToString().Contains(existingStudents[j]))
{
listView1.Items[i].BackColor = Color.Green;
}
}
}
}
The style
property lets you specify values for CSS properties.
The CSS width
property takes a length as its value.
Lengths require units. In quirks mode, browsers tend to assume pixels if provided with an integer instead of a length. Specify units.
e1.style.width = "400px";
If you use Fedora, in order to generate core dump file in the same directory of binary file:
echo "core.%e.%p" > /proc/sys/kernel/core_pattern
And
ulimit -c unlimited
There can be several things which cause this.
targetSdkVersion
and compileSdkVersion
.targetSdkVersion
and compileSdkVersion
are same.Other solutions can be:
File
? Invalidate Caches / Restarts...
Build
? Clean Project
Build
? Rebuild Project
Build
? Make Project
[this process may take some time]For a visual way to think about it, picture a clock face that, in your particular example, only goes to 4 instead of 12. If you start at 4 on the clock (which is like starting at zero) and go around it clockwise for 2 "hours", you land on 2, just like going around it clockwise for 6 "hours" would also land you on 2 (6 mod 4 == 2 just like 2 mod 4 == 2).
There were several projects available that reverse engineered the WhatsApp webservice interfaces. However, to my knowledge all of them are now discontinued/defunct due to legal action against them from WhatsApp.
For mobile phone applications there is a limited URL-Scheme-API available on IPhone and Android (Android-intent possible as well).
What about using NSString's hasSuffix and hasPrefix methods? Something like (if you're searching for "foo*.jpg"):
NSString *bundleRoot = [[NSBundle mainBundle] bundlePath];
NSArray *dirContents = [[NSFileManager defaultManager] directoryContentsAtPath:bundleRoot];
for (NSString *tString in dirContents) {
if ([tString hasPrefix:@"foo"] && [tString hasSuffix:@".jpg"]) {
// do stuff
}
}
For simple, straightforward matches like that it would be simpler than using a regex library.
You can find the number of characters using system function LEN
.
i.e.
SELECT LEN(Column) FROM TABLE
You cannot open Java Applets (nor any other NPAPI plugin) in Microsoft Edge - they aren't supported and won't be added in the future.
Further you should be aware that in the next release of Google Chrome (v45 - due September 2015) NPAPI plugins will also no longer be supported.
There are a couple of things that you can do:
Use Internet Explorer 11
You will find that in Windows 10 you will already have Internet Explorer 11 installed. IE 11 continues to support NPAPI (incl Java Applets).
IE11 is squirrelled away (c:\program files\internet explorer\iexplore.exe
). Just pin this exe to your task bar for easy access.
Use FireFox
You can also install and use a Firefox 32-bit Extended Support Release in Win10. Firefox have disabled NPAPI by default, but this can be overridden. This will only be supported until early 2018.
To renew the development profile before it expired, I finally found a way that works for me. I boldfaced the steps I had been missing before.
Go to the Apple provisioning portal, select "Provisioning". You'll get a list "Development Provisioning Profiles" where you'll see your soon to expire profile with the label "Managed by XCode". Click the "New Profile" button on top, select the type of profile you want and create it. Wait half a minute, refresh the home screen and when it shows the new profile as "Active", switch back to XCode, go to the Organizer, select "Provisioning profiles" under "Library" in left top column. Click "Refresh" at the bottom, log in (if it asks) and the new profile appears in the list after a short while.
Now, crucially, connect your device and drag your new profile to the "Provisioning Profiles" row under the connected device in the left column.
Finally, you can clean up the old profiles from your device if you feel like it.
Note: interestingly, it seems that simply marking and deleting your provisioning profile on the iOS Provisioning Portal site causes a new fresh Team Provisioning Profile to be created. So maybe that is all that is needed. I will try that next time to see if that is enough, if so you don't need to create a profile as I described above.
Have you tried this:
import java.io.*;
import java.util.*;
import java.net.*;
import org.apache.hadoop.fs.*;
import org.apache.hadoop.conf.*;
import org.apache.hadoop.io.*;
import org.apache.hadoop.mapred.*;
import org.apache.hadoop.util.*;
public class cat{
public static void main (String [] args) throws Exception{
try{
FileSystem fs = FileSystem.get(new Configuration());
FileStatus[] status = fs.listStatus(new Path("hdfs://test.com:9000/user/test/in")); // you need to pass in your hdfs path
for (int i=0;i<status.length;i++){
BufferedReader br=new BufferedReader(new InputStreamReader(fs.open(status[i].getPath())));
String line;
line=br.readLine();
while (line != null){
System.out.println(line);
line=br.readLine();
}
}
}catch(Exception e){
System.out.println("File not found");
}
}
}
Here you can find Postgre example, this code run multiple sql commands (update 2 columns) within single SQL connection
public static class SQLTest
{
public static void NpgsqlCommand()
{
using (NpgsqlConnection connection = new NpgsqlConnection("Server = ; Port = ; User Id = ; " + "Password = ; Database = ;"))
{
NpgsqlCommand command1 = new NpgsqlCommand("update xy set xw = 'a' WHERE aa='bb'", connection);
NpgsqlCommand command2 = new NpgsqlCommand("update xy set xw = 'b' where bb = 'cc'", connection);
command1.Connection.Open();
command1.ExecuteNonQuery();
command2.ExecuteNonQuery();
command2.Connection.Close();
}
}
}
Use a FULL OUTER JOIN:
select
a.col_a,
a.col_b,
b.col_c
from
(select col_a,col_bfrom tab1) a
join
(select col_a,col_cfrom tab2) b
on a.col_a= b.col_a
Adding the correct doctype declaration and avoiding the XML prolog should be enough to avoid quirks mode.
If you are looking at an office setting with regular office non technical users than Sharepoint is a viable alternative. You can setup document folders with version control enabled and checkins and checkouts. Makes it freindlier for regular office users.
Java 7+
It's possible to take advantage of the StandardCharsets
JDK class:
String str=...
InputStream is = new ByteArrayInputStream(StandardCharsets.UTF_16.encode(str).array());
While you can simply use it to prefix your identifiers, it's supposed to be used for generated code, such as replacement tokens in a template, for example.
You have missed out the field name id
in the second NOT LIKE
. Try:
SELECT * FROM transactions WHERE id NOT LIKE '1%' AND id NOT LIKE '2%'
The AND
in the where clause joins 2 full condition expressions such as id NOT LIKE '1%'
and can't be used to list multiple values that the id is 'not like'.
This solution is Only for local system / localhost on windows:
The simplest way to install xampp 5.6.X version as per your requirement in other windows drive then run xampp 5.6.X services from it's control panel for php 5.6 version.
NOTE: If you already have xampp (any other version) on your system then please close that xampp's services then start xampp 5.6.x services otherwise this solution will not work.
You can download your required (xampp 5.6 as per question) xampp version from below link:
https://sourceforge.net/projects/xampp/files/XAMPP%20Windows/
I have used this solution many times, it worked like charm. I hope this will also help you. Thank you to ask this question.
Good question. But I think there is no good answer which fits your criteria. The best I can think of is to use an extra vars file.
A task like this:
- include_vars: concat.yml
And in concat.yml
you have your definition:
newvar: "{{ var1 }}-{{ var2 }}-{{ var3 }}"
In my case, I disabled McAfee and then successfully installed tensorflow2.0 RC
127.0.0.1,6283
Add a comma between the ip and port
Go with the first and use single quotes!
The only situations when you should use double quotes, is when you need \r
, \n
, \t
!
The overhead is just not worth it to use it in any other case.
You should also check PHP variable concatenation, phpbench.com for some benchmarks on different methods of doing things.
Try this:
data = f.flatMap(lambda x: x.split(' '))
map = data.map(lambda x: (x, 1))
mapreduce = map.reduceByKey(lambda x,y: x+y)
result = mapreduce.collect()
Please note that when you run collect(), the RDD - which is a distributed data set is aggregated at the driver node and is essentially converted to a list. So obviously, it won't be a good idea to collect() a 2T data set. If all you need is a couple of samples from your RDD, use take(10).
You may want to use:
SELECT Name, 'Unpaid' AS Status FROM table;
The SELECT
clause syntax, as defined in MSDN: SELECT Clause (Transact-SQL), is as follows:
SELECT [ ALL | DISTINCT ]
[ TOP ( expression ) [ PERCENT ] [ WITH TIES ] ]
<select_list>
Where the expression
can be a constant, function, any combination of column names, constants, and functions connected by an operator or operators, or a subquery.
You mention you are using OS X- I have used cronnix in the past. It's not as geeky as editing it yourself, but it helped me learn what the columns are in a jiffy. Just a thought.
On Windows it is most probably that the device drivers are not installed properly.
First, install Google USB Driver
from Android SDK Manager.
Then, go to Start
, right-click on My Computer
, select Properties
and go to Device Manager
on the left. Locate you device under Other Devices
(Unknown devices
, USB Devices
). Right-click on it and select Properties
. Navigate to Driver
tab. Select Update Driver
and then Browse my computer for driver software
. Choose %ANDROID_SDK_HOME%\extras\google\usb_driver
directory. Windows should find and install drivers there. Then run adb kill-server
. Next time you do adb devices
the device should be in the list.
You need to use the Thread.sleep()
call.
More info here: http://docs.oracle.com/javase/tutorial/essential/concurrency/sleep.html
View single commit:
https://github.com/<user>/<project>/commit/<hash>
View log:
https://github.com/<user>/<project>/commits/<hash>
View full repo:
https://github.com/<user>/<project>/tree/<hash>
<hash>
can be any length as long as it is unique.
I'd refrain from using floats for this sort of thing; I'd rather use inline-block
.
Some more points to consider:
<head>
and <body>
doctype
Here's a better way to format your document:
<!DOCTYPE html>
<html>
<head>
<title>Website Title</title>
<style type="text/css">
* {margin: 0; padding: 0;}
#container {height: 100%; width:100%; font-size: 0;}
#left, #middle, #right {display: inline-block; *display: inline; zoom: 1; vertical-align: top; font-size: 12px;}
#left {width: 25%; background: blue;}
#middle {width: 50%; background: green;}
#right {width: 25%; background: yellow;}
</style>
</head>
<body>
<div id="container">
<div id="left">Left Side Menu</div>
<div id="middle">Random Content</div>
<div id="right">Right Side Menu</div>
</div>
</body>
</html>
Here's a jsFiddle for good measure.
I received the exact same error message. Except that my error message said "Could not load file or assembly 'EntityFramework, Version=6.0.0.0...", because I installed EF 6.1.1. Here's what I did to resolve the problem.
1) I started NuGet Manager Console by clicking on Tools > NuGet Package Manager > Package Manager Console 2) I uninstalled the installed EntityFramework 6.1.1 by typing the following command:
Uninstall-package EntityFramework
3) Once I received confirmation that the package has been uninstalled successfully, I installed the 5.0.0 version by typing the following command:
Install-Package EntityFramework -version 5.0.0
The problem is resolved.
querySelectorAll
function and split the values
string.Array#forEach
to iterate over every element from the values
array.Array#find
to find the option matching given value.selected
attribute to true
.Note: Array#from
transforms an array-like object into an array and then you are able to use Array.prototype
functions on it, like find or map.
var values = "Test,Prof,Off",_x000D_
options = Array.from(document.querySelectorAll('#strings option'));_x000D_
_x000D_
values.split(',').forEach(function(v) {_x000D_
options.find(c => c.value == v).selected = true;_x000D_
});
_x000D_
<select name='strings' id="strings" multiple style="width:100px;">_x000D_
<option value="Test">Test</option>_x000D_
<option value="Prof">Prof</option>_x000D_
<option value="Live">Live</option>_x000D_
<option value="Off">Off</option>_x000D_
<option value="On">On</option>_x000D_
</select>
_x000D_
You can do this without moment.js
A way to do this in native Javascript code :
var date = new Date(), y = date.getFullYear(), m = date.getMonth();
var firstDay = new Date(y, m, 1);
var lastDay = new Date(y, m + 1, 0);
firstDay = moment(firstDay).format(yourFormat);
lastDay = moment(lastDay).format(yourFormat);
I had the same ERROR
message. tbrisker's solution did not work in my case. Instead this solved the issue:
$ python3 -m venv .env
This method can use for to get current date from the system.
public static String getCurrentDateAndTime(){
Date c = Calendar.getInstance().getTime();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd");
String formattedDate = simpleDateFormat.format(c);
return formattedDate;
}
COLUMN()
and ROW()
won't work this way because they are applied to the cell that is calling them. In conditional formatting, you will have to be explicit instead of implicit.
For instance, if you want to use this conditional formating on a range begining on cell A1
, you can try:
`COLUMN(A1)` and `ROW(A1)`
Excel will automatically adapt the conditional formating to the current cell.
Yep! Use the link:
https://m.google.com/app/plus/x/?v=compose&content=YOUR_TEXT
It's SHARE url (not used for plus one) button.
If this will not work (not for me) try this url:
https://plusone.google.com/_/+1/confirm?hl=ru&url=_URL_&title=_TITLE_
Or see this solution:
Adding a Google Plus (one or share) link to an email newsletter
Well, you can always try WHERE textcolumn LIKE "%SUBSTRING%"
- but this is guaranteed to be pretty slow, as your query can't do an index match because you are looking for characters on the left side.
It depends on the field type - a textarea usually won't be saved as VARCHAR, but rather as (a kind of) TEXT field, so you can use the MATCH AGAINST operator.
To get the columns that don't match, simply put a NOT in front of the like: WHERE textcolumn NOT LIKE "%SUBSTRING%"
.
Whether the search is case-sensitive or not depends on how you stock the data, especially what COLLATION you use. By default, the search will be case-insensitive.
I say that doing a WHERE field LIKE "%value%"
is slower than WHERE field LIKE "value%"
if the column field has an index, but this is still considerably faster than getting all values and having your application filter. Both scenario's:
1/ If you do SELECT field FROM table WHERE field LIKE "%value%"
, MySQL will scan the entire table, and only send the fields containing "value".
2/ If you do SELECT field FROM table
and then have your application (in your case PHP) filter only the rows with "value" in it, MySQL will also scan the entire table, but send all the fields to PHP, which then has to do additional work. This is much slower than case #1.
Solution: Please do use the WHERE
clause, and use EXPLAIN
to see the performance.
Just to extend the answer above you can also index your columns rather than specifying the column names which can also be useful depending on what you're doing. Given that your location is the first field it would look like this:
bar <- foo[foo[ ,1] == "there", ]
This is useful because you can perform operations on your column value, like looping over specific columns (and you can do the same by indexing row numbers too).
This is also useful if you need to perform some operation on more than one column because you can then specify a range of columns:
foo[foo[ ,c(1:N)], ]
Or specific columns, as you would expect.
foo[foo[ ,c(1,5,9)], ]
If this server is visible to the outside world, It's worth checking if it's having lots of requests to connect from the outside world (i.e. people trying to break into it)
I had issues getting the above code to work within cookie.js. The following code managed to create the correct timestamp for the cookie expiration in my instance.
var inFifteenMinutes = new Date(new Date().getTime() + 15 * 60 * 1000);
This was from the FAQs for Cookie.js
Under Windows only: You may try to use ini_set()
functionDocs for the SMTP
Docs and smtp_port
Docs settings:
ini_set('SMTP', 'mysmtphost');
ini_set('smtp_port', 25);
A java Thread a unit of execution which was designed to perform a task in its run() method & terminate after that:
But in Android there are many use cases where we need to keep a Thread alive and wait for user inputs/events for eg. UI thread aka Main Thread
.
Main thread in Android is a Java thread which is first started by JVM at the launch of an app and keeps on running till the user choose to close it or encounters unhandled exception.
When an application is launched, the system creates a thread of execution for the application, called "main." This thread is very important because it is in charge of dispatching events to the appropriate user interface widgets, including drawing events.
Now point to note here is although main thread is Java thread yet it keeps on listening to user events and draw 60 fps frames on screen and still it wont die after each cycle. how is it so?
The answer is Looper Class: Looper is a class which is used to keep a thread alive and manage a message queue to execute tasks on that thread.
Threads by default do not have a message loop associated with them but you can assign one by calling Looper.prepare() in the run method and then call the Looper.loop().
Purpose of Looper is to keep a Thread alive and wait for next cycle of input
Message
object to perform computation which otherwise will get destroyed after first cycle of execution.
If you want to dig deeper how Looper manage Message
object queue then you can have a look at source code of Looperclass
:
https://github.com/aosp-mirror/platform_frameworks_base/blob/master/core/java/android/os/Looper.java
Below is an example of how you can create a Looper Thread
and communicate with Activity
class using LocalBroadcast
class LooperThread : Thread() {
// sendMessage success result on UI
private fun sendServerResult(result: String) {
val resultIntent = Intent(ServerService.ACTION)
resultIntent.putExtra(ServerService.RESULT_CODE, Activity.RESULT_OK)
resultIntent.putExtra(ServerService.RESULT_VALUE, result)
LocalBroadcastManager.getInstance(AppController.getAppController()).sendBroadcast(resultIntent)
}
override fun run() {
val looperIsNotPreparedInCurrentThread = Looper.myLooper() == null
// Prepare Looper if not already prepared
if (looperIsNotPreparedInCurrentThread) {
Looper.prepare()
}
// Create a handler to handle messaged from Activity
handler = Handler(Handler.Callback { message ->
// Messages sent to Looper thread will be visible here
Log.e(TAG, "Received Message" + message.data.toString())
//message from Activity
val result = message.data.getString(MainActivity.BUNDLE_KEY)
// Send Result Back to activity
sendServerResult(result)
true
})
// Keep on looping till new messages arrive
if (looperIsNotPreparedInCurrentThread) {
Looper.loop()
}
}
//Create and send a new message to looper
fun sendMessage(messageToSend: String) {
//Create and post a new message to handler
handler!!.sendMessage(createMessage(messageToSend))
}
// Bundle Data in message object
private fun createMessage(messageToSend: String): Message {
val message = Message()
val bundle = Bundle()
bundle.putString(MainActivity.BUNDLE_KEY, messageToSend)
message.data = bundle
return message
}
companion object {
var handler: Handler? = null // in Android Handler should be static or leaks might occur
private val TAG = javaClass.simpleName
}
}
Usage:
class MainActivity : AppCompatActivity() {
private var looperThread: LooperThread? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// start looper thread
startLooperThread()
// Send messages to Looper Thread
sendMessage.setOnClickListener {
// send random messages to looper thread
val messageToSend = "" + Math.random()
// post message
looperThread!!.sendMessage(messageToSend)
}
}
override fun onResume() {
super.onResume()
//Register to Server Service callback
val filterServer = IntentFilter(ServerService.ACTION)
LocalBroadcastManager.getInstance(this).registerReceiver(serverReceiver, filterServer)
}
override fun onPause() {
super.onPause()
//Stop Server service callbacks
LocalBroadcastManager.getInstance(this).unregisterReceiver(serverReceiver)
}
// Define the callback for what to do when data is received
private val serverReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
val resultCode = intent.getIntExtra(ServerService.RESULT_CODE, Activity.RESULT_CANCELED)
if (resultCode == Activity.RESULT_OK) {
val resultValue = intent.getStringExtra(ServerService.RESULT_VALUE)
Log.e(MainActivity.TAG, "Server result : $resultValue")
serverOutput.text =
(serverOutput.text.toString()
+ "\n"
+ "Received : " + resultValue)
serverScrollView.post( { serverScrollView.fullScroll(View.FOCUS_DOWN) })
}
}
}
private fun startLooperThread() {
// create and start a new LooperThread
looperThread = LooperThread()
looperThread!!.name = "Main Looper Thread"
looperThread!!.start()
}
companion object {
val BUNDLE_KEY = "handlerMsgBundle"
private val TAG = javaClass.simpleName
}
}
Can we use Async task or Intent Services instead?
Async tasks are designed to perform a short operation in background and give progres & results on UI thread. Async tasks have limits like you cant create more than 128 Async tasks and ThreadPoolExecutor
will allow only upto 5 Async tasks.
IntentServices
are also designed to do background task for a little longer duration and you can use LocalBroadcast
to communicate with Activity
. But services get destroyed after task execution. If you want to keep it running for a long time than you need to do hecks like while(true){...}
.
Other meaningful use cases for Looper Thread:
Used for 2 way socket communication where server keep on listening to Client socket and write back acknowledgment
Bitmap processing in background. Pass the image url to Looper thread and it will apply filter effects and store it in tempe rory location and then broadcast temp path of image.
You could subclass ArrayList, and call Collections.sort(this) after any element is added - you would need to override two versions of add, and two of addAll, to do this.
Performance would not be as good as a smarter implementation which inserted elements in the right place, but it would do the job. If addition to the list is rare, the cost amortised over all operations on the list should be low.
I just found out a workaround with shell by retrieving the previous command.
Press Ctrl-R to bring up reverse search command:
reverse-i-search
Then start typing git commit -m, this will add this as search command, and this brings the previous git commit with its message:
reverse-i-search`git commit -m`: git commit -m "message"
Enter. That's it!
(tested in Ubuntu shell)
input
fields can be styled as you wish. So instead of zoom, you could have
input[type="checkbox"]{
width: 30px; /*Desired width*/
height: 30px; /*Desired height*/
}
EDIT:
You would have to add extra rules like this:
input[type="checkbox"]{
width: 30px; /*Desired width*/
height: 30px; /*Desired height*/
cursor: pointer;
-webkit-appearance: none;
appearance: none;
}
Check this fiddle http://jsfiddle.net/p36tqqyq/1/
I call *args "star args" or "varargs" and **kwargs "keyword args".
I actually discovered something recently that seems to work for styling individual <option></option>
elements within Chrome, Firefox, and IE using pure CSS.
Maybe, try the following:
HTML:
<select>
<option value="blank">Blank</option>
<option class="white" value="white">White</option>
<option class="red" value="red">Red</option>
<option class="blue" value="blue">Blue</option>
</select>
CSS:
select {
background-color:#000;
color: #FFF;
}
select * {
background-color:#000;
color:#FFF;
}
select *.red { /* This, miraculously, styles the '<option class="red"></option>' elements. */
background-color:#F00;
color:#FFF;
}
select *.white {
background-color:#FFF;
color:#000;
}
select *.blue {
background-color:#06F;
color:#FFF;
}
Strange what throwing caution to the wind does. It doesn't seem to support the :active :hover :focus :link :visited :after :before
, though.
Example on JSFiddle: http://jsfiddle.net/Xd7TJ/2/
awk, sed, pipe, that's heavy
set `cat /etc/*release`; echo $1
This is more of a important comment and that why implicitly unwrapped optionals can be deceptive when it comes to debugging nil
values.
Think of the following code: It compiles with no errors/warnings:
c1.address.city = c3.address.city
Yet at runtime it gives the following error: Fatal error: Unexpectedly found nil while unwrapping an Optional value
Can you tell me which object is nil
?
You can't!
The full code would be:
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
var c1 = NormalContact()
let c3 = BadContact()
c1.address.city = c3.address.city // compiler hides the truth from you and then you sudden get a crash
}
}
struct NormalContact {
var address : Address = Address(city: "defaultCity")
}
struct BadContact {
var address : Address!
}
struct Address {
var city : String
}
Long story short by using var address : Address!
you're hiding the possibility that a variable can be nil
from other readers. And when it crashes you're like "what the hell?! my address
isn't an optional, so why am I crashing?!.
Hence it's better to write as such:
c1.address.city = c2.address!.city // ERROR: Fatal error: Unexpectedly found nil while unwrapping an Optional value
Can you now tell me which object it is that was nil
?
This time the code has been made more clear to you. You can rationalize and think that likely it's the address
parameter that was forcefully unwrapped.
The full code would be :
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
var c1 = NormalContact()
let c2 = GoodContact()
c1.address.city = c2.address!.city
c1.address.city = c2.address?.city // not compile-able. No deceiving by the compiler
c1.address.city = c2.address.city // not compile-able. No deceiving by the compiler
if let city = c2.address?.city { // safest approach. But that's not what I'm talking about here.
c1.address.city = city
}
}
}
struct NormalContact {
var address : Address = Address(city: "defaultCity")
}
struct GoodContact {
var address : Address?
}
struct Address {
var city : String
}
The bottom statement is equivalent to:
.half {
flex-grow: 0;
flex-shrink: 0;
flex-basis: 50%;
}
Which, in this case, would be equivalent as the box is not allowed to flex and therefore retains the initial width set by flex-basis.
Flex-basis defines the default size of an element before the remaining space is distributed so if the element were allowed to flex (grow/shrink) it may not be 50% of the width of the page.
I've found that I regularly return to https://css-tricks.com/snippets/css/a-guide-to-flexbox/ for help regarding flexbox :)
Put this in a file and make it executable:
#!/bin/bash
start=`grep -n $1 < $3 | head -n1 | cut -d: -f1; exit ${PIPESTATUS[0]}`
if [ ${PIPESTATUS[0]} -ne 0 ]; then
echo "couldn't find start pattern!" 1>&2
exit 1
fi
stop=`tail -n +$start < $3 | grep -n $2 | head -n1 | cut -d: -f1; exit ${PIPESTATUS[1]}`
if [ ${PIPESTATUS[0]} -ne 0 ]; then
echo "couldn't find end pattern!" 1>&2
exit 1
fi
stop=$(( $stop + $start - 1))
sed "$start,$stop!d" < $3
Execute the file with arguments (NOTE that the script does not handle spaces in arguments!):
To use with your example, use arguments: 1234 5555 myfile.txt
Includes lines with starting and stopping pattern.
It depends on the implementation of your JSON writer/parser. Microsoft's DataContractJsonSerializer seems to have a hard limit around 8kb (8192 I think), and it will error out for larger strings.
Edit: We were able to resolve the 8K limit for JSON strings by setting the MaxJsonLength property in the web config as described in this answer: https://stackoverflow.com/a/1151993/61569
In search of this same solution, I found what I needed under a different question in stackoverflow: Powershell-log-off-remote-session. The below one line will return a list of logged on users.
query user /server:$SERVER
Bash job control involves multiple processes, not multiple threads.
You can execute a command in background with the &
suffix.
You can wait for completion of a background command with the wait
command.
You can execute multiple commands in parallel by separating them with |
. This provides also a synchronization mechanism, since stdout of a command at left of |
is connected to stdin of command at right.
This can also be achieved using the Lambda based approach of Linq;
var list = ctn.Items
.Where(t=> t.DeliverySelection == true && t.Delivery.SentForDelivery == null)
.OrderBy(t => t.Delivery.SubmissionDate)
.Take(5);
other variation can be
const green= "Green";
const color : Color = Color[green] as Color;
You can create a jQuery function to unload Bootstrap CSS files at the size of 768px, and load it back when resized to lower width. This way you can design a mobile website without touching the desktop version, by using col-xs-* only
function resize() {
if ($(window).width() > 767) {
$('link[rel=stylesheet][href~="bootstrap.min.css"]').prop('disabled', true);
$('link[rel=stylesheet][href~="bootstrap-theme.min.css"]').prop('disabled', true);
}
else {
$('link[rel=stylesheet][href~="bootstrap.min.css"]').prop('disabled', false);
$('link[rel=stylesheet][href~="bootstrap-theme.min.css"]').prop('disabled', false);
}
}
and
$(document).ready(function() {
$(window).resize(resize);
resize();
if ($(window).width() > 767) {
$('link[rel=stylesheet][href~="bootstrap.min.css"]').prop('disabled', true);
$('link[rel=stylesheet][href~="bootstrap-theme.min.css"]').prop('disabled', true);
}
});
Google crawlers are not smart enough, they can't crawl relative URLs, that's why it's always recommended to use absolute URL's for better crawlability and indexability.
Therefore, you can not use this variation
> sitemap: /sitemap.xml
Recommended syntax is
Sitemap: https://www.yourdomain.com/sitemap.xml
Note:
If you want to only log the stack trace of the error (and not the error message) Node 6 and above automatically includes the error name and message inside the stack trace, which is a bit annoying if you want to do some custom error handling:
console.log(error.stack.replace(error.message, ''))
This workaround will log only the error name and stack trace (so you can, for example, format the error message and display it how you want somewhere else in your code).
The above example would print only the error name follow by the stack trace, for example:
Error:
at /Users/cfisher/Git/squashed/execProcess.js:6:17
at ChildProcess.exithandler (child_process.js:213:5)
at emitTwo (events.js:106:13)
at ChildProcess.emit (events.js:191:7)
at maybeClose (internal/child_process.js:877:16)
at Socket.<anonymous> (internal/child_process.js:334:11)
at emitOne (events.js:96:13)
at Socket.emit (events.js:188:7)
at Pipe._handle.close [as _onclose] (net.js:498:12)
Instead of:
Error: Error: Command failed: sh ./commands/getBranchCommitCount.sh HEAD
git: 'rev-lists' is not a git command. See 'git --help'.
Did you mean this?
rev-list
at /Users/cfisher/Git/squashed/execProcess.js:6:17
at ChildProcess.exithandler (child_process.js:213:5)
at emitTwo (events.js:106:13)
at ChildProcess.emit (events.js:191:7)
at maybeClose (internal/child_process.js:877:16)
at Socket.<anonymous> (internal/child_process.js:334:11)
at emitOne (events.js:96:13)
at Socket.emit (events.js:188:7)
at Pipe._handle.close [as _onclose] (net.js:498:12)
What you are doing is correct, the problem is somewhere else, e.g. the cookie is being set again somehow on refresh.
Using null
is fine for one of the branches of a ternary expression. And a ternary expression is fine as a statement in Javascript.
As a matter of style, though, if you have in mind invoking a procedure, it's clearer to write this using if..else:
if (x==2) doSomething;
else doSomethingElse
or, in your case,
if (x==2) doSomething;
if you want to encode or decode an array from or to JSON you can use these functions
$myJSONString = json_encode($myArray);
$myArray = json_decode($myString);
json_encode will result in a JSON string, built from an (multi-dimensional) array. json_decode will result in an Array, built from a well formed JSON string
with json_decode you can take the results from the API and only output what you want, for example:
echo $myArray['payload']['ign'];
As @Peter Cullen answer mention, your script will meet browser timeout first. So its good idea to provide some log output, then flush()
, but connection have buffer and you'll not see anything unless much output provided. Here are code snippet what helps provide reliable log:
set_time_limit(0);
...
print "log message";
print "<!--"; print str_repeat (' ', 4000); print "-->"; flush();
print "log message";
print "<!--"; print str_repeat (' ', 4000); print "-->"; flush();
Addition to most voted answer.
I want to add some words about obtainStyledAttributes() usage, when we create custom view using android:xxx prdefined attributes. Especially when we use TextAppearance.
As was mentioned in "2. Creating constructors", custom view gets AttributeSet on its creation. Main usage we can see in TextView source code (API 16).
final Resources.Theme theme = context.getTheme();
// TextAppearance is inspected first, but let observe it later
TypedArray a = theme.obtainStyledAttributes(
attrs, com.android.internal.R.styleable.TextView, defStyle, 0);
int n = a.getIndexCount();
for (int i = 0; i < n; i++)
{
int attr = a.getIndex(i);
// huge switch with pattern value=a.getXXX(attr) <=> a.getXXX(a.getIndex(i))
}
a.recycle();
What we can see here?
obtainStyledAttributes(AttributeSet set, int[] attrs, int defStyleAttr, int defStyleRes)
Attribute set is processed by theme according to documentation. Attribute values are compiled step by step. First attributes are filled from theme, then values are replaced by values from style, and finally exact values from XML for special view instance replace others.
Array of requested attributes - com.android.internal.R.styleable.TextView
It is an ordinary array of constants. If we are requesting standard attributes, we can build this array manually.
What is not mentioned in documentation - order of result TypedArray elements.
When custom view is declared in attrs.xml, special constants for attribute indexes are generated. And we can extract values this way: a.getString(R.styleable.MyCustomView_android_text)
. But for manual int[]
there are no constants. I suppose, that getXXXValue(arrayIndex) will work fine.
And other question is: "How we can replace internal constants, and request standard attributes?" We can use android.R.attr.* values.
So if we want to use standard TextAppearance attribute in custom view and read its values in constructor, we can modify code from TextView this way:
ColorStateList textColorApp = null;
int textSize = 15;
int typefaceIndex = -1;
int styleIndex = -1;
Resources.Theme theme = context.getTheme();
TypedArray a = theme.obtainStyledAttributes(attrs, R.styleable.CustomLabel, defStyle, 0);
TypedArray appearance = null;
int apResourceId = a.getResourceId(R.styleable.CustomLabel_android_textAppearance, -1);
a.recycle();
if (apResourceId != -1)
{
appearance =
theme.obtainStyledAttributes(apResourceId, new int[] { android.R.attr.textColor, android.R.attr.textSize,
android.R.attr.typeface, android.R.attr.textStyle });
}
if (appearance != null)
{
textColorApp = appearance.getColorStateList(0);
textSize = appearance.getDimensionPixelSize(1, textSize);
typefaceIndex = appearance.getInt(2, -1);
styleIndex = appearance.getInt(3, -1);
appearance.recycle();
}
Where CustomLabel is defined:
<declare-styleable name="CustomLabel">
<!-- Label text. -->
<attr name="android:text" />
<!-- Label text color. -->
<attr name="android:textColor" />
<!-- Combined text appearance properties. -->
<attr name="android:textAppearance" />
</declare-styleable>
Maybe, I'm mistaken some way, but Android documentation on obtainStyledAttributes() is very poor.
At the same time we can just extend standard UI component, using all its declared attributes. This approach is not so good, because TextView for instance declares a lot of properties. And it will be impossible to implement full functionality in overriden onMeasure() and onDraw().
But we can sacrifice theoretical wide reusage of custom component. Say "I know exactly what features I will use", and don't share code with anybody.
Then we can implement constructor CustomComponent(Context, AttributeSet, defStyle)
.
After calling super(...)
we will have all attributes parsed and available through getter methods.
Well, var x = new Array()
is different than var x = []
is different in some features I'll just explain the most useful two (in my opinion) of them.
Before I get into expalining the differences, I will set a base first; when we use x = []
defines a new variable with data type of Array, and it inherits all the methods that belong to the array prototype, something pretty similar (but not exactly) to extending a class. However, when we use x = new Array()
it initilizes a clone of the array prototype assigned to the variable x
.
Now let's see what are the difference
The First Difference is that using new Array(x)
where x
is an integer, initilizes an array of x
undefined values, for example new Array(16)
will initialize an array with 16 items all of them are undefined. This is very useful when you asynchronously fill an array of a predefined length.
For example (again :) ) let's say you are getting the results of 100 competitiors, and you're receiving them asynchronously from a remote system or db, then you'll need to allocate them in the array according to the rank once you receive each result. In this very rare case you will do something like myArray[result.rank - 1] = result.name
, so the rank 1 will be set to the index 0 and so on.
The second difference is that using new Array()
as you already know, instanciates a whole new clone of the array prototype and assigns it to your variable, that allows you to do some magic (not recommended btw). This magic is that you can overwrite a specific method of the legacy array methods. So, for example you can set the Array.push
method to push the new value to the beginning of the array instead of the end, and you can also add new methods (this is better) to this specific clone of the Array Prototype. That will allow you to define more complex types of arrays throughout your project with your own added methods and use it as a class.
Last thing, if you're from the very few people (that I truly love) that care about processing overhead and memory consumption of your app, you'd never tough new Array()
without being desperate to use it :).
I hope that has explained enough about the beast new Array()
:)
For now i think best emulator is https://app.crossbrowsertesting.com
It has real sizes and virtual keyboard (that is the most important thing) , zooming events...
Also https://appetize.io/demo has same things but it has time limit.
Since C# 7.0 supports using static
directive and Local functions you don't need preprocessor macros for most cases.
Found following solution working for my similar problem:
private ExtendedHashMap mData = new ExtendedHashMap();
private String[] mKeys;
public void setNewData(ExtendedHashMap data) {
mData.putAll(data);
mKeys = data.keySet().toArray(new String[data.size()]);
notifyDataSetChanged();
}
Using the clear-command
mData.clear()
is not nessescary
Create a file called 'k.sh', add the following text and place in your home directory (~):
winpty "C:\Program Files (x86)\Kinesics Text Editor\x64\k.exe" $1
At the git prompt type:
git config --global core.editor ~/k.sh
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
Button b1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1=(Button)findViewById(R.id.button);
b1.setOnClickListener(this);
}
@Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(),"Button is Working",Toast.LENGTH_LONG).show();
}
}
calloc
allocates the requested memory and returns a pointer to it. It also sets allocated memory to zero.
In case you are planning to use your string
as empty string all the time:
char *string = NULL;
string = (char*)calloc(1, sizeof(char));
In case you are planning to store some value in your string
later:
char *string = NULL;
int numberOfChars = 50; // you can use as many as you need
string = (char*)calloc(numberOfChars + 1, sizeof(char));
There's also solution for Node JS app. CORS Anywhere is a NodeJS proxy which adds CORS headers to the proxied request.
The url to proxy is literally taken from the path, validated and proxied. The protocol part of the proxied URI is optional, and defaults to "http". If port 443 is specified, the protocol defaults to "https".
This package does not put any restrictions on the http methods or headers, except for cookies. Requesting user credentials is disallowed. The app can be configured to require a header for proxying a request, for example to avoid a direct visit from the browser. https://robwu.nl/cors-anywhere.html
For my case, I was trying to execute procedure code in MySQL, and due to some issue with server in which Server can't figure out where to end the statement I was getting Error Code 1064. So I wrapped the procedure with custom DELIMITER and it worked fine.
For example, Before it was:
DROP PROCEDURE IF EXISTS getStats;
CREATE PROCEDURE `getStats` (param_id INT, param_offset INT, param_startDate datetime, param_endDate datetime)
BEGIN
/*Procedure Code Here*/
END;
After putting DELIMITER it was like this:
DROP PROCEDURE IF EXISTS getStats;
DELIMITER $$
CREATE PROCEDURE `getStats` (param_id INT, param_offset INT, param_startDate datetime, param_endDate datetime)
BEGIN
/*Procedure Code Here*/
END;
$$
DELIMITER ;
The underscore is simply a convention; nothing more. As such, its use is always somewhat different to each person. Here's how I understand them for the two languages in question:
In C++, an underscore usually indicates a private member variable.
In C#, I usually see it used only when defining the underlying private member variable for a public property. Other private member variables would not have an underscore. This usage has largely gone to the wayside with the advent of automatic properties though.
Before:
private string _name;
public string Name
{
get { return this._name; }
set { this._name = value; }
}
After:
public string Name { get; set; }
To delete via SQL
Item.delete_all # accepts optional conditions
To delete by calling each model's destroy method (expensive but ensures callbacks are called)
Item.destroy_all # accepts optional conditions
All here
Ok, adding to the answers stated you might be also looking for
IEnumerable<string> m_oEnum = Enumerable.Empty<string>();
or
IEnumerable<string> m_oEnum = new string[]{};
In my case I had folder name Newtonsoft.Json.6.0.7
but .csproj
file had path though folder ...\Newtonsoft.Json.6.0.5\...
Changing .csproj
file to have 6.0.7 fixed the problem.
I'm currently using Windows and needed to develop a PDF parser but adding a new environment variable via sysdm.cpl
alone did not work. For other Windows user, I strongly suggest adding C:\Program Files (x86)\Tesseract-OCR
to your profile.ps1
as well (if using Powershell that is).
Can we guarantee it will not die?
As long there is no reference returned, it's perfectly fine to do so. words
will be moved to the variable receiving the result.
The local variable will go out of scope. after it was moved (or copied).
Thread
or AsyncTask
for long-running operations (50ms+). Test your app to see where that is. Most operations (probably) don't require a thread, because most operations (probably) only involve a few rows. Use a thread for bulk operations.SQLiteDatabase
instance for each DB on disk between threads and implement a counting system to keep track of open connections.Are there any best practices for these scenarios?
Share a static field between all your classes. I used to keep a singleton around for that and other things that need to be shared. A counting scheme (generally using AtomicInteger) also should be used to make sure you never close the database early or leave it open.
My solution:
The old version I wrote is available at https://github.com/Taeluf/dev/tree/main/archived/databasemanager and is not maintained. If you want to understand my solution, look at the code and read my notes. My notes are usually pretty helpful.
DatabaseManager
. (or download it from github)DatabaseManager
and implement onCreate
and onUpgrade
like you normally would. You can create multiple subclasses of the one DatabaseManager
class in order to have different databases on disk.getDb()
to use the SQLiteDatabase
class.close()
for each subclass you instantiatedThe code to copy/paste:
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import java.util.concurrent.ConcurrentHashMap;
/** Extend this class and use it as an SQLiteOpenHelper class
*
* DO NOT distribute, sell, or present this code as your own.
* for any distributing/selling, or whatever, see the info at the link below
*
* Distribution, attribution, legal stuff,
* See https://github.com/JakarCo/databasemanager
*
* If you ever need help with this code, contact me at [email protected] (or [email protected] )
*
* Do not sell this. but use it as much as you want. There are no implied or express warranties with this code.
*
* This is a simple database manager class which makes threading/synchronization super easy.
*
* Extend this class and use it like an SQLiteOpenHelper, but use it as follows:
* Instantiate this class once in each thread that uses the database.
* Make sure to call {@link #close()} on every opened instance of this class
* If it is closed, then call {@link #open()} before using again.
*
* Call {@link #getDb()} to get an instance of the underlying SQLiteDatabse class (which is synchronized)
*
* I also implement this system (well, it's very similar) in my <a href="http://androidslitelibrary.com">Android SQLite Libray</a> at http://androidslitelibrary.com
*
*
*/
abstract public class DatabaseManager {
/**See SQLiteOpenHelper documentation
*/
abstract public void onCreate(SQLiteDatabase db);
/**See SQLiteOpenHelper documentation
*/
abstract public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion);
/**Optional.
* *
*/
public void onOpen(SQLiteDatabase db){}
/**Optional.
*
*/
public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {}
/**Optional
*
*/
public void onConfigure(SQLiteDatabase db){}
/** The SQLiteOpenHelper class is not actually used by your application.
*
*/
static private class DBSQLiteOpenHelper extends SQLiteOpenHelper {
DatabaseManager databaseManager;
private AtomicInteger counter = new AtomicInteger(0);
public DBSQLiteOpenHelper(Context context, String name, int version, DatabaseManager databaseManager) {
super(context, name, null, version);
this.databaseManager = databaseManager;
}
public void addConnection(){
counter.incrementAndGet();
}
public void removeConnection(){
counter.decrementAndGet();
}
public int getCounter() {
return counter.get();
}
@Override
public void onCreate(SQLiteDatabase db) {
databaseManager.onCreate(db);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
databaseManager.onUpgrade(db, oldVersion, newVersion);
}
@Override
public void onOpen(SQLiteDatabase db) {
databaseManager.onOpen(db);
}
@Override
public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
databaseManager.onDowngrade(db, oldVersion, newVersion);
}
@Override
public void onConfigure(SQLiteDatabase db) {
databaseManager.onConfigure(db);
}
}
private static final ConcurrentHashMap<String,DBSQLiteOpenHelper> dbMap = new ConcurrentHashMap<String, DBSQLiteOpenHelper>();
private static final Object lockObject = new Object();
private DBSQLiteOpenHelper sqLiteOpenHelper;
private SQLiteDatabase db;
private Context context;
/** Instantiate a new DB Helper.
* <br> SQLiteOpenHelpers are statically cached so they (and their internally cached SQLiteDatabases) will be reused for concurrency
*
* @param context Any {@link android.content.Context} belonging to your package.
* @param name The database name. This may be anything you like. Adding a file extension is not required and any file extension you would like to use is fine.
* @param version the database version.
*/
public DatabaseManager(Context context, String name, int version) {
String dbPath = context.getApplicationContext().getDatabasePath(name).getAbsolutePath();
synchronized (lockObject) {
sqLiteOpenHelper = dbMap.get(dbPath);
if (sqLiteOpenHelper==null) {
sqLiteOpenHelper = new DBSQLiteOpenHelper(context, name, version, this);
dbMap.put(dbPath,sqLiteOpenHelper);
}
//SQLiteOpenHelper class caches the SQLiteDatabase, so this will be the same SQLiteDatabase object every time
db = sqLiteOpenHelper.getWritableDatabase();
}
this.context = context.getApplicationContext();
}
/**Get the writable SQLiteDatabase
*/
public SQLiteDatabase getDb(){
return db;
}
/** Check if the underlying SQLiteDatabase is open
*
* @return whether the DB is open or not
*/
public boolean isOpen(){
return (db!=null&&db.isOpen());
}
/** Lowers the DB counter by 1 for any {@link DatabaseManager}s referencing the same DB on disk
* <br />If the new counter is 0, then the database will be closed.
* <br /><br />This needs to be called before application exit.
* <br />If the counter is 0, then the underlying SQLiteDatabase is <b>null</b> until another DatabaseManager is instantiated or you call {@link #open()}
*
* @return true if the underlying {@link android.database.sqlite.SQLiteDatabase} is closed (counter is 0), and false otherwise (counter > 0)
*/
public boolean close(){
sqLiteOpenHelper.removeConnection();
if (sqLiteOpenHelper.getCounter()==0){
synchronized (lockObject){
if (db.inTransaction())db.endTransaction();
if (db.isOpen())db.close();
db = null;
}
return true;
}
return false;
}
/** Increments the internal db counter by one and opens the db if needed
*
*/
public void open(){
sqLiteOpenHelper.addConnection();
if (db==null||!db.isOpen()){
synchronized (lockObject){
db = sqLiteOpenHelper.getWritableDatabase();
}
}
}
}
As an alternative:
Using CROSS APPLY and VALUES performs this operation quite simply and efficiently with just a single pass of the table (unlike union queries that do one pass for every column)
SELECT
ca.ColName, ca.ColValue
FROM YOurTable
CROSS APPLY (
Values
('ScripName' , ScripName),
('ScripCode' , ScripCode),
('Price' , cast(Price as varchar(50)) )
) as CA (ColName, ColValue)
Personally I find this syntax easier than using unpivot.
NB: You must take care that all source columns are converted into compatible types for the single value column
There are few steps you can follow
remove repository folder
C:/Users/user_name/.m2
Then run command using IDE terminal or open cmd in your project folder
mvn clean install
Restart your ide
If not solve your problem then run this command
mvn idea:idea
TEXT is a data-type for text based input. On the other hand, you have BLOB and CLOB which are more suitable for data storage (images, etc) due to their larger capacity limits (4GB for example).
As for the difference between BLOB and CLOB, I believe CLOB has character encoding associated with it, which implies it can be suited well for very large amounts of text.
BLOB and CLOB data can take a long time to retrieve, relative to how quick data from a TEXT field can be retrieved. So, use only what you need.
Just another way...
var elmo = {
color: 'red',
annoying: true,
height: 'unknown',
meta: { one: '1', two: '2'}
}
var subset = [elmo].map(x => ({
color: x.color,
height: x.height
}))[0]
You can use this function with an array of Objects =)
The hint is, the output file is created even if you get this error. The automatic deconstruction of vector starts after your code executed. Elements in the vector are deconstructed as well. This is most probably where the error occurs. The way you access the vector is through vector::operator[]
with an index read from stream. Try vector::at()
instead of vector::operator[]
. This won't solve your problem, but will show which assignment to the vector causes error.
As the official document: As of 1.9, a string is only considered to be HTML if it starts with a less-than ("<") character. The Migrate plugin can be used to restore the pre-1.9 behavior.
If a string is known to be HTML but may start with arbitrary text that is not an HTML tag, pass it to jQuery.parseHTML() which will return an array of DOM nodes representing the markup. A jQuery collection can be created from this, for example: $($.parseHTML(htmlString))
. This would be considered best practice when processing HTML templates for example. Simple uses of literal strings such as $("<p>Testing</p>").appendTo("body")
are unaffected by this change.
short answer, specific to OAuth2,
Downloading Wget is not necessary; the .NET Framework has web client classes built in.
$wc = New-Object system.Net.WebClient;
$sms = Read-Host "Enter SMS text";
$sms = [System.Web.HttpUtility]::UrlEncode($sms);
$smsResult = $wc.downloadString("http://smsserver/SNSManager/msgSend.jsp?uid&to=smartsms:*+001XXXXXX&msg=$sms&encoding=windows-1255")
You could use a negative look-ahead assertion:
^(?!tbd_).+
Or a negative look-behind assertion:
(^.{1,3}$|^.{4}(?<!tbd_).*)
Or just plain old character sets and alternations:
^([^t]|t($|[^b]|b($|[^d]|d($|[^_])))).*
I hope you find this helpful.
HTML :
<html>
<head>
<link rel = "stylesheet" href = "test.css">
<body>
</body>
<script src = "test.js"></script>
</head>
</html>
JAVASCRIPT :
var tableString = "<table>",
body = document.getElementsByTagName('body')[0],
div = document.createElement('div');
for (row = 1; row < 101; row += 1) {
tableString += "<tr>";
for (col = 1; col < 11; col += 1) {
tableString += "<td>" + "row [" + row + "]" + "col [" + col + "]" + "</td>";
}
tableString += "</tr>";
}
tableString += "</table>";
div.innerHTML = tableString;
body.appendChild(div);
SJLJ (setjmp/longjmp): – available for 32 bit and 64 bit – not “zero-cost”: even if an exception isn’t thrown, it incurs a minor performance penalty (~15% in exception heavy code) – allows exceptions to traverse through e.g. windows callbacks
DWARF (DW2, dwarf-2) – available for 32 bit only – no permanent runtime overhead – needs whole call stack to be dwarf-enabled, which means exceptions cannot be thrown over e.g. Windows system DLLs.
SEH (zero overhead exception) – will be available for 64-bit GCC 4.8.
source: https://wiki.qt.io/MinGW-64-bit
This problem has two parts:
1) Getting the index path of UITableViewCell
which contains pressed UIButton
There are some suggestions like:
Updating UIButton
's tag
in cellForRowAtIndexPath:
method using index path's row
value. This is not an good solution as it requires updating tag
continuously and it does not work with table views with more than one section.
Adding an NSIndexPath
property to custom cell and updating it instead of UIButton
's tag
in cellForRowAtIndexPath:
method. This solves multiple section problem but still not good as it requires updating always.
Keeping a weak refence to parent UITableView
in the custom cell while creating it and using indexPathForCell:
method to get the index path. Seems a little bit better, no need to update anything in cellForRowAtIndexPath:
method, but still requires setting a weak reference when the custom cell is created.
Using cell's superView
property to get a reference to parent UITableView
. No need to add any properties to the custom cell, and no need to set/update anything on creation/later. But cell's superView
depends on iOS implementation details. So it can not be used directly.
But this can be achieved using a simple loop, as we are sure the cell in question has to be in a UITableView:
UIView* view = self;
while (view && ![view isKindOfClass:UITableView.class])
view = view.superview;
UITableView* parentTableView = (UITableView*)view;
So, these suggestions can be combined into a simple and safe custom cell method for getting the index path:
- (NSIndexPath *)indexPath
{
UIView* view = self;
while (view && ![view isKindOfClass:UITableView.class])
view = view.superview;
return [(UITableView*)view indexPathForCell:self];
}
From now on, this method can be used to detect which UIButton
is pressed.
2) Informing other parties about button press event
After internally knowing which UIButton
is pressed in which custom cell with exact index path, this information needs to be sent to other parties (most probably the view controller handling the UITableView
). So, this button click event can be handled in a similar abstraction and logic level to didSelectRowAtIndexPath:
method of UITableView delegate.
Two approaches can be used for this:
a) Delegation: custom cell can have a delegate
property and can define a protocol. When button is pressed it just performs it's delegate methods on it's delegate
property. But this delegate
property needs to be set for each custom cell when they are created. As an alternative, custom cell can choose to perform its delegate methods on it's parent table view's delegate
too.
b) Notification Center: custom cells can define a custom notification name and post this notification with the index path and parent table view information provided in userInfo
object. No need to set anything for each cell, just adding an observer for the custom cell's notification is enough.
very easy 1- install pakage :
pip install mouse
2- add library to project :
import mouse
3- use it for example :
mouse.right_click()
in this url describe all function that you can use it :
You're setting overflow: hidden
. This will hide anything that's too large for the <div>
, meaning scrollbars won't be shown. Give your <div>
an explicit width and/or height, and change overflow
to auto
:
.scroll {
width: 200px;
height: 400px;
overflow: scroll;
}
If you only want to show a scrollbar if the content is longer than the <div>
, change overflow
to overflow: auto
. You can also only show one scrollbar by using overflow-y
or overflow-x
.
The solution is to simply reinstall ggplot2
. Maybe there is an incompatibility between the R version you are using, and your installed version of ggplot2
. Alternatively, something might have gone wrong while installing ggplot2
earlier, causing the issue you see.
One option is to use regular expressions:
if (str.match("^Hello")) {
// do this if begins with Hello
}
if (str.match("World$")) {
// do this if ends in world
}
Here's one sample: http://jsfiddle.net/CUUfb/1/
It seems to be easier in CSS:
<style type="text/css">
p.capitalize {text-transform:capitalize;}
</style>
<p class="capitalize">This is some text.</p>
This is from CSS text-transform Property (at W3Schools).
Take this answer updated for PyQt5, python 3.4
Use this as a pattern to start a worker that does not take data and return data as they are available to the form.
1 - Worker class is made smaller and put in its own file worker.py for easy memorization and independent software reuse.
2 - The main.py file is the file that defines the GUI Form class
3 - The thread object is not subclassed.
4 - Both thread object and the worker object belong to the Form object
5 - Steps of the procedure are within the comments.
# worker.py
from PyQt5.QtCore import QThread, QObject, pyqtSignal, pyqtSlot
import time
class Worker(QObject):
finished = pyqtSignal()
intReady = pyqtSignal(int)
@pyqtSlot()
def procCounter(self): # A slot takes no params
for i in range(1, 100):
time.sleep(1)
self.intReady.emit(i)
self.finished.emit()
And the main file is:
# main.py
from PyQt5.QtCore import QThread
from PyQt5.QtWidgets import QApplication, QLabel, QWidget, QGridLayout
import sys
import worker
class Form(QWidget):
def __init__(self):
super().__init__()
self.label = QLabel("0")
# 1 - create Worker and Thread inside the Form
self.obj = worker.Worker() # no parent!
self.thread = QThread() # no parent!
# 2 - Connect Worker`s Signals to Form method slots to post data.
self.obj.intReady.connect(self.onIntReady)
# 3 - Move the Worker object to the Thread object
self.obj.moveToThread(self.thread)
# 4 - Connect Worker Signals to the Thread slots
self.obj.finished.connect(self.thread.quit)
# 5 - Connect Thread started signal to Worker operational slot method
self.thread.started.connect(self.obj.procCounter)
# * - Thread finished signal will close the app if you want!
#self.thread.finished.connect(app.exit)
# 6 - Start the thread
self.thread.start()
# 7 - Start the form
self.initUI()
def initUI(self):
grid = QGridLayout()
self.setLayout(grid)
grid.addWidget(self.label,0,0)
self.move(300, 150)
self.setWindowTitle('thread test')
self.show()
def onIntReady(self, i):
self.label.setText("{}".format(i))
#print(i)
app = QApplication(sys.argv)
form = Form()
sys.exit(app.exec_())
Passing params
GET request to "/cars/honda"
returns a list of Honda car models
Passing query
GET request to "/car/honda?color=blue"
returns a list of Honda car models, but filtered so only models with an stock color of blue are returned.
It doesn't make sense to add those filters into the URL parameters (/car/honda/color/blue) because according to REST, that would imply that we want to get a bunch of information about the color "blue". Since what we really want is a filtered list of Honda models, we use query strings to filter down the results that get returned.
Notice that the query strings are really just { key: value } pairs in a slightly different format: ?key1=value1&key2=value2&key3=value3.
In python a list knows its length, so you can just do len(sys.argv)
to get the number of elements in argv
.
I will explain with simple example
[1,3,2] <=> [2,2,2]
Ruby will start comparing each element of both array from left hand side.
1
for left array is smaller than 2
of right array. Hence left array is smaller than right array. Output will be -1
.
[2,3,2] <=> [2,2,2]
As above it will first compare first element which are equal then it will compare second element, in this case second element of left array is greater hence output is 1
.
class.method
should work.
class SomeClass:
@classmethod
def some_class_method(cls):
pass
@staticmethod
def some_static_method():
pass
SomeClass.some_class_method()
SomeClass.some_static_method()
//Array is shorted and if writing in C/C++ think of XOR implementations in java as follows.
int num=-1;
for (int i=1; i<=100; i++){
num =2*i;
if(arr[num]==0){
System.out.println("index: "+i+" Array position: "+ num);
break;
}
else if(arr[num-1]==0){
System.out.println("index: "+i+ " Array position: "+ (num-1));
break;
}
}// use Rabbit and tortoise race, move the dangling index faster,
//learnt from Alogithimica, Ameerpet, hyderbad**
If you want to drop column(s) from the target data frame, but the column(s) are required for the join, you can do the following:
df1 = df1.merge(df2[['a', 'b', 'key1']], how = 'left',
left_on = 'key2', right_on = 'key1').drop('key1')
The .drop('key1')
part will prevent 'key1' from being kept in the resulting data frame, despite it being required to join in the first place.
Here is the solution for search and replace
function searchAndUpdate(name,replace){
var obj = array.filter(function ( obj ) {
return obj.name === name;
})[0];
obj.name = replace;
}
searchAndUpdate("string 2","New String 2");
Yes, you can do this in PHP e.g. in
Silex or Symfony3
using subrequest
$postParams = array(
'email' => $request->get('email'),
'agree_terms' => $request->get('agree_terms'),
);
$subRequest = Request::create('/register', 'POST', $postParams);
return $app->handle($subRequest, HttpKernelInterface::SUB_REQUEST, false);
Don't forget the awesome
git fetch -p
which fetches and prunes all origins.
Just adding to the answers already given, the solution using the string "nunique"
seems much faster, tested here on ~21M rows dataframe, then grouped to ~2M
%time _=g.agg({"id": lambda x: x.nunique()})
CPU times: user 3min 3s, sys: 2.94 s, total: 3min 6s
Wall time: 3min 20s
%time _=g.agg({"id": pd.Series.nunique})
CPU times: user 3min 2s, sys: 2.44 s, total: 3min 4s
Wall time: 3min 18s
%time _=g.agg({"id": "nunique"})
CPU times: user 14 s, sys: 4.76 s, total: 18.8 s
Wall time: 24.4 s
In my Jenkins instance (version 1.548) the configuration file is at:
/var/lib/jenkins/jobs/-the-project-name-/config.xml
Owned by jenkins user and jenkins group with 644 permissions. Copying the file to and from here should work. I haven't tried changing it directly but have backed-up the config from this spot in case the project needs to be setup again.
var video1;_x000D_
_x000D_
function onYouTubeIframeAPIReady(){_x000D_
player = new YT.Player("video1", {_x000D_
videoId: "id-number",_x000D_
width: 300,_x000D_
height: 200, _x000D_
playerVars: {_x000D_
"autoplay": 1, // and 0 means off_x000D_
"controls": 1,_x000D_
"showinfo": 0,_x000D_
"modestbranding": 0,_x000D_
"loop": 1,_x000D_
"fs": 0,_x000D_
"cc_load_policy": 0,_x000D_
"iv_load_policy": 3,_x000D_
},_x000D_
events: {_x000D_
'onReady': onPlayerReady_x000D_
}_x000D_
});_x000D_
}_x000D_
_x000D_
function onPlayerReady(event) {_x000D_
event.target.mute();_x000D_
event.target.setVolume(0); //this can be set from 0 to 100_x000D_
}
_x000D_
Remember that the sound will not be muted in IE and Safari.
The example above showing the import with ...sun.com/jsp/jstl/format is incorrect (meaning it didn't work for me).
Instead try the below -this import statement is valid
<%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %><%@ taglib uri="http://java.sun.com/jstl/core-rt" prefix="c-rt" %><%@ taglib uri="http://java.sun.com/jstl/fmt" prefix="fmt" %>
<html>
<head>
<title>Format Date</title>
</head>
<body>
<c-rt:set var="now" value="<%=new java.util.Date()%>" />
<table border="1" cellpadding="0" cellspacing="0"
style="border-collapse: collapse" bordercolor="#111111"
width="63%" id="AutoNumber2">
<tr>
<td width="100%" colspan="2" bgcolor="#0000FF">
<p align="center">
<b>
<font color="#FFFFFF" size="4">Formatting:
<fmt:formatDate value="${now}" type="both"
timeStyle="long" dateStyle="long" />
</font>
</b>
</p>
</td>
</tr>
Use the .Select()
after grouping:
var agencyContracts = _agencyContractsRepository.AgencyContracts
.GroupBy(ac => new
{
ac.AgencyContractID, // required by your view model. should be omited
// in most cases because group by primary key
// makes no sense.
ac.AgencyID,
ac.VendorID,
ac.RegionID
})
.Select(ac => new AgencyContractViewModel
{
AgencyContractID = ac.Key.AgencyContractID,
AgencyId = ac.Key.AgencyID,
VendorId = ac.Key.VendorID,
RegionId = ac.Key.RegionID,
Amount = ac.Sum(acs => acs.Amount),
Fee = ac.Sum(acs => acs.Fee)
});
You need to use the border property as seen here: jsFiddle
HTML:
<table width="770">
<tr>
<td class="border-left-bottom">picture (border only to the left and bottom ) </td>
<td>text</td>
</tr>
<tr>
<td>text</td>
<td class="border-left-bottom">picture (border only to the left and bottom) </td>
</tr>
</table>`
CSS:
td.border-left-bottom{
border-left: solid 1px #000;
border-bottom: solid 1px #000;
}
Here is a very useful step by step guideline for insert multi rows in Oracle:
https://livesql.oracle.com/apex/livesql/file/content_BM1LJQ87M5CNIOKPOWPV6ZGR3.html
The last step:
INSERT ALL
/* Everyone is a person, so insert all rows into people */
WHEN 1=1 THEN
INTO people (person_id, given_name, family_name, title)
VALUES (id, given_name, family_name, title)
/* Only people with an admission date are patients */
WHEN admission_date IS NOT NULL THEN
INTO patients (patient_id, last_admission_date)
VALUES (id, admission_date)
/* Only people with a hired date are staff */
WHEN hired_date IS NOT NULL THEN
INTO staff (staff_id, hired_date)
VALUES (id, hired_date)
WITH names AS (
SELECT 4 id, 'Ruth' given_name, 'Fox' family_name, 'Mrs' title,
NULL hired_date, DATE'2009-12-31' admission_date
FROM dual UNION ALL
SELECT 5 id, 'Isabelle' given_name, 'Squirrel' family_name, 'Miss' title ,
NULL hired_date, DATE'2014-01-01' admission_date
FROM dual UNION ALL
SELECT 6 id, 'Justin' given_name, 'Frog' family_name, 'Master' title,
NULL hired_date, DATE'2015-04-22' admission_date
FROM dual UNION ALL
SELECT 7 id, 'Lisa' given_name, 'Owl' family_name, 'Dr' title,
DATE'2015-01-01' hired_date, NULL admission_date
FROM dual
)
SELECT * FROM names
If you are using Python3 with pathlib
you can access os.stat()
information using the Path.stat()
method, which has the attribute st_size
(file size in bytes):
>>> from pathlib import Path
>>> mypath = Path("path/to/my/file")
>>> mypath.stat().st_size == 0 # True if empty
The comment by MK pointed me in the right direction.
In the case of Apache 2.4 and up, there are different defaults and a new directive.
I am running Apache 2.4.6, and I had to add the following directives to get it working:
SSLProxyEngine on
SSLProxyVerify none
SSLProxyCheckPeerCN off
SSLProxyCheckPeerName off
SSLProxyCheckPeerExpire off
This will put each item on a new line
VB.NET
mytext = responseFromServer.Replace("{", vbNewLine + "{")
C#
mytext = responseFromServer.Replace("{", Environment.NewLine + "{");
Same error can raise by mixing: tabs + spaces.
with open('/foo', 'w') as f:
(spaces OR tab) print f <-- success
(spaces AND tab) print f <-- fail
Simplyfing for the begginers:
If you want to select an element immediatly after another element you use the +
selector.
For example:
div + p
The "+" element selects all <p>
elements that are placed immediately after <div>
elements
If you want to learn more about selectors use this table
it is compatible with all the browsers, change values to fit your application
background: #fdfdfd;
background: -moz-linear-gradient(top, #fdfdfd 0%, #f6f6f6 60%, #f2f2f2 100%);
background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#fdfdfd), color-stop(60%,#f6f6f6), color-stop(100%,#f2f2f2));
background: -webkit-linear-gradient(top, #fdfdfd 0%,#f6f6f6 60%,#f2f2f2 100%);
background: -o-linear-gradient(top, #fdfdfd 0%,#f6f6f6 60%,#f2f2f2 100%);
background: -ms-linear-gradient(top, #fdfdfd 0%,#f6f6f6 60%,#f2f2f2 100%);
background: linear-gradient(to bottom, #fdfdfd 0%,#f6f6f6 60%,#f2f2f2 100%);
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#fdfdfd', endColorstr='#f2f2f2',GradientType=0
Here is a simple example of group by in .net core 2.1
var query = this.DbContext.Notifications.
Where(n=> n.Sent == false).
GroupBy(n => new { n.AppUserId })
.Select(g => new { AppUserId = g.Key, Count = g.Count() });
var query2 = from n in this.DbContext.Notifications
where n.Sent == false
group n by n.AppUserId into g
select new { id = g.Key, Count = g.Count()};
Which translates to:
SELECT [n].[AppUserId], COUNT(*) AS [Count]
FROM [Notifications] AS [n]
WHERE [n].[Sent] = 0
GROUP BY [n].[AppUserId]
You just want to set the field separator as .
using the -F
option and print the first field:
$ echo aaa0.bbb.ccc | awk -F'.' '{print $1}'
aaa0
Same thing but using cut:
$ echo aaa0.bbb.ccc | cut -d'.' -f1
aaa0
Or with sed
:
$ echo aaa0.bbb.ccc | sed 's/[.].*//'
aaa0
Even grep
:
$ echo aaa0.bbb.ccc | grep -o '^[^.]*'
aaa0
Is this what you are looking for?
Option Explicit
Public Sub addDataToTable(ByVal strTableName As String, ByVal strData As String, ByVal col As Integer)
Dim lLastRow As Long
Dim iHeader As Integer
With ActiveSheet.ListObjects(strTableName)
'find the last row of the list
lLastRow = ActiveSheet.ListObjects(strTableName).ListRows.Count
'shift from an extra row if list has header
If .Sort.Header = xlYes Then
iHeader = 1
Else
iHeader = 0
End If
End With
'add the data a row after the end of the list
ActiveSheet.Cells(lLastRow + 1 + iHeader, col).Value = strData
End Sub
It handles both cases whether you have header or not.
You can use require as well to render images like
//then in the render function of Jsx insert the mainLogo variable
class NavBar extends Component {
render() {
return (
<nav className="nav" style={nbStyle}>
<div className="container">
//right below here
<img src={require('./logoWhite.png')} style={nbStyle.logo} alt="fireSpot"/>
</div>
</nav>
);
}
}
For me the above solutions were close but added some unwanted /n's and dtype:object, so here's a modified version:
df.groupby(['name', 'month'])['text'].apply(lambda text: ''.join(text.to_string(index=False))).str.replace('(\\n)', '').reset_index()
We implemented two versions of this, one a simple multi thread pool that can execute many types of callables, making our lives much easier and the second version that uses processes, which is less flexible in terms of callables and requires and extra call to dill.
Setting frozen_pool to true will freeze execution until finish_pool_queue is called in either class.
Thread Version:
'''
Created on Nov 4, 2019
@author: Kevin
'''
from threading import Lock, Thread
from Queue import Queue
import traceback
from helium.loaders.loader_retailers import print_info
from time import sleep
import signal
import os
class ThreadPool(object):
def __init__(self, queue_threads, *args, **kwargs):
self.frozen_pool = kwargs.get('frozen_pool', False)
self.print_queue = kwargs.get('print_queue', True)
self.pool_results = []
self.lock = Lock()
self.queue_threads = queue_threads
self.queue = Queue()
self.threads = []
for i in range(self.queue_threads):
t = Thread(target=self.make_pool_call)
t.daemon = True
t.start()
self.threads.append(t)
def make_pool_call(self):
while True:
if self.frozen_pool:
#print '--> Queue is frozen'
sleep(1)
continue
item = self.queue.get()
if item is None:
break
call = item.get('call', None)
args = item.get('args', [])
kwargs = item.get('kwargs', {})
keep_results = item.get('keep_results', False)
try:
result = call(*args, **kwargs)
if keep_results:
self.lock.acquire()
self.pool_results.append((item, result))
self.lock.release()
except Exception as e:
self.lock.acquire()
print e
traceback.print_exc()
self.lock.release()
os.kill(os.getpid(), signal.SIGUSR1)
self.queue.task_done()
def finish_pool_queue(self):
self.frozen_pool = False
while self.queue.unfinished_tasks > 0:
if self.print_queue:
print_info('--> Thread pool... %s' % self.queue.unfinished_tasks)
sleep(5)
self.queue.join()
for i in range(self.queue_threads):
self.queue.put(None)
for t in self.threads:
t.join()
del self.threads[:]
def get_pool_results(self):
return self.pool_results
def clear_pool_results(self):
del self.pool_results[:]
Process Version:
'''
Created on Nov 4, 2019
@author: Kevin
'''
import traceback
from helium.loaders.loader_retailers import print_info
from time import sleep
import signal
import os
from multiprocessing import Queue, Process, Value, Array, JoinableQueue, Lock,\
RawArray, Manager
from dill import dill
import ctypes
from helium.misc.utils import ignore_exception
from mem_top import mem_top
import gc
class ProcessPool(object):
def __init__(self, queue_processes, *args, **kwargs):
self.frozen_pool = Value(ctypes.c_bool, kwargs.get('frozen_pool', False))
self.print_queue = kwargs.get('print_queue', True)
self.manager = Manager()
self.pool_results = self.manager.list()
self.queue_processes = queue_processes
self.queue = JoinableQueue()
self.processes = []
for i in range(self.queue_processes):
p = Process(target=self.make_pool_call)
p.start()
self.processes.append(p)
print 'Processes', self.queue_processes
def make_pool_call(self):
while True:
if self.frozen_pool.value:
sleep(1)
continue
item_pickled = self.queue.get()
if item_pickled is None:
#print '--> Ending'
self.queue.task_done()
break
item = dill.loads(item_pickled)
call = item.get('call', None)
args = item.get('args', [])
kwargs = item.get('kwargs', {})
keep_results = item.get('keep_results', False)
try:
result = call(*args, **kwargs)
if keep_results:
self.pool_results.append(dill.dumps((item, result)))
else:
del call, args, kwargs, keep_results, item, result
except Exception as e:
print e
traceback.print_exc()
os.kill(os.getpid(), signal.SIGUSR1)
self.queue.task_done()
def finish_pool_queue(self, callable=None):
self.frozen_pool.value = False
while self.queue._unfinished_tasks.get_value() > 0:
if self.print_queue:
print_info('--> Process pool... %s' % (self.queue._unfinished_tasks.get_value()))
if callable:
callable()
sleep(5)
for i in range(self.queue_processes):
self.queue.put(None)
self.queue.join()
self.queue.close()
for p in self.processes:
with ignore_exception: p.join(10)
with ignore_exception: p.terminate()
with ignore_exception: del self.processes[:]
def get_pool_results(self):
return self.pool_results
def clear_pool_results(self):
del self.pool_results[:]
def test(eg): print 'EG', eg
Call with either:
tp = ThreadPool(queue_threads=2)
tp.queue.put({'call': test, 'args': [random.randint(0, 100)]})
tp.finish_pool_queue()
or
pp = ProcessPool(queue_processes=2)
pp.queue.put(dill.dumps({'call': test, 'args': [random.randint(0, 100)]}))
pp.queue.put(dill.dumps({'call': test, 'args': [random.randint(0, 100)]}))
pp.finish_pool_queue()
Following code will do the task....
<?php
$contacts = array(
"[email protected]",
"[email protected]",
//....as many email address as you need
);
foreach($contacts as $contact) {
$to = $contact;
$subject = 'the subject';
$message = 'hello';
mail($to, $subject, $message, $headers);
}
?>
You can override the equals method of the class like:
@Override
public int hashCode() {
int hash = 0;
hash += (app != null ? app.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
HubRule other = (HubRule) object;
if (this.app.equals(other.app)) {
boolean operatorHubList = false;
if (other.operator != null ? this.operator != null ? this.operator
.equals(other.operator) : false : true) {
operatorHubList = true;
}
if (operatorHubList) {
return true;
} else {
return false;
}
} else {
return false;
}
}
Well, if you want to compare two object from a class you must implement in some way the equals and the hash code method
this is very basic method to send plain text email using mail function.
<?php
$to = '[email protected]';
$subject = 'This is subject';
$message = 'This is body of email';
$from = "From: FirstName LastName <[email protected]>";
mail($to,$subject,$message,$from);
for speed you can do this
WHERE date(created_at) ='2019-10-21'
In math, ? means FOR ALL.
Unicode character (\u2200, ?).
Try inserting this clearing div before the last </div>
<div style="clear: both; line-height: 0;"> </div>
itertools.combinations is your friend if you have Python 2.6 or greater. Otherwise, check the link for an implementation of an equivalent function.
import itertools
def findsubsets(S,m):
return set(itertools.combinations(S, m))
S: The set for which you want to find subsets
m: The number of elements in the subset
I have created a sample UI which shows the save and open file dialog. Click on save button to open save dialog and click on open button to open file dialog.
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class FileChooserEx {
public static void main(String[] args) {
Runnable r = new Runnable() {
@Override
public void run() {
new FileChooserEx().createUI();
}
};
EventQueue.invokeLater(r);
}
private void createUI() {
JFrame frame = new JFrame();
frame.setLayout(new BorderLayout());
JButton saveBtn = new JButton("Save");
JButton openBtn = new JButton("Open");
saveBtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
JFileChooser saveFile = new JFileChooser();
saveFile.showSaveDialog(null);
}
});
openBtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
JFileChooser openFile = new JFileChooser();
openFile.showOpenDialog(null);
}
});
frame.add(new JLabel("File Chooser"), BorderLayout.NORTH);
frame.add(saveBtn, BorderLayout.CENTER);
frame.add(openBtn, BorderLayout.SOUTH);
frame.setTitle("File Chooser");
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
This is maybe not the case of original OP question, but: if you exceeds the default max size, this maybe a symptom of some other issue you have. in my case, I had the warrning, but finally it turned into a FATAL ERROR: MarkCompactCollector: semi-space copy, fallback in old gen Allocation failed - JavaScript heap out of memory. the reason was that i dynamically imported the current module, so this ended up with an endless loop...
Take a look at this video tutorial about Autolayout, they explain it carefully
You can use try catch block to help with not found images
getProductImage(id) {
var images = require.context('@/assets/', false, /\.jpg$/)
let productImage = ''
try {
productImage = images(`./product${id}.jpg`)
} catch (error) {
productImage = images(`./no_image.jpg`)
}
return productImage
},
For what it's worth, here is a C# sample async implementation based on HttpListener and HttpClient (I use it to be able to connect Chrome in Android devices to IIS Express, that's the only way I found...).
And If you need HTTPS support, it shouldn't require more code, just certificate configuration: Httplistener with HTTPS support
// define http://localhost:5000 and http://127.0.0.1:5000/ to be proxies for http://localhost:53068
using (var server = new ProxyServer("http://localhost:53068", "http://localhost:5000/", "http://127.0.0.1:5000/"))
{
server.Start();
Console.WriteLine("Press ESC to stop server.");
while (true)
{
var key = Console.ReadKey(true);
if (key.Key == ConsoleKey.Escape)
break;
}
server.Stop();
}
....
public class ProxyServer : IDisposable
{
private readonly HttpListener _listener;
private readonly int _targetPort;
private readonly string _targetHost;
private static readonly HttpClient _client = new HttpClient();
public ProxyServer(string targetUrl, params string[] prefixes)
: this(new Uri(targetUrl), prefixes)
{
}
public ProxyServer(Uri targetUrl, params string[] prefixes)
{
if (targetUrl == null)
throw new ArgumentNullException(nameof(targetUrl));
if (prefixes == null)
throw new ArgumentNullException(nameof(prefixes));
if (prefixes.Length == 0)
throw new ArgumentException(null, nameof(prefixes));
RewriteTargetInText = true;
RewriteHost = true;
RewriteReferer = true;
TargetUrl = targetUrl;
_targetHost = targetUrl.Host;
_targetPort = targetUrl.Port;
Prefixes = prefixes;
_listener = new HttpListener();
foreach (var prefix in prefixes)
{
_listener.Prefixes.Add(prefix);
}
}
public Uri TargetUrl { get; }
public string[] Prefixes { get; }
public bool RewriteTargetInText { get; set; }
public bool RewriteHost { get; set; }
public bool RewriteReferer { get; set; } // this can have performance impact...
public void Start()
{
_listener.Start();
_listener.BeginGetContext(ProcessRequest, null);
}
private async void ProcessRequest(IAsyncResult result)
{
if (!_listener.IsListening)
return;
var ctx = _listener.EndGetContext(result);
_listener.BeginGetContext(ProcessRequest, null);
await ProcessRequest(ctx).ConfigureAwait(false);
}
protected virtual async Task ProcessRequest(HttpListenerContext context)
{
if (context == null)
throw new ArgumentNullException(nameof(context));
var url = TargetUrl.GetComponents(UriComponents.SchemeAndServer, UriFormat.Unescaped);
using (var msg = new HttpRequestMessage(new HttpMethod(context.Request.HttpMethod), url + context.Request.RawUrl))
{
msg.Version = context.Request.ProtocolVersion;
if (context.Request.HasEntityBody)
{
msg.Content = new StreamContent(context.Request.InputStream); // disposed with msg
}
string host = null;
foreach (string headerName in context.Request.Headers)
{
var headerValue = context.Request.Headers[headerName];
if (headerName == "Content-Length" && headerValue == "0") // useless plus don't send if we have no entity body
continue;
bool contentHeader = false;
switch (headerName)
{
// some headers go to content...
case "Allow":
case "Content-Disposition":
case "Content-Encoding":
case "Content-Language":
case "Content-Length":
case "Content-Location":
case "Content-MD5":
case "Content-Range":
case "Content-Type":
case "Expires":
case "Last-Modified":
contentHeader = true;
break;
case "Referer":
if (RewriteReferer && Uri.TryCreate(headerValue, UriKind.Absolute, out var referer)) // if relative, don't handle
{
var builder = new UriBuilder(referer);
builder.Host = TargetUrl.Host;
builder.Port = TargetUrl.Port;
headerValue = builder.ToString();
}
break;
case "Host":
host = headerValue;
if (RewriteHost)
{
headerValue = TargetUrl.Host + ":" + TargetUrl.Port;
}
break;
}
if (contentHeader)
{
msg.Content.Headers.Add(headerName, headerValue);
}
else
{
msg.Headers.Add(headerName, headerValue);
}
}
using (var response = await _client.SendAsync(msg).ConfigureAwait(false))
{
using (var os = context.Response.OutputStream)
{
context.Response.ProtocolVersion = response.Version;
context.Response.StatusCode = (int)response.StatusCode;
context.Response.StatusDescription = response.ReasonPhrase;
foreach (var header in response.Headers)
{
context.Response.Headers.Add(header.Key, string.Join(", ", header.Value));
}
foreach (var header in response.Content.Headers)
{
if (header.Key == "Content-Length") // this will be set automatically at dispose time
continue;
context.Response.Headers.Add(header.Key, string.Join(", ", header.Value));
}
var ct = context.Response.ContentType;
if (RewriteTargetInText && host != null && ct != null &&
(ct.IndexOf("text/html", StringComparison.OrdinalIgnoreCase) >= 0 ||
ct.IndexOf("application/json", StringComparison.OrdinalIgnoreCase) >= 0))
{
using (var ms = new MemoryStream())
{
using (var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false))
{
await stream.CopyToAsync(ms).ConfigureAwait(false);
var enc = context.Response.ContentEncoding ?? Encoding.UTF8;
var html = enc.GetString(ms.ToArray());
if (TryReplace(html, "//" + _targetHost + ":" + _targetPort + "/", "//" + host + "/", out var replaced))
{
var bytes = enc.GetBytes(replaced);
using (var ms2 = new MemoryStream(bytes))
{
ms2.Position = 0;
await ms2.CopyToAsync(context.Response.OutputStream).ConfigureAwait(false);
}
}
else
{
ms.Position = 0;
await ms.CopyToAsync(context.Response.OutputStream).ConfigureAwait(false);
}
}
}
}
else
{
using (var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false))
{
await stream.CopyToAsync(context.Response.OutputStream).ConfigureAwait(false);
}
}
}
}
}
}
public void Stop() => _listener.Stop();
public override string ToString() => string.Join(", ", Prefixes) + " => " + TargetUrl;
public void Dispose() => ((IDisposable)_listener)?.Dispose();
// out-of-the-box replace doesn't tell if something *was* replaced or not
private static bool TryReplace(string input, string oldValue, string newValue, out string result)
{
if (string.IsNullOrEmpty(input) || string.IsNullOrEmpty(oldValue))
{
result = input;
return false;
}
var oldLen = oldValue.Length;
var sb = new StringBuilder(input.Length);
bool changed = false;
var offset = 0;
for (int i = 0; i < input.Length; i++)
{
var c = input[i];
if (offset > 0)
{
if (c == oldValue[offset])
{
offset++;
if (oldLen == offset)
{
changed = true;
sb.Append(newValue);
offset = 0;
}
continue;
}
for (int j = 0; j < offset; j++)
{
sb.Append(input[i - offset + j]);
}
sb.Append(c);
offset = 0;
}
else
{
if (c == oldValue[0])
{
if (oldLen == 1)
{
changed = true;
sb.Append(newValue);
}
else
{
offset = 1;
}
continue;
}
sb.Append(c);
}
}
if (changed)
{
result = sb.ToString();
return true;
}
result = input;
return false;
}
}
sometimes those other directives in the content
tag can mess up Apple's best guess/heuristic at how to layout your page, all you need to disable pinch zoom is.
<meta name="viewport" content="user-scalable=no" />
Your second DELETE
query was nearly correct. Just be sure to put the table name (or an alias) between DELETE
and FROM
to specify which table you are deleting from. This is simpler than using a nested SELECT
statement like in the other answers.
DELETE tableA
FROM tableA
INNER JOIN tableB u on (u.qlabel = tableA.entityrole AND u.fieldnum = tableA.fieldnum)
WHERE (LENGTH(tableA.memotext) NOT IN (8,9,10)
OR tableA.memotext NOT LIKE '%/%/%')
AND (u.FldFormat = 'Date')
DELETE q
FROM tableA q
INNER JOIN tableB u on (u.qlabel = q.entityrole AND u.fieldnum = q.fieldnum)
WHERE (LENGTH(q.memotext) NOT IN (8,9,10)
OR q.memotext NOT LIKE '%/%/%')
AND (u.FldFormat = 'Date')
More examples here:
How to Delete using INNER JOIN with SQL Server?
https://code.google.com/p/worlddb/downloads/list
This database has multi languages country names, region names, city names and they's latitude and longitude number and country's alpha2 code .
I know this is quite late to answer this question but I resolved this problem by myself and thought worth sharing it with everyone.`
public void replaceFragment(BaseFragment fragment) {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
final FragmentManager fManager = getSupportFragmentManager();
BaseFragment fragm = (BaseFragment) fManager.findFragmentByTag(fragment.getFragmentTag());
transaction.setCustomAnimations(R.anim.enter_from_right, R.anim.exit_to_left, R.anim.enter_from_left, R.anim.exit_to_right);
if (fragm == null) { //here fragment is not available in the stack
transaction.replace(R.id.container, fragment, fragment.getFragmentTag());
transaction.addToBackStack(fragment.getFragmentTag());
} else {
//fragment was found in the stack , now we can reuse the fragment
// please do not add in back stack else it will add transaction in back stack
transaction.replace(R.id.container, fragm, fragm.getFragmentTag());
}
transaction.commit();
}
And in the onBackPressed()
@Override
public void onBackPressed() {
if(getSupportFragmentManager().getBackStackEntryCount()>1){
super.onBackPressed();
}else{
finish();
}
}
As you mentioned, there could be two below versions of defining a List:
List<? extends Map<String, String>>
List<?>
2 is very open. It can hold any object type. This may not be useful in case you want to have a map of a given type. In case someone accidentally puts a different type of map, for example, Map<String, int>
. Your consumer method might break.
In order to ensure that List
can hold objects of a given type, Java generics introduced ? extends
. So in #1, the List
can hold any object which is derived from Map<String, String>
type. Adding any other type of data would throw an exception.
string.find(character)
string.index(character)
Perhaps you'd like to have a look at the documentation to find out what the difference between the two is.
Something like this should work, if run in the controller:
$controller = $this;
$path = '/path/to/app/'
. $controller->module->getId() // only necessary if you're using modules
. '/' . $controller->getId()
. '/' . $controller->getAction()->getId()
. '/';
This assumes that you are using 'friendly' URLs in your app config.
This link goes to the best comparison chart around, directly from the Microsoft. It compares ALL aspects of all MS SQL server editions. To compare three editions you are asking about, just focus on the last three columns of every table in there.
Summary compiled from the above document:
* = contains the feature SQLEXPR SQLEXPRWT SQLEXPRADV ---------------------------------------------------------------------------- > SQL Server Core * * * > SQL Server Management Studio - * * > Distributed Replay – Admin Tool - * * > LocalDB - * * > SQL Server Data Tools (SSDT) - - * > Full-text and semantic search - - * > Specification of language in query - - * > some of Reporting services features - - *
Add the same color of the background to the paragraph and then invert with CSS:
div {_x000D_
background-color: #f00;_x000D_
}_x000D_
_x000D_
p { _x000D_
color: #f00;_x000D_
-webkit-filter: invert(100%);_x000D_
filter: invert(100%);_x000D_
}
_x000D_
<div>_x000D_
<p>inverted color</p>_x000D_
</div>
_x000D_
The fastest way is to do a*a
or a**2
or np.square(a)
whereas np.power(a, 2)
showed to be considerably slower.
np.power()
allows you to use different exponents for each element if instead of 2
you pass another array of exponents. From the comments of @GarethRees I just learned that this function will give you different results than a**2
or a*a
, which become important in cases where you have small tolerances.
I've timed some examples using NumPy 1.9.0 MKL 64 bit, and the results are shown below:
In [29]: a = np.random.random((1000, 1000))
In [30]: timeit a*a
100 loops, best of 3: 2.78 ms per loop
In [31]: timeit a**2
100 loops, best of 3: 2.77 ms per loop
In [32]: timeit np.power(a, 2)
10 loops, best of 3: 71.3 ms per loop
To fetch a branch that exists on remote, the simplest way is:
git fetch origin branchName
git checkout branchName
You can see if it already exists on remote with:
git branch -r
This will fetch the remote branch to your local and will automatically track the remote one.
The attribute selector syntax is [name=value]
where name
is the attribute name and value
is the attribute value.
So if you want to select all input
elements with the attribute name
having the value inputName[]
:
$('input[name="inputName[]"]')
And if you want to check for two attributes (here: name
and value
):
$('input[name="inputName[]"][value=someValue]')
I love the answers from Kiril V. Lyadvinsky and CC. but my problem was a little more specific than just case-insensitivity; I needed a lazy Unicode-supported command-line argument parser that could eliminate false-positives/negatives when dealing with alphanumeric string searches that could have special characters in the base string used to format alphanum keywords I was searching against, e.g., Wolfjäger
shouldn't match jäger
but <jäger>
should.
It's basically just Kiril/CC's answer with extra handling for alphanumeric exact-length matches.
/* Undefined behavior when a non-alpha-num substring parameter is used. */
bool find_alphanum_string_CI(const std::wstring& baseString, const std::wstring& subString)
{
/* Fail fast if the base string was smaller than what we're looking for */
if (subString.length() > baseString.length())
return false;
auto it = std::search(
baseString.begin(), baseString.end(), subString.begin(), subString.end(),
[](char ch1, char ch2)
{
return std::toupper(ch1) == std::toupper(ch2);
}
);
if(it == baseString.end())
return false;
size_t match_start_offset = it - baseString.begin();
std::wstring match_start = baseString.substr(match_start_offset, std::wstring::npos);
/* Typical special characters and whitespace to split the substring up. */
size_t match_end_pos = match_start.find_first_of(L" ,<.>;:/?\'\"[{]}=+-_)(*&^%$#@!~`");
/* Pass fast if the remainder of the base string where
the match started is the same length as the substring. */
if (match_end_pos == std::wstring::npos && match_start.length() == subString.length())
return true;
std::wstring extracted_match = match_start.substr(0, match_end_pos);
return (extracted_match.length() == subString.length());
}
Another answer could be to use the tar.gz file instead in the Linux case. There seem to be something like that also for the solaris platform. This way all files will already be in the expected format and there won't be any unpacking issues.
This should be understood in the context of GitHub forks (where you fork a GitHub repo on GitHub before cloning that fork locally).
upstream
generally refers to the original repo that you have forkeddownstream
” and “upstream
”" for more on upstream
term) origin
is your fork: your own repo on GitHub, clone of the original repo of GitHubFrom the GitHub page:
When a repo is cloned, it has a default remote called
origin
that points to your fork on GitHub, not the original repo it was forked from.
To keep track of the original repo, you need to add another remote namedupstream
git remote add upstream git://github.com/<aUser>/<aRepo.git>
(with aUser/aRepo
the reference for the original creator and repository, that you have forked)
You will use upstream
to fetch from the original repo (in order to keep your local copy in sync with the project you want to contribute to).
git fetch upstream
(git fetch
alone would fetch from origin
by default, which is not what is needed here)
You will use origin
to pull and push since you can contribute to your own repository.
git pull
git push
(again, without parameters, 'origin' is used by default)
You will contribute back to the upstream
repo by making a pull request.
Use style="display: none;"
. Also, you probably don't need to have the DIV, just setting the style to display: none
on the checkbox would probably be sufficient.
Easiest solution for your question, it worked in my case:
import string
def solve(s):
return string.capwords(s,' ')
s=input()
res=solve(s)
print(res)
I posted a general approach for troubleshooting the "DLL load failed" problem in this post on Windows systems. For reference:
Use the DLL dependency analyzer Dependencies to analyze
<Your Python Dir>\Lib\site-packages\tensorflow\python\_pywrap_tensorflow_internal.pyd
and determine the exact missing DLL (indicated by a?
beside the DLL). The path of the .pyd file is based on the TensorFlow 1.9 GPU version that I installed. I am not sure if the name and path is the same in other TensorFlow versions.Look for information of the missing DLL and install the appropriate package to resolve the problem.
You should be able to set the server.session.timeout
in your application.properties file.
ref: http://docs.spring.io/spring-boot/docs/1.4.x/reference/html/common-application-properties.html
Call make
command this way:
make CFLAGS=-Dvar=42
And be sure to use $(CFLAGS)
in your compile command in the Makefile. As @jørgensen mentioned , putting the variable assignment after the make
command will override the CFLAGS
value already defined the Makefile.
Alternatively you could set -Dvar=42
in another variable than CFLAGS
and then reuse this variable in CFLAGS
to avoid completely overriding CFLAGS
.
@jason-mccreary is totally right. Besides I recommend you this code to get more info in case of malfunction:
$rest = curl_exec($crl);
if ($rest === false)
{
// throw new Exception('Curl error: ' . curl_error($crl));
print_r('Curl error: ' . curl_error($crl));
}
curl_close($crl);
print_r($rest);
EDIT 1
To debug you can set CURLOPT_HEADER
to true to check HTTP response with firebug::net or similar.
curl_setopt($crl, CURLOPT_HEADER, true);
EDIT 2
About Curl error: SSL certificate problem, verify that the CA cert is OK
try adding this headers (just to debug, in a production enviroment you should keep these options in true
):
curl_setopt($crl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($crl, CURLOPT_SSL_VERIFYPEER, false);
With Underscore/Lodash:
General use case:
_.without(array, emptyVal, otherEmptyVal);
_.without([1, 2, 1, 0, 3, 1, 4], 0, 1);
With empties:
_.without(['foo', 'bar', '', 'baz', '', '', 'foobar'], '');
--> ["foo", "bar", "baz", "foobar"]
Here is a new one (Note: in Tech Preview stage): http://www.dot42.com
It is basically a Visual Studio add-in that lets you compile your C# code directly to DEX code. This means there is no run-time requirement such as Mono.
Disclosure: I work for this company
UPDATE: all sources are now on https://github.com/dot42
If you use Oracle 10 or higher you can use regexp functions as codaddict suggested. In earlier versions translate
function will help you:
select * from tablename where translate(x, '.1234567890', '.') is null;
More info about Oracle translate function can be found here or in official documentation "SQL Reference"
UPD: If you have signs or spaces in your numbers you can add "+-
" characters to the second parameter of translate
function.
I would like to add more details to Stan's answer #2 for below reasons:
I faced this issue myself more than dozen times and depending on project conditions, I chose between stan's voodoo magic answer #1 or #2. When I kept on facing it again, I become more inquistive that why it happens in first place.
I'd like to add answer for Mac users too.
There are limitations with both these possible answers:
It may happen due to any of the below reasons:
Operating system not allocating system resources to the Excel process. (Solution: One needs to just start the operating system - success rate is very low but has known to work many times)
P-code is the intermediate code that was used in Visual Basic (before .NET) and hence it is still used in the VBA. It enabled a more compact executable at the expense of slower execution. Why I am talking about p-code? Because it gets corrupted sometimes between multiple executions and large files or just due to installation of the software (Excel) went corrupt somewhere. When p-code corrupts. the code execution keeps getting interrupted. Solution: In these cases, it is assumed that your code has started to corrupt and chances in future are that your Excel workbook also get corrupt giving you messages like "excel file corrupted and cannot be opened". Hence, as a quick solution, you can rely on answer #1 or answer #2 as per your requirements. However, never ignore the signs of corruption. It's better to copy your code modules in notepad, delete the modules, save & close the workbook, close the excel. Now, re-open the workbook and start creating new modules with the code copied earlier to notepad.
Mac users, try any of the below option and of them will definitely work depending on your system architecture i.e. OS and Office version
You will be put into break mode using the above key combinations as the macro suspends execution immediately finishing the current task. This is replacement of Step 2.
xlErrorHandler
along with Resume
statement in the Error Handler if the error code is 18. Then, the interrupt is sent to the running procedure as an error, trappable by an error handler set up with an On Error GoTo statement. The trappable error code is 18. The current procedure is interrupted, and the user can debug or end the procedure. Microsoft gives caution that do not use this if your error handler has resume statement else your error handler always returns to the same statement. That's exactly we want in unwanted meaningless interruptions of code execution.This function will return you the date and time in the following format: YYYY:MM:DD:HH:MM:SS
. It also works in Node.js.
function getDateTime() {
var date = new Date();
var hour = date.getHours();
hour = (hour < 10 ? "0" : "") + hour;
var min = date.getMinutes();
min = (min < 10 ? "0" : "") + min;
var sec = date.getSeconds();
sec = (sec < 10 ? "0" : "") + sec;
var year = date.getFullYear();
var month = date.getMonth() + 1;
month = (month < 10 ? "0" : "") + month;
var day = date.getDate();
day = (day < 10 ? "0" : "") + day;
return year + ":" + month + ":" + day + ":" + hour + ":" + min + ":" + sec;
}
Drop the spaces around the =
sign:
#!/bin/bash
STR="Hello World"
echo $STR
You may specify a comparer(IComparer implementation) as a parameter in Array.Sort, the order of sorting actually depends on comparer. The default comparer is used in ascending sorting
If you used the accepted answer, however, you will still receive the PHP Notice if a character in your input string cannot be transliterated:
<?php
$cp1252 = '';
for ($i = 128; $i < 256; $i++) {
$cp1252 .= chr($i);
}
echo iconv("cp1252", "utf-8//TRANSLIT", $cp1252);
PHP Notice: iconv(): Detected an illegal character in input string in CP1252.php on line 8
Notice: iconv(): Detected an illegal character in input string in CP1252.php on line 8
So you should use IGNORE, which will ignore what can't be transliterated:
echo iconv("cp1252", "utf-8//IGNORE", $cp1252);
If you want to color your terminal console, then you can use npm package chalk
npm i chalk
Invoke it from the shell, with an argument like /?
or --help
. Those are the usual help switches.
Just give you some idea how other databases solve this problem. DolphinDB
also has built-in support for pivoting and the sql looks much more intuitive and neat. It is as simple as specifying the key column (Store
), pivoting column (Week
), and the calculated metric (sum(xCount)
).
//prepare a 10-million-row table
n=10000000
t=table(rand(100, n) + 1 as Store, rand(54, n) + 1 as Week, rand(100, n) + 1 as xCount)
//use pivot clause to generate a pivoted table pivot_t
pivot_t = select sum(xCount) from t pivot by Store, Week
DolphinDB is a columnar high performance database. The calculation in the demo costs as low as 546 ms on a dell xps laptop (i7 cpu). To get more details, please refer to online DolphinDB manual https://www.dolphindb.com/help/index.html?pivotby.html
you just setting at php.ini
then set :
upload_max_filesize = 1000M;
post_max_size = 1000M;
then restart your xampp.. Check the image
If you'll go through these steps:
brew install jmeter
and hit Enterjmeter
and hit Enter againYou won't have to solve any kind of issue. Don't thank
You could use string.Join
:
List<string> list = new List<string>()
{
"Red",
"Blue",
"Green"
};
string output = string.Join(Environment.NewLine, list.ToArray());
Console.Write(output);
The result would be:
Red
Blue
Green
As an alternative to Environment.NewLine
, you can replace it with a string based line-separator of your choosing.
I see a number of answers using the Remove method and others using the Delete method.
Remove (according to the docs) will immediately remove the record from the (local) table, and on Update, will not remove a missing record.
Delete in comparison changes the RowState to Deleted, and will update the server table on Update. Likewise, calling the AcceptChanges method before the Update to the server table will reset all your RowState(s) to Unchanged and nothing will flow to the server. (Still nursing my thumb after hitting this a number of times).
First of all I'd like to say that I 100% agree with John Saunders that you must avoid loops in SQL in most cases especially in production.
But occasionally as a one time thing to populate a table with a hundred records for testing purposes IMHO it's just OK to indulge yourself to use a loop.
For example in your case to populate your table with records with hospital ids between 16 and 100 and make emails and descriptions distinct you could've used
CREATE PROCEDURE populateHospitals
AS
DECLARE @hid INT;
SET @hid=16;
WHILE @hid < 100
BEGIN
INSERT hospitals ([Hospital ID], Email, Description)
VALUES(@hid, 'user' + LTRIM(STR(@hid)) + '@mail.com', 'Sample Description' + LTRIM(STR(@hid)));
SET @hid = @hid + 1;
END
And result would be
ID Hospital ID Email Description
---- ----------- ---------------- ---------------------
1 16 [email protected] Sample Description16
2 17 [email protected] Sample Description17
...
84 99 [email protected] Sample Description99
Yes even I got the same error. So I did the following changes
-> Check the error in the Problems tab located near the Console tab
-> See where the error persists, Its possible that some jar file may be corrupted or is outdated so, pom isn't activated in the Project.
-> I found one of my jar was outdated version so I updated it by getting the dependencies from maven repository from this link https://mvnrepository.com
So to conclude, do check where the error persist and which jar file is outdated and make changes accordingly
Try this code
.button:after {
content: ""
position: absolute
width: 70px
background-image: url('../../images/frontapp/mid-icon.svg')
display: inline-block
background-size: contain
background-repeat: no-repeat
right: 0
bottom: 0
}
I have used this one successfully
System.IO.Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName)
It works even inside linqpad.
By using drop_duplicates
pd.concat([df1,df2]).drop_duplicates(keep=False)
Update :
Above method only working for those dataframes they do not have duplicate itself, For example
df1=pd.DataFrame({'A':[1,2,3,3],'B':[2,3,4,4]})
df2=pd.DataFrame({'A':[1],'B':[2]})
It will output like below , which is wrong
Wrong Output :
pd.concat([df1, df2]).drop_duplicates(keep=False)
Out[655]:
A B
1 2 3
Correct Output
Out[656]:
A B
1 2 3
2 3 4
3 3 4
How to achieve that?
Method 1: Using isin
with tuple
df1[~df1.apply(tuple,1).isin(df2.apply(tuple,1))]
Out[657]:
A B
1 2 3
2 3 4
3 3 4
Method 2: merge
with indicator
df1.merge(df2,indicator = True, how='left').loc[lambda x : x['_merge']!='both']
Out[421]:
A B _merge
1 2 3 left_only
2 3 4 left_only
3 3 4 left_only
composer require vendor/package:version
for example:
composer require refinery29/test-util:0.10.2
Do you mean append
?
>>> x = [1,2,3]
>>> y = [4,5,6]
>>> x.append(y)
>>> x
[1, 2, 3, [4, 5, 6]]
Or merge?
>>> x = [1,2,3]
>>> y = [4,5,6]
>>> x + y
[1, 2, 3, 4, 5, 6]
>>> x.extend(y)
>>> x
[1, 2, 3, 4, 5, 6]
This doesn't exactly answer your question, but will get you the same result with less headache.
I always have my click events call methods that contain all the logic I would like to execute. So that I can just call the method directly if I want to perform the action without an actual click.
You have to use the JSON.stringify()
function included with the V8 engine that node uses.
var objToJson = { ... };
response.write(JSON.stringify(objToJson));
Edit: As far as I know, IANA has officially registered a MIME type for JSON as application/json
in RFC4627. It is also is listed in the Internet Media Type list here.
A good way to achieve this is to have a Maven mirror server such as Sonatype Nexus. It is free and very easy to setup (Java web app). With Nexus one can have private (team, corporate etc) repository with a capability of deploying third party and internal apps into it, while also registering other Maven repositories as part of the same server. This way the local Maven settings would reference only the one private Nexus server and all the dependencies will be resolved using it.
A small variation of Sean's answer:
<import resource="classpath*:spring-config.xml" />
With the asterisk in order to spring search files 'spring-config.xml' anywhere in the classpath.
Another reference: Divide Spring configuration across multiple projects
Maybe the following is what you are looking for:
SELECT name, pathfilename
FROM table1
NATURAL JOIN table2
NATURAL JOIN table3
WHERE name = 'John';