Easy task using stringByReplacingOccurrencesOfString
NSString *search = [searchbar.text stringByReplacingOccurrencesOfString:@" " withString:@""];
well i found a solution to this problem for who want to work with xCode 4. All what you have to do is importing frameworks from the SimulatorSDK folder /Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator4.3.sdk/System/Library/Frameworks
i don't know if it works when you try to test your app on a real iDevice, but i'm sure that it works on simulator.
ENJOY
Use the IP instead:
DROP USER 'root'@'127.0.0.1'; GRANT ALL PRIVILEGES ON . TO 'root'@'%';
For more possibilities, see this link.
To create the root user, seeing as MySQL is local & all, execute the following from the command line (Start > Run > "cmd" without quotes):
mysqladmin -u root password 'mynewpassword'
I have personally found pywinrm
library to be very effective. However, it does require some commands to be run on the machine and some other setup before it will work.
Another option is where you have tables like 'type' or 'status', for example, OrderStatus, where you always want to control the Id value, create the Id (Primary Key) column without it being an Identity column is the first place.
Like so:
def find_and_replace(file, word, replacement):
with open(file, 'r+') as f:
text = f.read()
f.write(text.replace(word, replacement))
I prefer this all the time and found it much easier.
echo "Welcome {$name}!"
As Fragments Version 1.3.0-alpha01
The setRetainInstance() method on Fragments has been deprecated. With the introduction of ViewModels, developers have a specific API for retaining state that can be associated with Activities, Fragments, and Navigation graphs. This allows developers to use a normal, not retained Fragment and keep the specific state they want retained separate, avoiding a common source of leaks while maintaining the useful properties of a single creation and destruction of the retained state (namely, the constructor of the ViewModel and the onCleared() callback it receives).
Might be better choice:
@Override
public String toString() {
return new GsonBuilder().create().toJson(this, Producto.class);
}
To run a batch file at start up: start >> all programs >> right-click startup >> open >> right click batch file >> create shortcut >> drag shortcut to startup folder.
The path to the folder is : [D|C]:\Profiles\{User}\??AppData\Roaming\Micro??soft\Windows\Start Menu\Programs\Startu??p
Another excellent plugin: http://documentcloud.github.com/visualsearch/
If case anyone is looking for a regex that allows only numbers with an optional 2 decimal places
^\d*(\.\d{0,2})?$
For an example, I have found solution below to be fairly reliable
HTML:
<input name="my_field" pattern="^\d*(\.\d{0,2})?$" />
JS / JQuery:
$(document).on('keydown', 'input[pattern]', function(e){
var input = $(this);
var oldVal = input.val();
var regex = new RegExp(input.attr('pattern'), 'g');
setTimeout(function(){
var newVal = input.val();
if(!regex.test(newVal)){
input.val(oldVal);
}
}, 0);
});
Update
setTimeout is not working correctly anymore for this, maybe browsers have changed. Some other async solution will need to be devised.
You can hit the key q (for quit) and it should take you to the prompt.
Please see this link.
I recommend trying Kestrel, it's fast and simple as Beanstalk but supports fanout queues. Speaks memcached. It's built using Scala and used at Twitter.
BSD's
for i in $(seq 1 254); do (ping -c1 -W5 192.168.1.$i >/dev/null && echo "192.168.1.$i" &) ;done
Single statement that works with trailing slash. If you are using IE11 you'll have to polyfill the filter
function.
var name = window.location.pathname
.split("/")
.filter(function (c) { return c.length;})
.pop();
I was also scratching my head around the same issue, and everything worked after I set the role to be root when adding the first admin user.
use admin
db.createUser(
{
user: 'admin',
pwd: 'password',
roles: [ { role: 'root', db: 'admin' } ]
}
);
exit;
If you have already created the admin
user, you can change the role like this:
use admin;
db.grantRolesToUser('admin', [{ role: 'root', db: 'admin' }])
For a complete authentication setting reference, see the steps I've compiled after hours of research over the internet.
one line answer
var height = parseInt(ctx.font) * 1.2;
CSS "line-height: normal" is between 1 and 1.2
read here for more info
This is due to the way Windows App Execution Aliases work in Git-Bash.
It is a known issue in MSYS2 failing to access Windows reparse points with IO_REPARSE_TAG_APPEXECLINK
As a workaround, you can alias to a function invocation that uses cmd.exe
under the hood.
Add the following to your ~/.bashrc
file::
function python { cmd.exe /c "python $1 $2 $3";}
For python, I'd recommend just toggling off app execution aliases as in the accepted answer, but for libraries that are distributed exclusively through the windows store like winget
, this is your best option.
Like this
css
body {
background-color : #484848;
margin: 0;
padding: 0;
}
h1 {
color : #000000;
text-align : center;
font-family: "SIMPSON";
}
form {
width: 300px;
margin: 0 auto;
}
One major difference that is important to know is that ActiveX controls show up as objects that you can use in your code- try inserting an ActiveX control into a worksheet, bring up the VBA editor (ALT + F11) and you will be able to access the control programatically. You can't do this with form controls (macros must instead be explicitly assigned to each control), but form controls are a little easier to use. If you are just doing something simple, it doesn't matter which you use but for more advanced scripts ActiveX has better possibilities.
ActiveX is also more customizable.
[STAThread]
static void Main() // args are OK here, of course
{
bool ok;
m = new System.Threading.Mutex(true, "YourNameHere", out ok);
if (! ok)
{
MessageBox.Show("Another instance is already running.");
return;
}
Application.Run(new Form1()); // or whatever was there
GC.KeepAlive(m); // important!
}
From: Ensuring a single instance of .NET Application
and: Single Instance Application Mutex
Same answer as @Smink and @Imjustpondering with a twist:
Jon Skeet's FAQ on C# to find out why GC.KeepAlive matters
You can use stored procedure in this way..
DELIMITER |
CREATE PROCEDURE explode( pDelim VARCHAR(32), pStr TEXT)
BEGIN
DROP TABLE IF EXISTS temp_explode;
CREATE TEMPORARY TABLE temp_explode (id INT AUTO_INCREMENT PRIMARY KEY NOT NULL, word VARCHAR(40));
SET @sql := CONCAT('INSERT INTO temp_explode (word) VALUES (', REPLACE(QUOTE(pStr), pDelim, '\'), (\''), ')');
PREPARE myStmt FROM @sql;
EXECUTE myStmt;
END |
DELIMITER ;
example call:
SET @str = "The quick brown fox jumped over the lazy dog";
SET @delim = " ";
CALL explode(@delim,@str);
SELECT id,word FROM temp_explode;
You're passing in a pointer *random
but you're using it like a reference &random
The pointer (what you have) says "This is the address in memory that contains the address of random"
The reference says "This is the address of random"
That's right. You could try it in the interpreter like this:
>>> a_set = set(['a', 'b', 'c'])
>>> 'a' in a_set
True
>>>'d' in a_set
False
You can create an async init() {... return this;}
method, then instead do new MyClass().init()
whenever you'd normally just say new MyClass()
.
This is not clean because it relies on everyone who uses your code, and yourself, to always instantiate the object like so. However if you're only using this object in a particular place or two in your code, it could maybe be fine.
A significant problem though occurs because ES has no type system, so if you forget to call it, you've just returned undefined
because the constructor returns nothing. Oops. Much better would be to do something like:
The best thing to do would be:
class AsyncOnlyObject {
constructor() {
}
async init() {
this.someField = await this.calculateStuff();
}
async calculateStuff() {
return 5;
}
}
async function newAsync_AsyncOnlyObject() {
return await new AsyncOnlyObject().init();
}
newAsync_AsyncOnlyObject().then(console.log);
// output: AsyncOnlyObject {someField: 5}
However then you might accidentally do new AsyncOnlyObject, you should probably just create factory function that uses Object.create(AsyncOnlyObject.prototype)
directly:
async function newAsync_AsyncOnlyObject() {
return await Object.create(AsyncOnlyObject.prototype).init();
}
newAsync_AsyncOnlyObject().then(console.log);
// output: AsyncOnlyObject {someField: 5}
However say you want to use this pattern on many objects... you could abstract this as a decorator or something you (verbosely, ugh) call after defining like postProcess_makeAsyncInit(AsyncOnlyObject)
, but here I'm going to use extends
because it sort of fits into subclass semantics (subclasses are parent class + extra, in that they should obey the design contract of the parent class, and may do additional things; an async subclass would be strange if the parent wasn't also async, because it could not be initialized the same way):
class AsyncObject {
constructor() {
throw new Error('classes descended from AsyncObject must be initialized as (await) TheClassName.anew(), rather than new TheClassName()');
}
static async anew(...args) {
var R = Object.create(this.prototype);
R.init(...args);
return R;
}
}
class MyObject extends AsyncObject {
async init(x, y=5) {
this.x = x;
this.y = y;
// bonus: we need not return 'this'
}
}
MyObject.anew('x').then(console.log);
// output: MyObject {x: "x", y: 5}
(do not use in production: I have not thought through complicated scenarios such as whether this is the proper way to write a wrapper for keyword arguments.)
Most of the time, when you try to assing value into object, and if the value is null, then this kind of exception occur. Please check this link.
for the sake of self learning, you can put some check condition. like
if (myObj== null)
Console.Write("myObj is NULL");
Here is how to do dump the database (with just the schema):
mysqldump -u root -p"passwd" --no-data --add-drop-database --databases my_db_name | sed 's#/[*]!40000 DROP DATABASE IF EXISTS my_db_name;#' >my_db_name.sql
If you also want the data, remove the --no-data
option.
Also, it is very likely, that problem with proxy settings.
Any who didn't overcome Tomact starting problrem, - try in NetBeans choose No Proxy in the Tools -> Options -> General tab.
It helped me.
On Raspberry Pi I had to create from ARM driver and set the geckodriver and log path in:
sudo nano /usr/local/lib/python2.7/dist-packages/selenium/webdriver/firefox/webdriver.py
def __init__(self, firefox_profile=None, firefox_binary=None,
timeout=30, capabilities=None, proxy=None,
executable_path="/PATH/gecko/geckodriver",
firefox_options=None,
log_path="/PATH/geckodriver.log"):
if (array.length>0) // edited in response Joachim's comment
sb.append(array[i]);
for (int i=1; i<array.length; i++)
sb.append(",").append(array[i]);
Based on Clearest way to comma-delimit a list (Java)?
Using this idea: Does the last element in a loop deserve a separate treatment?
If you need to remove just trailing whitespace, you could use str.rstrip()
, which should be slightly more efficient than str.strip()
:
>>> lst = ['this\n', 'is\n', 'a\n', 'list\n', 'of\n', 'words\n']
>>> [x.rstrip() for x in lst]
['this', 'is', 'a', 'list', 'of', 'words']
>>> list(map(str.rstrip, lst))
['this', 'is', 'a', 'list', 'of', 'words']
global
members are not available by default in your <template>
's scope. But you can easily pass them on using computed
properties.
computed: {
moment: () => moment,
console: () => console,
window: () => window
}
Now you can use any of them in your template. i.e: console.log(moment(), window)
.
Note this doesn't add any overhead.
OK some answers about malloc were already posted.
The more interesting part is how free works (and in this direction, malloc too can be understood better).
In many malloc/free implementations, free does normally not return the memory to the operating system (or at least only in rare cases). The reason is that you will get gaps in your heap and thus it can happen, that you just finish off your 2 or 4 GB of virtual memory with gaps. This should be avoided, since as soon as the virtual memory is finished, you will be in really big trouble. The other reason is, that the OS can only handle memory chunks that are of a specific size and alignment. To be specific: Normally the OS can only handle blocks that the virtual memory manager can handle (most often multiples of 512 bytes e.g. 4KB).
So returning 40 Bytes to the OS will just not work. So what does free do?
Free will put the memory block in its own free block list. Normally it also tries to meld together adjacent blocks in the address space. The free block list is just a circular list of memory chunks which have some administrative data in the beginning. This is also the reason why managing very small memory elements with the standard malloc/free is not efficient. Every memory chunk needs additional data and with smaller sizes more fragmentation happens.
The free-list is also the first place that malloc looks at when a new chunk of memory is needed. It is scanned before it calls for new memory from the OS. When a chunk is found that is bigger than the needed memory, it is divided into two parts. One is returned to caller, the other is put back into the free list.
There are many different optimizations to this standard behaviour (for example for small chunks of memory). But since malloc and free must be so universal, the standard behaviour is always the fallback when alternatives are not usable. There are also optimizations in handling the free-list — for example storing the chunks in lists sorted by sizes. But all optimizations also have their own limitations.
Why does your code crash:
The reason is that by writing 9 chars (don't forget the trailing null byte) into an area sized for 4 chars, you will probably overwrite the administrative-data stored for another chunk of memory that resides "behind" your chunk of data (since this data is most often stored "in front" of the memory chunks). When free then tries to put your chunk into the free list, it can touch this administrative-data and therefore stumble over an overwritten pointer. This will crash the system.
This is a rather graceful behaviour. I have also seen situations where a runaway pointer somewhere has overwritten data in the memory-free-list and the system did not immediately crash but some subroutines later. Even in a system of medium complexity such problems can be really, really hard to debug! In the one case I was involved, it took us (a larger group of developers) several days to find the reason of the crash -- since it was in a totally different location than the one indicated by the memory dump. It is like a time-bomb. You know, your next "free" or "malloc" will crash, but you don't know why!
Those are some of the worst C/C++ problems, and one reason why pointers can be so problematic.
You can use some div or span instead of button and then on click call some function which submits form at he end.
<form id="my_form">
<span onclick="submit()">submit</span>
</form>
<script>
function submit()
{
//do something
$("#my_form").submit();
}
</script>
I received the same error after installing android studio and trying to run hello world. I think you need to use the SDK Manager inside Android Studio to install some things first.
Open up Android Studio, and click on the SDK Manager in the toolbar.
Now install the SDK tools you need.
For each Android release you are targeting, hit the appropriate Android X.X folder and select (at a minimum):
The SDK Manager will run (this can take a while) and download and install the various SDKs.
Inside Android Studio, File->Project Structure will show you where your Android sdks are installed. As you can see mine is c:\users\Joe\AppData\Local\Android\sdk1.
If I navigate to C:\Users\Joe\AppData\Local\Android\sdk1\sources you can see the various Android SDKs installed there...
I use this to convert char to string (an example) :
char c = 'A';
char str1[2] = {c , '\0'};
char str2[5] = "";
strcpy(str2,str1);
Tell PDO your charset
initially.... something like
PDO("mysql:host=$host;dbname=$DB_name;charset=utf8;", $username, $password);
Notice the: charset=utf8;
part.
hope it helps!
I've added yet another JavaScript serializer repo to GitHub.
Rather than take the approach of serializing and deserializing JavaScript objects to an internal format the approach here is to serialize JavaScript objects out to native JavaScript. This has the advantage that the format is totally agnostic from the serializer, and the object can be recreated simply by calling eval().
If you have Xcode 4 Build Location setting set to "Place build products in derived data location (recommended), it should be located in ~/Library/Developer/Xcode/DerivedData. This directory will have your project in there as a directory, the project name will be appended with a bunch of generated letters so look carefully.
I haven't seen any decompilers that generate C++ code. I've seen a few experimental ones that make a reasonable attempt at generating C code, but they tended to be dependent on matching the code-generation patterns of a particular compiler (that may have changed, it's been awhile since I last looked into this). Of course any symbolic information will be gone. Google for "decompiler".
This Problem is because of Path so you need to build the path using following Steps
Goto project ----->Right Click on Project Name ---->properties ---->click on Than Java Build Path option than ---> click Android 4.2.2---->Ok
open both of the files then compare them by splitting its word contents;
log_file_A='file_A.txt'
log_file_B='file_B.txt'
read_A=open(log_file_A,'r')
read_A=read_A.read()
print read_A
read_B=open(log_file_B,'r')
read_B=read_B.read()
print read_B
File_A_set = set(read_A.split(' '))
File_A_set = set(read_B.split(' '))
print File_A_set == File_B_set
This might help
import binascii
x = b'test'
x = binascii.hexlify(x)
y = str(x,'ascii')
print(x) # Outputs b'74657374' (hex encoding of "test")
print(y) # Outputs 74657374
x_unhexed = binascii.unhexlify(x)
print(x_unhexed) # Outputs b'test'
x_ascii = str(x_unhexed,'ascii')
print(x_ascii) # Outputs test
This code contains examples for converting ASCII characters to and from hexadecimal. In your situation, the line you'd want to use is str(binascii.hexlify(c),'ascii')
.
In Python:
>>> a[0] = "hello"
NameError: name 'a' is not defined
>>> a[0:] = "hello"
NameError: name 'a' is not defined
>>> a = []
>>> a[0] = "hello"
IndexError: list assignment index out of range
>>> a[0:] = "hello"
>>> a
['h', 'e', 'l', 'l', 'o']
These slice assignments also give the same results:
a[:] = "hello"
a[42:] = "hello"
a[:33] = "hello"
If you don't want to assign identifier to the hidden field; you can use name or class with selector like:
$('input[name=hiddenfieldname]').val();
or with assigned class:
$('input.hiddenfieldclass').val();
You just need to install Android development kit from http://developer.android.com/sdk/installing/studio.html#Updating
and also Download and install Java JDK (Choose the Java platform)
define the environment variable in windows System setting https://confluence.atlassian.com/display/DOC/Setting+the+JAVA_HOME+Variable+in+Windows
Voila ! You are Donezo !
First, JavaScript's switch
is no faster than if/else
(and sometimes much slower).
Second, the only way to use switch
with multiple variables is to combine them into one primitive (string, number, etc) value:
var stateA = "foo";
var stateB = "bar";
switch (stateA + "-" + stateB) {
case "foo-bar": ...
...
}
But, personally, I would rather see a set of if
/else
statements.
Edit: When all the values are integers, it appears that switch can out-perform if/else in Chrome. See the comments.
Shefali's solution for UIImageView works great, but it needs a little modification:
- (void)pinch:(UIPinchGestureRecognizer *)gesture {
if (gesture.state == UIGestureRecognizerStateEnded
|| gesture.state == UIGestureRecognizerStateChanged) {
NSLog(@"gesture.scale = %f", gesture.scale);
CGFloat currentScale = self.frame.size.width / self.bounds.size.width;
CGFloat newScale = currentScale * gesture.scale;
if (newScale < MINIMUM_SCALE) {
newScale = MINIMUM_SCALE;
}
if (newScale > MAXIMUM_SCALE) {
newScale = MAXIMUM_SCALE;
}
CGAffineTransform transform = CGAffineTransformMakeScale(newScale, newScale);
self.transform = transform;
gesture.scale = 1;
}
}
(Shefali's solution had the downside that it did not scale continuously while pinching. Furthermore, when starting a new pinch, the current image scale was reset.)
white-space: pre-wrap
is what worked for me for <span>
and <div>
.
I'm using json lib from http://json-lib.sourceforge.net/
json-lib-2.1-jdk15.jar
import net.sf.json.JSONObject;
...
public void send()
{
//put attributes
Map m = New HashMap();
m.put("send_to","[email protected]");
m.put("email_subject","this is a test email");
m.put("email_content","test email content");
//generate JSON Object
JSONObject json = JSONObject.fromObject(content);
String message = json.toString();
...
}
public void receive(String jsonMessage)
{
//parse attributes
JSONObject json = JSONObject.fromObject(jsonMessage);
String to = (String) json.get("send_to");
String title = (String) json.get("email_subject");
String content = (String) json.get("email_content");
...
}
More samples here http://json-lib.sourceforge.net/usage.html
according to this book:
MySQL lets you specify a “width” for integer types, such as INT(11). This is meaningless for most applications: it does not restrict the legal range of values, but simply specifies the number of characters MySQL’s interactive tools will reserve for display purposes. For storage and computational purposes, INT(1) is identical to INT(20).
We can use CSS to hide the first option , But it wont work in IE 10, 11. The best way is to remove the element using Jquery. This solution works for major browser tested in chrome and IE10 ,11
Also if you are using angular , sometime using setTimeout works
$scope.RemoveFirstOptionElement = function (element) {
setTimeout(function () {
$(element.children()[0]).remove();
}, 0);
};
I think you could experiment with different activity flags, as it sounds like multiple instances.
"singleTop" "singleTask" "singleInstance"
Are the ones I would try, they can be defined inside the manifest.
http://developer.android.com/guide/topics/manifest/activity-element.html
This should work (adapted from https://stackoverflow.com/a/8285722/388902).
var ctrl_down = false;
var ctrl_key = 17;
var s_key = 83;
$(document).keydown(function(e) {
if (e.keyCode == ctrl_key) ctrl_down = true;
}).keyup(function(e) {
if (e.keyCode == ctrl_key) ctrl_down = false;
});
$(document).keydown(function(e) {
if (ctrl_down && (e.keyCode == s_key)) {
alert('Ctrl-s pressed');
// Your code
return false;
}
});
You can pass params directly to $http.get()
The following works fine
$http.get(user.details_path, {
params: { user_id: user.id }
});
JSONObject responseDetailsJson = new JSONObject();
JSONArray jsonArray = new JSONArray();
List<String> ls =new ArrayList<String>();
for(product cj:cities.getList()) {
ls.add(cj);
JSONObject formDetailsJson = new JSONObject();
formDetailsJson.put("id", cj.id);
formDetailsJson.put("name", cj.name);
jsonArray.put(formDetailsJson);
}
responseDetailsJson.put("Cities", jsonArray);
return responseDetailsJson;
put the folder which has the properties file for log in java build path source. You can add it by right clicking the project ----> build path -----> configure build path ------> add t
You could just add a space before and after "word".
x = raw_input("Type your word: ")
if " word " in x:
print "Yes"
elif " word " not in x:
print "Nope"
This way it looks for the space before and after "word".
>>> Type your word: Swordsmith
>>> Nope
>>> Type your word: word
>>> Yes
$('controlCheckBox').click(function(){
var temp = $(this).prop('checked');
$('controlledCheckBoxes').prop('checked', temp);
});
I would suggest using the duplicated method on the Pandas Index itself:
df3 = df3[~df3.index.duplicated(keep='first')]
While all the other methods work, the currently accepted answer is by far the least performant for the provided example. Furthermore, while the groupby method is only slightly less performant, I find the duplicated method to be more readable.
Using the sample data provided:
>>> %timeit df3.reset_index().drop_duplicates(subset='index', keep='first').set_index('index')
1000 loops, best of 3: 1.54 ms per loop
>>> %timeit df3.groupby(df3.index).first()
1000 loops, best of 3: 580 µs per loop
>>> %timeit df3[~df3.index.duplicated(keep='first')]
1000 loops, best of 3: 307 µs per loop
Note that you can keep the last element by changing the keep argument to 'last'
.
It should also be noted that this method works with MultiIndex
as well (using df1 as specified in Paul's example):
>>> %timeit df1.groupby(level=df1.index.names).last()
1000 loops, best of 3: 771 µs per loop
>>> %timeit df1[~df1.index.duplicated(keep='last')]
1000 loops, best of 3: 365 µs per loop
The error means you cannot use the local variable mi
inside an inner class.
To use a variable inside an inner class you must declare it final
. As long as mi
is the counter of the loop and final
variables cannot be assigned, you must create a workaround to get mi
value in a final
variable that can be accessed inside inner class:
final Integer innerMi = new Integer(mi);
So your code will be like this:
for (int mi=0; mi<colors.length; mi++){
String pos = Character.toUpperCase(colors[mi].charAt(0)) + colors[mi].substring(1);
JMenuItem Jmi =new JMenuItem(pos);
Jmi.setIcon(new IconA(colors[mi]));
// workaround:
final Integer innerMi = new Integer(mi);
Jmi.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JMenuItem item = (JMenuItem) e.getSource();
IconA icon = (IconA) item.getIcon();
// HERE YOU USE THE FINAL innerMi variable and no errors!!!
Color kolorIkony = getColour(colors[innerMi]);
textArea.setForeground(kolorIkony);
}
});
mnForeground.add(Jmi);
}
}
In my case the following was necessary:
sudo chgrp vboxsf /media/sf_sharedFolder
Mine DID execute commands in order. Here's my version of what I was using it for:
START cmd.exe /k "U: & cd U:\Design_stuff\new_lcso_website_2017 & python -m http.server"
I needed to
If those commands are out of order, it would not display the correct files. I initially forgot to change to U:
and, running the batch file on my Desktop, it created a web page in my browser at http://localhost:8000 showing me the contents of my Desktop instead of the folder I wanted.
According to Gil great answer I solved by Overriding the getItemViewType as explained by Gil. His answer is great and have to be marked as correct. In any case, I add the code to reach the score:
In your recycler adapter:
@Override
public int getItemViewType(int position) {
int viewType = 0;
// add here your booleans or switch() to set viewType at your needed
// I.E if (position == 0) viewType = 1; etc. etc.
return viewType;
}
@Override
public FileViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if (viewType == 0) {
return new MyViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.my_layout_for_first_row, parent, false));
}
return new MyViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.my_other_rows, parent, false));
}
By doing this, you can set whatever custom layout for whatever row!
DatabaseMetaData dbm = con.getMetaData();
// check if "employee" table is there
ResultSet tables = dbm.getTables(null, null, "employee", null);
if (tables.next()) {
// Table exists
}
else {
// Table does not exist
}
ArrayList<ArrayList<String>> listOLists = new ArrayList<ArrayList<String>>();
ArrayList<String> singleList = new ArrayList<String>();
singleList.add("hello");
singleList.add("world");
listOLists.add(singleList);
ArrayList<String> anotherList = new ArrayList<String>();
anotherList.add("this is another list");
listOLists.add(anotherList);
There is no other way - except implementing lazy loading.
Or manual loading....
myobj = context.MyObjects.First();
myobj.ChildA.Load();
myobj.ChildB.Load();
...
This is the normal behavior and the reason is that your sqlCommandHandlerService.persist
method needs a TX when being executed (because it is marked with @Transactional
annotation). But when it is called inside processNextRegistrationMessage
, because there is a TX available, the container doesn't create a new one and uses existing TX. So if any exception occurs in sqlCommandHandlerService.persist
method, it causes TX to be set to rollBackOnly
(even if you catch the exception in the caller and ignore it).
To overcome this you can use propagation levels for transactions. Have a look at this to find out which propagation best suits your requirements.
Well after a colleague came to me with a couple of questions about a similar situation, I feel this needs a bit of clarification.
Although propagations solve such issues, you should be VERY careful about using them and do not use them unless you ABSOLUTELY understand what they mean and how they work. You may end up persisting some data and rolling back some others where you don't expect them to work that way and things can go horribly wrong.
Note that the search query is now case sensitive.
When using
SELECT * FROM table WHERE `first_name` LIKE '%$search_term%'
It will match both "Larry" and "larry". With this concat_ws, it will suddenly become case sensitive!
This can be fixed by using the following query:
SELECT * FROM table WHERE UPPER(CONCAT_WS(' ', `first_name`, `last_name`) LIKE UPPER('%$search_term%')
Edit: Note that this only works on non-binary elements. See also mynameispaulie's answer.
It's HTML character references for encoding a character by its decimal code point
Look at the ASCII table here and you'll see that 39 (hex 0x27, octal 47) is the code for apostrophe
Swift 3:
Try this:
extension String {
func htmlAttributedString() -> NSAttributedString? {
guard let data = self.data(using: String.Encoding.utf16, allowLossyConversion: false) else { return nil }
guard let html = try? NSMutableAttributedString(
data: data,
options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
documentAttributes: nil) else { return nil }
return html
}
}
And for using:
let str = "<h1>Hello bro</h1><h2>Come On</h2><h3>Go sis</h3><ul><li>ME 1</li><li>ME 2</li></ul> <p>It is me bro , remember please</p>"
self.contentLabel.attributedText = str.htmlAttributedString()
Jenkins does not show coverage results as it is a problem of version compatibilities between jenkins jacoco plugin and maven jacoco plugin. On my side I have fixed it by using a more recent version of maven jacoco plugin
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>0.7.9</version>
</plugin>
<plugins>
<pluginManagement>
<build>
Just make option#1 Select Language:
Please try this,
public void removeNotification(Context context, int notificationId) {
NotificationManager nMgr = (NotificationManager) context.getApplicationContext()
.getSystemService(Context.NOTIFICATION_SERVICE);
nMgr.cancel(notificationId);
}
A more simple English explanation: jQuery is something that makes AJAX and other JavaScript tasks much easier.
You are adding the formControlName
to the label and not the input.
You have this:
<div >
<div class="input-field col s12">
<input id="email" type="email">
<label class="center-align" for="email" formControlName="email">Email</label>
</div>
</div>
Try using this:
<div >
<div class="input-field col s12">
<input id="email" type="email" formControlName="email">
<label class="center-align" for="email">Email</label>
</div>
</div>
Update the other input fields as well.
I just had to do this myself, so I thought I would post another answer here.
Here is another way to create a rounded corner border and clip its inner content. This is the straightforward way by using the Clip property. It's nice if you want to avoid a VisualBrush.
The xaml:
<Border
Width="200"
Height="25"
CornerRadius="11"
Background="#FF919194"
>
<Border.Clip>
<RectangleGeometry
RadiusX="{Binding CornerRadius.TopLeft, RelativeSource={RelativeSource AncestorType={x:Type Border}}}"
RadiusY="{Binding RadiusX, RelativeSource={RelativeSource Self}}"
>
<RectangleGeometry.Rect>
<MultiBinding
Converter="{StaticResource widthAndHeightToRectConverter}"
>
<Binding
Path="ActualWidth"
RelativeSource="{RelativeSource AncestorType={x:Type Border}}"
/>
<Binding
Path="ActualHeight"
RelativeSource="{RelativeSource AncestorType={x:Type Border}}"
/>
</MultiBinding>
</RectangleGeometry.Rect>
</RectangleGeometry>
</Border.Clip>
<Rectangle
Width="100"
Height="100"
Fill="Blue"
HorizontalAlignment="Left"
VerticalAlignment="Center"
/>
</Border>
The code for the converter:
public class WidthAndHeightToRectConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
double width = (double)values[0];
double height = (double)values[1];
return new Rect(0, 0, width, height);
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
I assume 0
means false
(which is the case in a lot of programming languages). That means true
is not 0
(some languages use -1
some others use 1
; doesn't hurt to be compatible to either). So assuming by "better" you mean less typing, you can just write:
bool boolValue = intValue != 0;
Already tested by me, it works fine
For i =0 To ListBox2.items.count - 1
ListBox2.Items.removeAt(0)
Next
For comprehensive SFTP support in .NET try edtFTPnet/PRO. It's been around a long time with support for many different SFTP servers.
We also sell an SFTP server for Windows, CompleteFTP, which is an inexpensive way to get support for SFTP on your Windows machine. Also has FTP and FTPS.
The problem with your code is :
String show[]= {rs4.getString(1)};
String actuate[]={rs4.getString(2)};
This will create a new array every time your loop (an not append as you might be assuming) and hence in the end you will have only one element per array.
Here is one more way to solve this :
StringBuilder sids = new StringBuilder ();
StringBuilder lids = new StringBuilder ();
while (rs4.next()) {
sids.append(rs4.getString(1)).append(" ");
lids.append(rs4.getString(2)).append(" ");
}
String show[] = sids.toString().split(" ");
String actuate[] = lids.toString().split(" ");
These arrays will have all the required element.
It depends on what you're trying to achieve after changing the Java file. Until you want to test the maven process, you never need to do anything. Eclipse/MyEclipse will build what is necessary and put the output in the appropriate place within your project. You can also run or deploy it (if it's a web project, for example), without your needing to explicitly do anything with maven. In the end, to install your project in the maven repository, you will need to do a maven install. You may also have other maven goals that you wish to execute, which MyEclipse won't do automatically.
As I say, it depends on what you want to do.
To move a table from database A to database B at your local setup, use the following command:
pg_dump -h localhost -U owner-name -p 5432 -C -t table-name database1 | psql -U owner-name -h localhost -p 5432 database2
With jQuery you can use:
$.isEmptyObject(obj); // Returns: Boolean
As of jQuery 1.4 this method checks both properties on the object itself and properties inherited from prototypes (in that it doesn't use hasOwnProperty).
With ECMAScript 5th Edition in modern browsers (IE9+, FF4+, Chrome5+, Opera12+, Safari5+) you can use the built in Object.keys method:
var obj = { blah: 1 };
var isEmpty = !Object.keys(obj).length;
Or plain old JavaScript:
var isEmpty = function(obj) {
for(var p in obj){
return false;
}
return true;
};
Another solution:
inside the loop, use List instead of string.
List<string> lst= new List<string>();
for(int i=0; i<100000; i++){
...........
lst.Add(...);
}
return String.Join("", lst.ToArray());;
it is very very fast.
There are a few problems here.
1: onBlur expects a callback, and you are calling renderPasswordConfirmError
and using the return value, which is null.
2: you need a place to render the error.
3: you need a flag to track "and I validating", which you would set to true on blur. You can set this to false on focus if you want, depending on your desired behavior.
handleBlur: function () {
this.setState({validating: true});
},
render: function () {
return <div>
...
<input
type="password"
placeholder="Password (confirm)"
valueLink={this.linkState('password2')}
onBlur={this.handleBlur}
/>
...
{this.renderPasswordConfirmError()}
</div>
},
renderPasswordConfirmError: function() {
if (this.state.validating && this.state.password !== this.state.password2) {
return (
<div>
<label className="error">Please enter the same password again.</label>
</div>
);
}
return null;
},
you can use LINQ
string abc = "abc";
char getresult = abc.Where((item, index) => index == 2).Single();
This feature is built into jqGrid.
setup your grid function as follows.
$('#myGrid').jqGrid({
...
colNames: ['Manager', 'Name', 'HiddenSalary'],
colModel: [
{ name: 'Manager', editable: true },
{ name: 'Price', editable: true },
{ name: 'HiddenSalary', hidden: true , editable: true,
editrules: {edithidden:true}
}
],
...
};
There are other editrules that can be applied but this basic setup would hide the manager's salary in the grid view but would allow editing when the edit form was displayed.
HashSet is unordered and unsorted Set.
LinkedHashSet is the ordered version of HashSet.
The only difference between HashSet and LinkedHashSet is that:
LinkedHashSet maintains the insertion order.
When we iterate through a HashSet, the order is unpredictable while it is predictable in case of LinkedHashSet.
The reason for how LinkedHashSet maintains insertion order is that:
The underlying used data structure is Doubly-Linked-List.
echo "12|23|11" | awk '{split($0,a,"|"); print a[3] a[2] a[1]}'
should work.
Sure, you can use equals
if you want to go along with the crowd, but if you really want to amaze your fellow programmers check for inequality like this:
if ("success" != statusCheck.intern())
intern method is part of standard Java String API.
Access Token
for Mobile Number and Country Code
(Server Side OR Client Side)You can get the mobile number
with your access_token
with this API
https://graph.accountkit.com/v1.1/me/?access_token=xxxxxxxxxxxx. Maybe, once you have the mobile number
and the id
, you can work with it to verify the user with your server & database
.
xxxxxxxxxx
above is the Access Token
{
"id": "61940819992708",
"phone": {
"number": "+91XX82923912",
"country_prefix": "91",
"national_number": "XX82923912"
}
}
Auth Code
for Access Token
(Server Side)If you have an Auth Code
instead, you can first get the Access Token
with this API
- https://graph.accountkit.com/v1.1/access_token?grant_type=authorization_code&code=xxxxxxxxxx&access_token=AA|yyyyyyyyyy|zzzzzzzzzz
xxxxxxxxxx
, yyyyyyyyyy
and zzzzzzzzzz
above are the Auth Code
, App ID
and App Secret
respectively.
{
"id": "619XX819992708",
"access_token": "EMAWdcsi711meGS2qQpNk4XBTwUBIDtqYAKoZBbBZAEZCZAXyWVbqvKUyKgDZBniZBFwKVyoVGHXnquCcikBqc9ROF2qAxLRrqBYAvXknwND3dhHU0iLZCRwBNHNlyQZD",
"token_refresh_interval_sec": XX92000
}
server-side
since the API
requires the APP Secret
which is not meant to be shared
for security reasons
.Good Luck.
See TRY...CATCH (Transact-SQL)
CREATE PROCEDURE [dbo].[PL_GEN_PROVN_NO1]
@GAD_COMP_CODE VARCHAR(2) =NULL,
@@voucher_no numeric =null output
AS
BEGIN
begin try
-- your proc code
end try
begin catch
-- what you want to do in catch
end catch
END -- proc end
Thanks Sanoj, that worked for me.
However iOS does not support "onbeforeunload" on iPhone. Workaround for me was to set localStorage with js:
<button onclick="myFunction()">Click me</button>
<script>
document.addEventListener("DOMContentLoaded", function(event) {
var scrollpos = localStorage.getItem('scrollpos');
if (scrollpos) window.scrollTo(0, scrollpos);
});
function myFunction() {
localStorage.setItem('scrollpos', window.scrollY);
location.reload();
}
</script>
For docker run
:
Simply add the option --user <user>
to change to another user when you start the docker container.
docker run -it --user nobody busybox
For docker attach
or docker exec
:
Since the command is used to attach/execute into the existing process, therefore it uses the current user there directly.
docker run -it busybox # CTRL-P/Q to quit
docker attach <container id> # then you have root user
/ # id
uid=0(root) gid=0(root) groups=10(wheel)
docker run -it --user nobody busybox # CTRL-P/Q to quit
docker attach <container id>
/ $ id
uid=99(nobody) gid=99(nogroup)
If you really want to attach to the user you want to have, then
run --user <user>
or mention it in your Dockerfile
using USER
Calendar start = Calendar.getInstance();
Calendar end = Calendar.getInstance();
start.set(2010, 7, 23);
end.set(2010, 8, 26);
Date startDate = start.getTime();
Date endDate = end.getTime();
long startTime = startDate.getTime();
long endTime = endDate.getTime();
long diffTime = endTime - startTime;
long diffDays = diffTime / (1000 * 60 * 60 * 24);
DateFormat dateFormat = DateFormat.getDateInstance();
System.out.println("The difference between "+
dateFormat.format(startDate)+" and "+
dateFormat.format(endDate)+" is "+
diffDays+" days.");
This will not work when crossing daylight savings time (or leap seconds) as orange80 pointed out and might as well not give the expected results when using different times of day. Using JodaTime might be easier for correct results, as the only correct way with plain Java before 8 I know is to use Calendar's add and before/after methods to check and adjust the calculation:
start.add(Calendar.DAY_OF_MONTH, (int)diffDays);
while (start.before(end)) {
start.add(Calendar.DAY_OF_MONTH, 1);
diffDays++;
}
while (start.after(end)) {
start.add(Calendar.DAY_OF_MONTH, -1);
diffDays--;
}
If you are using the new Navigation Component, is simple as
findNavController().popBackStack()
It will do all the FragmentTransaction in behind for you.
Stash is just a convenience method. Since branches are so cheap and easy to manage in git, I personally almost always prefer creating a new temporary branch than stashing, but it's a matter of taste mostly.
The one place I do like stashing is if I discover I forgot something in my last commit and have already started working on the next one in the same branch:
# Assume the latest commit was already done
# start working on the next patch, and discovered I was missing something
# stash away the current mess I made
git stash save
# some changes in the working dir
# and now add them to the last commit:
git add -u
git commit --amend
# back to work!
git stash pop
To the best of my understanding, time.clock() has as much precision as your system will allow it.
You should be able to perform a select on the orders table, using a raw WHERE to find the max(id
) in a subquery, like this:
\DB::table('orders')->where('id', \DB::raw("(select max(`id`) from orders)"))->get();
If you want to use Eloquent (for example, so you can convert your response to an object) you will want to use whereRaw, because some functions such as toJSON
or toArray
will not work without using Eloquent models.
$order = Order::whereRaw('id = (select max(`id`) from orders)')->get();
That, of course, requires that you have a model that extends Eloquent.
class Order extends Eloquent {}
As mentioned in the comments, you don't need to use whereRaw
, you can do the entire query using the query builder without raw SQL.
// Using the Query Builder
\DB::table('orders')->find(\DB::table('orders')->max('id'));
// Using Eloquent
$order = Order::find(\DB::table('orders')->max('id'));
(Note that if the id
field is not unique, you will only get one row back - this is because find()
will only return the first result from the SQL server.).
It's an abbreviation of Error NO ENTry (or Error NO ENTity), and can actually be used for more than files/directories.
It's abbreviated because C compilers at the dawn of time didn't support more than 8 characters in symbols.
plot.new() error occurs when only part of the function is ran.
Please find the attachment for an example to correct error With error....When abline is ran without plot() above Error-free ...When both plot and abline ran together
short, sweet and you don't even need redirection :-)
perl -p -i -e 'tr/A-Z/a-z/' file
There is a jquery print area. I've been using it for some time now.
$(".printMe").click(function(){
$("#outprint").printArea({ mode: 'popup', popClose: true });
});
>>> import datetime
>>> d = datetime.datetime.strptime('2011-06-09', '%Y-%m-%d')
>>> d.strftime('%b %d,%Y')
'Jun 09,2011'
In pre-2.5 Python, you can replace datetime.strptime
with time.strptime
, like so (untested): datetime.datetime(*(time.strptime('2011-06-09', '%Y-%m-%d')[0:6]))
1: HTML
<tbody>
{% for ticket in tickets %}
<tr>
<td class="ticket_id">{{ticket.id}}</td>
<td class="ticket_eam">{{ticket.eam}}</td>
<td class="ticket_subject">{{ticket.subject}}</td>
<td>{{ticket.zone}}</td>
<td>{{ticket.plaza}}</td>
<td>{{ticket.lane}}</td>
<td>{{ticket.uptime}}</td>
<td>{{ticket.downtime}}</td>
<td><a href="{% url 'ticket_details' ticket_id=ticket.id %}"><button data-toggle="modal" data-target="#modaldemo3" class="value-modal"><i class="icon ion-edit"></a></i></button> <button><i class="fa fa-eye-slash"></i></button>
</tr>
{% endfor %}
</tbody>
The {% url 'ticket_details' %} is the function name in your views
2: Views.py
def ticket_details(request, ticket_id):
print(ticket_id)
return render(request, ticket.html)
ticket_id is the parameter you will get from the ticket_id=ticket.id
3: URL.py
urlpatterns = [
path('ticket_details/?P<int:ticket_id>/', views.ticket_details, name="ticket_details") ]
/?P - where ticket_id is the name of the group and pattern is some pattern to match.
Use this app : Servers Ultimate
With this app can run any server you can imagine on your android device (php, mysql, ftp, dhcp, ...) your phone will be a real server, just install the app click on (+) sign to add server, if the server is not installed the app will ask to download the package.
You can access your server via LAN or WAN easily.
All,
From what I'm seeing here all answers are wrong, especially if you entered the sudo mode, with all returning 'root' instead of the logged in user. The answer is in using 'who' and finding eh 'tty1' user and extracting that. Thw "w" command works the same and var=$SUDO_USER gets the real logged in user.
Cheers!
TBNK
TLDR; (just read the bold text)
Most answers here will tell you how to create an empty DataFrame and fill it out, but no one will tell you that it is a bad thing to do.
Here is my advice: Accumulate data in a list, not a DataFrame.
Use a list to collect your data, then initialise a DataFrame when you are ready. Either a list-of-lists or list-of-dicts format will work, pd.DataFrame
accepts both.
data = []
for a, b, c in some_function_that_yields_data():
data.append([a, b, c])
df = pd.DataFrame(data, columns=['A', 'B', 'C'])
Pros of this approach:
It is always cheaper to append to a list and create a DataFrame in one go than it is to create an empty DataFrame (or one of NaNs) and append to it over and over again.
Lists also take up less memory and are a much lighter data structure to work with, append, and remove (if needed).
dtypes
are automatically inferred (rather than assigning object
to all of them).
A RangeIndex
is automatically created for your data, instead of you having to take care to assign the correct index to the row you are appending at each iteration.
If you aren't convinced yet, this is also mentioned in the documentation:
Iteratively appending rows to a DataFrame can be more computationally intensive than a single concatenate. A better solution is to append those rows to a list and then concatenate the list with the original DataFrame all at once.
That's fine, you can still do this in linear time by growing or creating a python list of smaller DataFrames, then calling pd.concat
.
small_dfs = []
for small_df in some_function_that_yields_dataframes():
small_dfs.append(small_df)
large_df = pd.concat(small_dfs, ignore_index=True)
or, more concisely:
large_df = pd.concat(
list(some_function_that_yields_dataframes()), ignore_index=True)
append
or concat
inside a loopHere is the biggest mistake I've seen from beginners:
df = pd.DataFrame(columns=['A', 'B', 'C'])
for a, b, c in some_function_that_yields_data():
df = df.append({'A': i, 'B': b, 'C': c}, ignore_index=True) # yuck
# or similarly,
# df = pd.concat([df, pd.Series({'A': i, 'B': b, 'C': c})], ignore_index=True)
Memory is re-allocated for every append
or concat
operation you have. Couple this with a loop and you have a quadratic complexity operation.
The other mistake associated with df.append
is that users tend to forget append is not an in-place function, so the result must be assigned back. You also have to worry about the dtypes:
df = pd.DataFrame(columns=['A', 'B', 'C'])
df = df.append({'A': 1, 'B': 12.3, 'C': 'xyz'}, ignore_index=True)
df.dtypes
A object # yuck!
B float64
C object
dtype: object
Dealing with object columns is never a good thing, because pandas cannot vectorize operations on those columns. You will need to do this to fix it:
df.infer_objects().dtypes
A int64
B float64
C object
dtype: object
loc
inside a loopI have also seen loc
used to append to a DataFrame that was created empty:
df = pd.DataFrame(columns=['A', 'B', 'C'])
for a, b, c in some_function_that_yields_data():
df.loc[len(df)] = [a, b, c]
As before, you have not pre-allocated the amount of memory you need each time, so the memory is re-grown each time you create a new row. It's just as bad as append
, and even more ugly.
And then, there's creating a DataFrame of NaNs, and all the caveats associated therewith.
df = pd.DataFrame(columns=['A', 'B', 'C'], index=range(5))
df
A B C
0 NaN NaN NaN
1 NaN NaN NaN
2 NaN NaN NaN
3 NaN NaN NaN
4 NaN NaN NaN
It creates a DataFrame of object columns, like the others.
df.dtypes
A object # you DON'T want this
B object
C object
dtype: object
Appending still has all the issues as the methods above.
for i, (a, b, c) in enumerate(some_function_that_yields_data()):
df.iloc[i] = [a, b, c]
Timing these methods is the fastest way to see just how much they differ in terms of their memory and utility.
Here is the issue
$total_result = $result->num_rows;
try this
<?php
if ($result = $mysqli->query("SELECT * FROM players ORDER BY id"))
{
if ($result->num_rows > 0)
{
$total_result = $result->num_rows;
$total_pages = ceil($total_result / $per_page);
if(isset($_GET['page']) && is_numeric($_GET['page']))
{
$show_page = $_GET['page'];
if ($show_page > 0 && $show_page <= $total_pages)
{
$start = ($show_page - 1) * $per_page;
$end = $start + $per_page;
}
else
{
$start = 0;
$end = $per_page;
}
}
else
{
$start = 0;
$end = $per_page;
}
//display paginations
echo "<p> View pages: ";
for ($i=1; $i < $total_pages; $i++)
{
if (isset($_GET['page']) && $_GET['page'] == $i)
{
echo $i . " ";
}
else
{
echo "<a href='view-pag.php?$i'>" . $i . "</a> | ";
}
}
echo "</p>";
}
else
{
echo "No result to display.";
}
}
else
{
echo "Error: " . $mysqli->error;
}
?>
import sys
def hello(a, b):
print 'hello and that\'s your sum: {0}'.format(a + b)
if __name__ == '__main__':
hello(int(sys.argv[1]), int(sys.argv[2]))
Moreover see @thibauts answer about how to call python script.
int[] numbers = { 1, 3, 4, 9, 2 };
numbers = numbers.Except(new int[]{4}).ToArray();
<!DOCTYPE html>
<html>
<head>
<title>aj</title>
</head>
<body>
<canvas id="c"></canvas>
</body>
</html>
with CSS
body {
margin: 0;
padding: 0
}
#c {
position: absolute;
width: 100%;
height: 100%;
overflow: hidden
}
background-attachment: fixed;
http://www.w3.org/TR/CSS21/colors.html#background-properties
you can find your answer in the combination of these two pages in the API:
ref is used to register a reference to an element or a child component. The reference will be registered under the parent component’s $refs object. If used on a plain DOM element, the reference will be that element
An object that holds child components that have ref registered.
The simplest way is to use a FlatButton
wrapped inside a Container
, The button by default takes the size of its parent and so assign a desired width to the Container
.
Container(
color: Colors.transparent,
width: MediaQuery.of(context).size.width,
height: 60,
child: FlatButton(
shape: new RoundedRectangleBorder(
borderRadius: new BorderRadius.circular(30.0),
),
onPressed: () {},
color: Colors.red[300],
child: Text(
"Button",
style: TextStyle(
color: Colors.black,
fontFamily: 'Raleway',
fontSize: 22.0,
),
),
),
)
Output:
Use it for correct result
$dom = new DOMDocument();
$dom->loadHTML('<meta http-equiv="Content-Type" content="text/html; charset=utf-8">' . $profile);
echo $dom->saveHTML();
echo $profile;
This operation
mb_convert_encoding($profile, 'HTML-ENTITIES', 'UTF-8');
It is bad way, because special symbols like < ; , > ; can be in $profile, and they will not convert twice after mb_convert_encoding. It is the hole for XSS and incorrect HTML.
If you dont use asp.net or .net core there is also an easy way in >= .Net Standard 2.0 projects.
First you can set the desired size of the hash, salt and iteration number which is related to the duration of the hash generation:
private const int SaltSize = 32;
private const int HashSize = 32;
private const int IterationCount = 10000;
To generare the password hash and salt you can use something like this:
public static string GeneratePasswordHash(string password, out string salt)
{
using (Rfc2898DeriveBytes rfc2898DeriveBytes = new Rfc2898DeriveBytes(password, SaltSize))
{
rfc2898DeriveBytes.IterationCount = IterationCount;
byte[] hashData = rfc2898DeriveBytes.GetBytes(HashSize);
byte[] saltData = rfc2898DeriveBytes.Salt;
salt = Convert.ToBase64String(saltData);
return Convert.ToBase64String(hashData);
}
}
To verify if the password which the user entered is valid you can check with the values in your database:
public static bool VerifyPassword(string password, string passwordHash, string salt)
{
using (Rfc2898DeriveBytes rfc2898DeriveBytes = new Rfc2898DeriveBytes(password, SaltSize))
{
rfc2898DeriveBytes.IterationCount = IterationCount;
rfc2898DeriveBytes.Salt = Convert.FromBase64String(salt);
byte[] hashData = rfc2898DeriveBytes.GetBytes(HashSize);
return Convert.ToBase64String(hashData) == passwordHash;
}
}
The following unit test shows the usage:
string password = "MySecret";
string passwordHash = PasswordHasher.GeneratePasswordHash(password, out string salt);
Assert.True(PasswordHasher.VerifyPassword(password, passwordHash, salt));
Assert.False(PasswordHasher.VerifyPassword(password.ToUpper(), passwordHash, salt));
Convert Date To String
Use name Space
using System.Globalization;
Code
string date = DateTime.ParseExact(datetext.Text, "dd-MM-yyyy", CultureInfo.InstalledUICulture).ToString("yyyy-MM-dd");
I believe its in /tmp/. Check your phpinfo function though, it should say session.save_path in there somewhere.
Easy way of doing it would be:
<input type="file" accept=".gif,.jpg,.jpeg,.png,.doc,.docx">
Works with all browsers, except IE9. I haven't tested it in IE10+.
I also had a requirement something similar to it. I wanted to have a container in the center of the screen and inside the container there are many views. Following is the xml layout code. Here i'm using nested constraint layout to create container in the center of the screen.
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/gradient_background"
tools:context=".activities.AppInfoActivity">
<ImageView
android:id="@+id/ivClose"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_marginStart="20dp"
android:layout_marginTop="20dp"
android:src="@drawable/ic_round_close_24"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="300dp"
android:layout_height="300dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.5">
<ImageView
android:id="@+id/ivAppIcon"
android:layout_width="100dp"
android:layout_height="100dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="@drawable/dead" />
<TextView
android:id="@+id/tvAppName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Birds Shooter Plane"
android:textAlignment="center"
android:textSize="30sp"
android:textStyle="bold"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/ivAppIcon" />
<TextView
android:id="@+id/tvAppVersion"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Version : 1.0"
android:textAlignment="center"
android:textSize="12sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/tvAppName" />
<TextView
android:id="@+id/tvDevelopedBy"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="25dp"
android:text="Developed by"
android:textAlignment="center"
android:textSize="12sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/tvAppVersion" />
<TextView
android:id="@+id/tvDevelopedName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:text="K Pradeep Kumar Reddy"
android:textAlignment="center"
android:textSize="14sp"
android:textStyle="bold"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/tvDevelopedBy" />
<TextView
android:id="@+id/tvContact"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:text="Contact : [email protected]"
android:textAlignment="center"
android:textSize="12sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/tvDevelopedName" />
<TextView
android:id="@+id/tvCheckForUpdate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="25dp"
android:text="@string/check_for_update"
android:textAlignment="center"
android:textSize="14sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/tvContact" />
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
Here is the screenshot of the layout
Other solution is to remove the nested constraint layout and add constraint_vertical_bias = 0.5 attribute to the top element in the center of layout. I think this is called as chaining of views.
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/gradient_background"
tools:context=".activities.AppInfoActivity">
<ImageView
android:id="@+id/ivClose"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_marginStart="20dp"
android:layout_marginTop="20dp"
android:src="@drawable/ic_round_close_24"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<ImageView
android:id="@+id/ivAppIcon"
android:layout_width="100dp"
android:layout_height="100dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.5"
app:srcCompat="@drawable/dead" />
<TextView
android:id="@+id/tvAppName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/app_display_name"
android:textAlignment="center"
android:textSize="30sp"
android:textStyle="bold"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/ivAppIcon" />
<TextView
android:id="@+id/tvAppVersion"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/version"
android:textAlignment="center"
android:textSize="12sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/tvAppName" />
<TextView
android:id="@+id/tvDevelopedBy"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="25dp"
android:text="@string/developed_by"
android:textAlignment="center"
android:textSize="12sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/tvAppVersion" />
<TextView
android:id="@+id/tvDevelopedName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:text="@string/developer_name"
android:textAlignment="center"
android:textSize="14sp"
android:textStyle="bold"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/tvDevelopedBy" />
<TextView
android:id="@+id/tvContact"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:text="@string/developer_email"
android:textAlignment="center"
android:textSize="12sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/tvDevelopedName" />
<TextView
android:id="@+id/tvCheckForUpdate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="25dp"
android:text="@string/check_for_update"
android:textAlignment="center"
android:textSize="14sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/tvContact" />
</androidx.constraintlayout.widget.ConstraintLayout>
Substring
has two Overloading methods:
public string Substring(int startIndex);//The substring starts at a specified character position and continues to the end of the string.
public string Substring(int startIndex, int length);//The substring starts at a specified character position and taking length no of character from the startIndex.
So for this scenario, you may use the first method like this below:
var str = "hello world!";
str = str.Substring(10);
Here the output is:
d!
If you may apply defensive coding by checking its length.
I found my issue was an improper
if (leaf = NULL) {...}
where it should have been
if (leaf == NULL){...}
Check those compiler warnings!
You have to use parseInt() to convert
For eg.
var z = parseInt(x) + parseInt(y);
use parseFloat() if you want to handle float value.
char* charP = createStr();
Would be correct if your function was correct. Unfortunately you are returning a pointer to a local variable in the function which means that it is a pointer to undefined data as soon as the function returns. You need to use heap allocation like malloc for the string in your function in order for the pointer you return to have any meaning. Then you need to remember to free it later.
The problem is that you can't use a list
as the key in a dict
, since dict
keys need to be immutable. Use a tuple instead.
This is a list:
[x, y]
This is a tuple:
(x, y)
Note that in most cases, the (
and )
are optional, since ,
is what actually defines a tuple (as long as it's not surrounded by []
or {}
, or used as a function argument).
You might find the section on tuples in the Python tutorial useful:
Though tuples may seem similar to lists, they are often used in different situations and for different purposes. Tuples are immutable, and usually contain an heterogeneous sequence of elements that are accessed via unpacking (see later in this section) or indexing (or even by attribute in the case of namedtuples). Lists are mutable, and their elements are usually homogeneous and are accessed by iterating over the list.
And in the section on dictionaries:
Unlike sequences, which are indexed by a range of numbers, dictionaries are indexed by keys, which can be any immutable type; strings and numbers can always be keys. Tuples can be used as keys if they contain only strings, numbers, or tuples; if a tuple contains any mutable object either directly or indirectly, it cannot be used as a key. You can’t use lists as keys, since lists can be modified in place using index assignments, slice assignments, or methods like append() and extend().
In case you're wondering what the error message means, it's complaining because there's no built-in hash function for lists (by design), and dictionaries are implemented as hash tables.
Inspired by broofa's answer here.
preg_replace_callback('/[xy]/', function ($matches)
{
return dechex('x' == $matches[0] ? mt_rand(0, 15) : (mt_rand(0, 15) & 0x3 | 0x8));
}
, 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx');
Or if unable to use anonymous functions.
preg_replace_callback('/[xy]/', create_function(
'$matches',
'return dechex("x" == $matches[0] ? mt_rand(0, 15) : (mt_rand(0, 15) & 0x3 | 0x8));'
)
, 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx');
You should use this command to set the global installation flocation of npm packages
(git bash) npm config --global set prefix </path/you/want/to/use>/npm
(cmd/git-cmd) npm config --global set prefix <drive:\path\you\want\to\use>\npm
You may also consider the npm-cache
location right next to it. (as would be in a normal nodejs installation on windows)
(git bash) npm config --global set cache </path/you/want/to/use>/npm-cache
(cmd/git-cmd) npm config --global set cache <drive:\path\you\want\to\use>\npm-cache
Actually there is no any cancel()
or dismiss()
method from AlertDialog.Builder Class.
So Instead of AlertDialog.Builder optionDialog
use AlertDialog
instance.
Like,
AlertDialog optionDialog = new AlertDialog.Builder(this).create();
Now, Just call optionDialog.dismiss();
background.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
SetBackground();
// here I want to dismiss it after SetBackground() method
optionDialog.dismiss();
}
});
Update: using .indexOf()
to detect if stat
value is one of arr
elements
Pure JavaScript
var arr = [20,30,40,50,60,70,80,90,100];_x000D_
//or detect equal to all_x000D_
//var arr = [10,10,10,10,10,10,10];_x000D_
var stat = 10;_x000D_
_x000D_
if(arr.indexOf(stat)==-1)alert("stat is not equal to one more elements of array");
_x000D_
You can also just use the top command and your user ID will indicate the jobs running and the their times.
$ top
(this will show all running jobs)
$ top -U [user ID]
(This will show jobs that are specific for the user ID)
In the current version of safari this is not working anymore. You have to define the second parameter as non-passive by passing {passiv:false}
document.addEventListener('touchmove', function(e) {
e.preventDefault();
}, { passive: false });
With bash you may use read
like tis:
#!/usr/bin/env bash
{ IFS= read -rd '' value <config.txt;} 2>/dev/null
printf '%s' "$value"
Notice that:
The last newline is preserved.
The stderr
is silenced to /dev/null
by redirecting the whole commands block, but the return status of the read command is preserved, if one needed to handle read error conditions.
The part you should be interested in is the /?
part, which should solve most other questions you have with the tool.
Microsoft Windows XP [Version 5.1.2600] (C) Copyright 1985-2001 Microsoft Corp. C:\>cmd /? Starts a new instance of the Windows XP command interpreter CMD [/A | /U] [/Q] [/D] [/E:ON | /E:OFF] [/F:ON | /F:OFF] [/V:ON | /V:OFF] [[/S] [/C | /K] string] /C Carries out the command specified by string and then terminates /K Carries out the command specified by string but remains /S Modifies the treatment of string after /C or /K (see below) /Q Turns echo off /D Disable execution of AutoRun commands from registry (see below) /A Causes the output of internal commands to a pipe or file to be ANSI /U Causes the output of internal commands to a pipe or file to be Unicode /T:fg Sets the foreground/background colors (see COLOR /? for more info) /E:ON Enable command extensions (see below) /E:OFF Disable command extensions (see below) /F:ON Enable file and directory name completion characters (see below) /F:OFF Disable file and directory name completion characters (see below) /V:ON Enable delayed environment variable expansion using ! as the delimiter. For example, /V:ON would allow !var! to expand the variable var at execution time. The var syntax expands variables at input time, which is quite a different thing when inside of a FOR loop. /V:OFF Disable delayed environment expansion.
I've found a working code:
JSONParser parser = new JSONParser();
Object obj = parser.parse(content);
JSONArray array = new JSONArray();
array.add(obj);
PHP 7 ready version. It uses openssl_encrypt function from PHP OpenSSL Library.
class Openssl_EncryptDecrypt {
function encrypt ($pure_string, $encryption_key) {
$cipher = 'AES-256-CBC';
$options = OPENSSL_RAW_DATA;
$hash_algo = 'sha256';
$sha2len = 32;
$ivlen = openssl_cipher_iv_length($cipher);
$iv = openssl_random_pseudo_bytes($ivlen);
$ciphertext_raw = openssl_encrypt($pure_string, $cipher, $encryption_key, $options, $iv);
$hmac = hash_hmac($hash_algo, $ciphertext_raw, $encryption_key, true);
return $iv.$hmac.$ciphertext_raw;
}
function decrypt ($encrypted_string, $encryption_key) {
$cipher = 'AES-256-CBC';
$options = OPENSSL_RAW_DATA;
$hash_algo = 'sha256';
$sha2len = 32;
$ivlen = openssl_cipher_iv_length($cipher);
$iv = substr($encrypted_string, 0, $ivlen);
$hmac = substr($encrypted_string, $ivlen, $sha2len);
$ciphertext_raw = substr($encrypted_string, $ivlen+$sha2len);
$original_plaintext = openssl_decrypt($ciphertext_raw, $cipher, $encryption_key, $options, $iv);
$calcmac = hash_hmac($hash_algo, $ciphertext_raw, $encryption_key, true);
if(function_exists('hash_equals')) {
if (hash_equals($hmac, $calcmac)) return $original_plaintext;
} else {
if ($this->hash_equals_custom($hmac, $calcmac)) return $original_plaintext;
}
}
/**
* (Optional)
* hash_equals() function polyfilling.
* PHP 5.6+ timing attack safe comparison
*/
function hash_equals_custom($knownString, $userString) {
if (function_exists('mb_strlen')) {
$kLen = mb_strlen($knownString, '8bit');
$uLen = mb_strlen($userString, '8bit');
} else {
$kLen = strlen($knownString);
$uLen = strlen($userString);
}
if ($kLen !== $uLen) {
return false;
}
$result = 0;
for ($i = 0; $i < $kLen; $i++) {
$result |= (ord($knownString[$i]) ^ ord($userString[$i]));
}
return 0 === $result;
}
}
define('ENCRYPTION_KEY', '__^%&Q@$&*!@#$%^&*^__');
$string = "This is the original string!";
$OpensslEncryption = new Openssl_EncryptDecrypt;
$encrypted = $OpensslEncryption->encrypt($string, ENCRYPTION_KEY);
$decrypted = $OpensslEncryption->decrypt($encrypted, ENCRYPTION_KEY);
Either use
<embed src="file.pdf" />
if embedding is an option or my new plugin, PIFF: https://github.com/terrasoftlabs/piff
First things first, hover the mouse over the grey area below. Not part of the answer, but absolutely has to be said:
If you have a shell script that does "checkout, build, deploy" all by itself, then why are you using Jenkins? You are foregoing all the features of Jenkins that make it what it is. You might as well have a cron or an SVN post-commit hook call the script directly. Jenkins performing the SVN checkout itself is crucial. It allows the builds to be triggered only when there are changes (or on timer, or manual, if you prefer). It keeps track of changes between builds. It shows those changes, so you can see which build was for which set of changes. It emails committers when their changes caused successful or failed build (again, as configured as you prefer). It will email committers when their fixes fixed the failing build. And more and more. Jenkins archiving the artifacts also makes them available, per build, straight off Jenkins. While not as crucial as the SVN checkout, this is once again an integral part of what makes it Jenkins. Same with deploying. Unless you have a single environment, deployment usually happens to multiple environments. Jenkins can keep track of which environment a specific build (with specific set of SVN changes) is deployed it, through the use of Promotions. You are foregoing all of this. It sounds like you are told "you have to use Jenkins" but you don't really want to, and you are doing it just to get your bosses off your back, just to put a checkmark "yes, I've used Jenkins"
The short answer is: the exit code of last command of the Jenkin's Execute Shell build step is what determines the success/failure of the Build Step. 0
- success, anything else
- failure.
Note, this is determining the success/failure of the build step, not the whole job run. The success/failure of the whole job run can further be affected by multiple build steps, and post-build actions and plugins.
You've mentioned Build step 'Execute shell' marked build as failure
, so we will focus just on a single build step. If your Execute shell build step only has a single line that calls your shell script, then the exit code of your shell script will determine the success/failure of the build step. If you have more lines, after your shell script execution, then carefully review them, as they are the ones that could be causing failure.
Finally, have a read here Jenkins Build Script exits after Google Test execution. It is not directly related to your question, but note that part about Jenkins launching the Execute Shell build step, as a shell script with /bin/sh -xe
The -e
means that the shell script will exit with failure, even if just 1 command fails, even if you do error checking for that command (because the script exits before it gets to your error checking). This is contrary to normal execution of shell scripts, which usually print the error message for the failed command (or redirect it to null and handle it by other means), and continue.
To circumvent this, add set +e
to the top of your shell script.
Since you say your script does all it is supposed to do, chances are the failing command is somewhere at the end of the script. Maybe a final echo? Or copy of artifacts somewhere? Without seeing the full console output, we are just guessing.
Please post the job run's console output, and preferably the shell script itself too, and then we could tell you exactly which line is failing.
First you have to create a li
(with id and value as you required) then add it to your ul
.
Javascript ::
addAnother = function() {
var ul = document.getElementById("list");
var li = document.createElement("li");
var children = ul.children.length + 1
li.setAttribute("id", "element"+children)
li.appendChild(document.createTextNode("Element "+children));
ul.appendChild(li)
}
Check this example that add li
element to ul
.
Case statement syntax in SQL SERVER:
CASE column
WHEN value1 THEN 1
WHEN value3 THEN 2
WHEN value3 THEN 3
WHEN value1 THEN 4
ELSE ''
END
And we can use like below also:
CASE
WHEN column=value1 THEN 1
WHEN column=value3 THEN 2
WHEN column=value3 THEN 3
WHEN column=value1 THEN 4
ELSE ''
END
This will create you the result in lightning fast.
select top 100000 identity (int ,1,1) as Sequence into Tally from sysobjects , sys.all_columns
select dateadd(dd,sequence,-1) Dates into CalenderTable from tally
delete from CalenderTable where dates < -- mention the mindate you need
delete from CalenderTable where dates > -- mention the max date you need
Step 1 : Create a sequence table
Step 2 : Use the sequence table to generate the desired dates
Step 3 : Delete unwanted dates
Array.reduce could be inefficient for large arrays, especially with the mod operator. I think a cleaner (and possibly easier to read) functional solution would be this:
const chunkArray = (arr, size) =>
arr.length > size
? [arr.slice(0, size), ...chunkArray(arr.slice(size), size)]
: [arr];
<script type="text/javascript" >
function aa()
{
var YourArray = ['United States', 'Canada', 'Argentina', 'Armenia'];
var ObjUl = $('<ul></ul>');
for (i = 0; i < YourArray.length; i++)
{
var Objli = $('<li></li>');
var Obja = $('<a></a>');
ObjUl.addClass("ui-menu-item");
ObjUl.attr("role", "menuitem");
Obja.addClass("ui-all");
Obja.attr("tabindex", "-1");
Obja.text(YourArray[i]);
Objli.append(Obja);
ObjUl.append(Objli);
}
$('.DivSai').append(ObjUl);
}
</script>
</head>
<body onload="aa()">
<form id="form1" runat="server">
<div class="DivSai" >
</div>
</form>
</body>
This will not work java -cp lib\*.jar -jar myproject.jar
. You have to put it jar by jar.
So in case of commons-codec-1.3.jar
.
java -cp lib/commons-codec-1.3.jar;lib/next_jar.jar
and so on.
The other solution might be putting all your jars to ext
directory of your JRE. This is ok if you are using a standalone JRE. If you are using the same JRE for running more than one application I do not recommend doing it.
For .NET Core projects, run dotnet restore
or dotnet build
command in NuGet Package Manager Console
(which automatically runs restore)
You can run console from
Tools > NuGet Package Manager > Package Manager Console
SOAP
Simple Object Access Protocol (SOAP) is a standard, an XML language, defining a message architecture and message formats. It is used by Web services. It contains a description of the operations.
WSDL is an XML-based language for describing Web services and how to access them. It will run on SMTP, HTTP, FTP, etc. It requires middleware support and well-defined mechanism to define services like WSDL+XSD and WS-Policy. SOAP will return XML based data
REST
Representational State Transfer (RESTful) web services. They are second-generation Web services.
RESTful web services communicate via HTTP rather than SOAP-based services and do not require XML messages or WSDL service-API definitions. For REST middleware is not required, only HTTP support is needed. It is a WADL standard, REST can return XML, plain text, JSON, HTML, etc.
Make sure that you update your php.ini
for CLI
. For my case this was C:\wamp\bin\php\php5.4.3\php.ini
and uncomment extension=php_openssl.dll
line.
Use the credential that you use to login to PC. Username can be searched by Clicking in sequence
Advanced -> Find -> Choose your Username -> (e.g. JOHNSMITH_HP/John)
Password must be same as your windows login password
There you go !!
You can create NSAttributedString
NSDictionary *attributes = @{ NSForegroundColorAttributeName : [UIColor redColor] };
NSAttributedString *attrStr = [[NSAttributedString alloc] initWithString:@"My Color String" attributes:attrs];
OR NSMutableAttributedString
to apply custom attributes with Ranges.
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@%@", methodPrefix, method] attributes: @{ NSFontAttributeName : FONT_MYRIADPRO(48) }];
[attributedString addAttribute:NSFontAttributeName value:FONT_MYRIADPRO_SEMIBOLD(48) range:NSMakeRange(methodPrefix.length, method.length)];
Available Attributes: NSAttributedStringKey
UPDATE:
let message: String = greeting + someMessage
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = 2.0
// Note: UIFont(appFontFamily:ofSize:) is extended init.
let regularAttributes: [NSAttributedString.Key : Any] = [.font : UIFont(appFontFamily: .regular, ofSize: 15)!, .paragraphStyle : paragraphStyle]
let boldAttributes = [NSAttributedString.Key.font : UIFont(appFontFamily: .semiBold, ofSize: 15)!]
let mutableString = NSMutableAttributedString(string: message, attributes: regularAttributes)
mutableString.addAttributes(boldAttributes, range: NSMakeRange(0, greeting.count))
This was what worked for me (using jquery datepicker):
$('body').on('focus', '.datepicker', function() {
$(this).removeClass('hasDatepicker').datepicker();
});
I'd like to share with you how I address this kind of question. My case is slightly different as the result of table2 is dynamic and the column numbers may be less than that of table1. But the concept is the same.
First, get the result of table2.
Next, unpivot it.
Then write the update query using dynamic SQL. Sample code is written for testing 2 simple tables - tblA and tblB
--CREATE TABLE tblA(id int, col1 VARCHAR(25), col2 VARCHAR(25), col3 VARCHAR(25), col4 VARCHAR(25))
--CREATE TABLE tblB(id int, col1 VARCHAR(25), col2 VARCHAR(25), col3 VARCHAR(25), col4 VARCHAR(25))
--INSERT INTO tblA(id, col1, col2, col3, col4)
--VALUES(1,'A1','A2','A3','A4')
--INSERT INTO tblB(id, col1, col2, col3, col4)
--VALUES(1,'B1','B2','B3','B4')
DECLARE @id VARCHAR(10) = 1, @TSQL NVARCHAR(MAX)
DECLARE @tblPivot TABLE(
colName VARCHAR(255),
val VARCHAR(255)
)
INSERT INTO @tblPivot
SELECT colName, val
FROM tblB
UNPIVOT
(
val
FOR colName IN (col1, col2, col3, col4)
) unpiv
WHERE id = @id
SELECT @TSQL = COALESCE(@TSQL + '''
,','') + colName + ' = ''' + val
FROM @tblPivot
SET @TSQL = N'UPDATE tblA
SET ' + @TSQL + '''
WHERE id = ' + @id
PRINT @TSQL
--EXEC SP_EXECUTESQL @TSQL
PRINT @TSQL
result:
If it fits the protocol you use, consider using a DataInputStream, where the behavior is very well defined.
If you have such error when using remote oracle database, you can delete your tnsname and listener then create new config with "hostname" or ip address instead of "localhost". such as listener.ora
LISTENER =
(DESCRIPTION_LIST =
(DESCRIPTION =
(ADDRESS = (PROTOCOL = TCP)(HOST = hostname)(PORT = 1521))
)
tnsnames.ora
DB =
(DESCRIPTION =
(ADDRESS_LIST =
(ADDRESS = (PROTOCOL = TCP)(HOST = hostname)(PORT = 1521))
)
(CONNECT_DATA =
(SERVICE_NAME = DB)
)
)
It works fine for me.
Try using the -L
flag with pg_restore by specifying the file taken from pg_dump -Fc
-L list-file --use-list=list-file
Restore only those archive elements that are listed in list-file, and restore them in the order they appear in the file. Note that if filtering switches such as -n or -t are used with -L, they will further restrict the items restored.
list-file is normally created by editing the output of a previous -l operation. Lines can be moved or removed, and can also be commented out by placing a semicolon (;) at the start of the line. See below for examples.
https://www.postgresql.org/docs/9.5/app-pgrestore.html
pg_dump -Fc -f pg.dump db_name
pg_restore -l pg.dump | grep -v 'COMMENT - EXTENSION' > pg_restore.list
pg_restore -L pg_restore.list pg.dump
Here you can see the Inverse is true by outputting only the comment:
pg_dump -Fc -f pg.dump db_name
pg_restore -l pg.dump | grep 'COMMENT - EXTENSION' > pg_restore_inverse.list
pg_restore -L pg_restore_inverse.list pg.dump
--
-- PostgreSQL database dump
--
-- Dumped from database version 9.4.15
-- Dumped by pg_dump version 9.5.14
SET statement_timeout = 0;
SET lock_timeout = 0;
SET client_encoding = 'UTF8';
SET standard_conforming_strings = on;
SELECT pg_catalog.set_config('search_path', '', false);
SET check_function_bodies = false;
SET client_min_messages = warning;
SET row_security = off;
--
-- Name: EXTENSION plpgsql; Type: COMMENT; Schema: -; Owner:
--
COMMENT ON EXTENSION plpgsql IS 'PL/pgSQL procedural language';
--
-- PostgreSQL database dump complete
--
Here's an example if you need to join more than 2 tables:
from d in context.dc_tpatient_bookingd
join bookingm in context.dc_tpatient_bookingm
on d.bookingid equals bookingm.bookingid into bookingmGroup
from m in bookingmGroup.DefaultIfEmpty()
join patient in dc_tpatient
on m.prid equals patient.prid into patientGroup
from p in patientGroup.DefaultIfEmpty()
Fix: Unlock your device before running it.
Hi Guys: Think I may have a fix for this:
Sounds ridiculous but try unlocking your Virtual Device; i.e. use your mouse to swipe and open. Your app should then work!!
Python has no built-in encryption schemes, no. You also should take encrypted data storage serious; trivial encryption schemes that one developer understands to be insecure and a toy scheme may well be mistaken for a secure scheme by a less experienced developer. If you encrypt, encrypt properly.
You don’t need to do much work to implement a proper encryption scheme however. First of all, don’t re-invent the cryptography wheel, use a trusted cryptography library to handle this for you. For Python 3, that trusted library is cryptography
.
I also recommend that encryption and decryption applies to bytes; encode text messages to bytes first; stringvalue.encode()
encodes to UTF8, easily reverted again using bytesvalue.decode()
.
Last but not least, when encrypting and decrypting, we talk about keys, not passwords. A key should not be human memorable, it is something you store in a secret location but machine readable, whereas a password often can be human-readable and memorised. You can derive a key from a password, with a little care.
But for a web application or process running in a cluster without human attention to keep running it, you want to use a key. Passwords are for when only an end-user needs access to the specific information. Even then, you usually secure the application with a password, then exchange encrypted information using a key, perhaps one attached to the user account.
The cryptography
library includes the Fernet recipe, a best-practices recipe for using cryptography. Fernet is an open standard,
with ready implementations in a wide range of programming languages and it packages AES CBC encryption for you with version information, a timestamp and an HMAC signature to prevent message tampering.
Fernet makes it very easy to encrypt and decrypt messages and keep you secure. It is the ideal method for encrypting data with a secret.
I recommend you use Fernet.generate_key()
to generate a secure key. You can use a password too (next section), but a full 32-byte secret key (16 bytes to encrypt with, plus another 16 for the signature) is going to be more secure than most passwords you could think of.
The key that Fernet generates is a bytes
object with URL and file safe base64 characters, so printable:
from cryptography.fernet import Fernet
key = Fernet.generate_key() # store in a secure location
print("Key:", key.decode())
To encrypt or decrypt messages, create a Fernet()
instance with the given key, and call the Fernet.encrypt()
or Fernet.decrypt()
, both the plaintext message to encrypt and the encrypted token are bytes
objects.
encrypt()
and decrypt()
functions would look like:
from cryptography.fernet import Fernet
def encrypt(message: bytes, key: bytes) -> bytes:
return Fernet(key).encrypt(message)
def decrypt(token: bytes, key: bytes) -> bytes:
return Fernet(key).decrypt(token)
Demo:
>>> key = Fernet.generate_key()
>>> print(key.decode())
GZWKEhHGNopxRdOHS4H4IyKhLQ8lwnyU7vRLrM3sebY=
>>> message = 'John Doe'
>>> encrypt(message.encode(), key)
'gAAAAABciT3pFbbSihD_HZBZ8kqfAj94UhknamBuirZWKivWOukgKQ03qE2mcuvpuwCSuZ-X_Xkud0uWQLZ5e-aOwLC0Ccnepg=='
>>> token = _
>>> decrypt(token, key).decode()
'John Doe'
You can use a password instead of a secret key, provided you use a strong key derivation method. You do then have to include the salt and the HMAC iteration count in the message, so the encrypted value is not Fernet-compatible anymore without first separating salt, count and Fernet token:
import secrets
from base64 import urlsafe_b64encode as b64e, urlsafe_b64decode as b64d
from cryptography.fernet import Fernet
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
backend = default_backend()
iterations = 100_000
def _derive_key(password: bytes, salt: bytes, iterations: int = iterations) -> bytes:
"""Derive a secret key from a given password and salt"""
kdf = PBKDF2HMAC(
algorithm=hashes.SHA256(), length=32, salt=salt,
iterations=iterations, backend=backend)
return b64e(kdf.derive(password))
def password_encrypt(message: bytes, password: str, iterations: int = iterations) -> bytes:
salt = secrets.token_bytes(16)
key = _derive_key(password.encode(), salt, iterations)
return b64e(
b'%b%b%b' % (
salt,
iterations.to_bytes(4, 'big'),
b64d(Fernet(key).encrypt(message)),
)
)
def password_decrypt(token: bytes, password: str) -> bytes:
decoded = b64d(token)
salt, iter, token = decoded[:16], decoded[16:20], b64e(decoded[20:])
iterations = int.from_bytes(iter, 'big')
key = _derive_key(password.encode(), salt, iterations)
return Fernet(key).decrypt(token)
Demo:
>>> message = 'John Doe'
>>> password = 'mypass'
>>> password_encrypt(message.encode(), password)
b'9Ljs-w8IRM3XT1NDBbSBuQABhqCAAAAAAFyJdhiCPXms2vQHO7o81xZJn5r8_PAtro8Qpw48kdKrq4vt-551BCUbcErb_GyYRz8SVsu8hxTXvvKOn9QdewRGDfwx'
>>> token = _
>>> password_decrypt(token, password).decode()
'John Doe'
Including the salt in the output makes it possible to use a random salt value, which in turn ensures the encrypted output is guaranteed to be fully random regardless of password reuse or message repetition. Including the iteration count ensures that you can adjust for CPU performance increases over time without losing the ability to decrypt older messages.
A password alone can be as safe as a Fernet 32-byte random key, provided you generate a properly random password from a similar size pool. 32 bytes gives you 256 ^ 32 number of keys, so if you use an alphabet of 74 characters (26 upper, 26 lower, 10 digits and 12 possible symbols), then your password should be at least math.ceil(math.log(256 ** 32, 74))
== 42 characters long. However, a well-selected larger number of HMAC iterations can mitigate the lack of entropy somewhat as this makes it much more expensive for an attacker to brute force their way in.
Just know that choosing a shorter but still reasonably secure password won’t cripple this scheme, it just reduces the number of possible values a brute-force attacker would have to search through; make sure to pick a strong enough password for your security requirements.
An alternative is not to encrypt. Don't be tempted to just use a low-security cipher, or a home-spun implementation of, say Vignere. There is no security in these approaches, but may give an inexperienced developer that is given the task to maintain your code in future the illusion of security, which is worse than no security at all.
If all you need is obscurity, just base64 the data; for URL-safe requirements, the base64.urlsafe_b64encode()
function is fine. Don't use a password here, just encode and you are done. At most, add some compression (like zlib
):
import zlib
from base64 import urlsafe_b64encode as b64e, urlsafe_b64decode as b64d
def obscure(data: bytes) -> bytes:
return b64e(zlib.compress(data, 9))
def unobscure(obscured: bytes) -> bytes:
return zlib.decompress(b64d(obscured))
This turns b'Hello world!'
into b'eNrzSM3JyVcozy_KSVEEAB0JBF4='
.
If all you need is a way to make sure that the data can be trusted to be unaltered after having been sent to an untrusted client and received back, then you want to sign the data, you can use the hmac
library for this with SHA1 (still considered secure for HMAC signing) or better:
import hmac
import hashlib
def sign(data: bytes, key: bytes, algorithm=hashlib.sha256) -> bytes:
assert len(key) >= algorithm().digest_size, (
"Key must be at least as long as the digest size of the "
"hashing algorithm"
)
return hmac.new(key, data, algorithm).digest()
def verify(signature: bytes, data: bytes, key: bytes, algorithm=hashlib.sha256) -> bytes:
expected = sign(data, key, algorithm)
return hmac.compare_digest(expected, signature)
Use this to sign data, then attach the signature with the data and send that to the client. When you receive the data back, split data and signature and verify. I've set the default algorithm to SHA256, so you'll need a 32-byte key:
key = secrets.token_bytes(32)
You may want to look at the itsdangerous
library, which packages this all up with serialisation and de-serialisation in various formats.
Fernet builds on AEC-CBC with a HMAC signature to ensure integrity of the encrypted data; a malicious attacker can't feed your system nonsense data to keep your service busy running in circles with bad input, because the ciphertext is signed.
The Galois / Counter mode block cipher produces ciphertext and a tag to serve the same purpose, so can be used to serve the same purposes. The downside is that unlike Fernet there is no easy-to-use one-size-fits-all recipe to reuse on other platforms. AES-GCM also doesn't use padding, so this encryption ciphertext matches the length of the input message (whereas Fernet / AES-CBC encrypts messages to blocks of fixed length, obscuring the message length somewhat).
AES256-GCM takes the usual 32 byte secret as a key:
key = secrets.token_bytes(32)
then use
import binascii, time
from base64 import urlsafe_b64encode as b64e, urlsafe_b64decode as b64d
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.backends import default_backend
from cryptography.exceptions import InvalidTag
backend = default_backend()
def aes_gcm_encrypt(message: bytes, key: bytes) -> bytes:
current_time = int(time.time()).to_bytes(8, 'big')
algorithm = algorithms.AES(key)
iv = secrets.token_bytes(algorithm.block_size // 8)
cipher = Cipher(algorithm, modes.GCM(iv), backend=backend)
encryptor = cipher.encryptor()
encryptor.authenticate_additional_data(current_time)
ciphertext = encryptor.update(message) + encryptor.finalize()
return b64e(current_time + iv + ciphertext + encryptor.tag)
def aes_gcm_decrypt(token: bytes, key: bytes, ttl=None) -> bytes:
algorithm = algorithms.AES(key)
try:
data = b64d(token)
except (TypeError, binascii.Error):
raise InvalidToken
timestamp, iv, tag = data[:8], data[8:algorithm.block_size // 8 + 8], data[-16:]
if ttl is not None:
current_time = int(time.time())
time_encrypted, = int.from_bytes(data[:8], 'big')
if time_encrypted + ttl < current_time or current_time + 60 < time_encrypted:
# too old or created well before our current time + 1 h to account for clock skew
raise InvalidToken
cipher = Cipher(algorithm, modes.GCM(iv, tag), backend=backend)
decryptor = cipher.decryptor()
decryptor.authenticate_additional_data(timestamp)
ciphertext = data[8 + len(iv):-16]
return decryptor.update(ciphertext) + decryptor.finalize()
I've included a timestamp to support the same time-to-live use-cases that Fernet supports.
This is the approach that All ?? V????y follows, albeit incorrectly. This is the cryptography
version, but note that I include the IV in the ciphertext, it should not be stored as a global (reusing an IV weakens the security of the key, and storing it as a module global means it'll be re-generated the next Python invocation, rendering all ciphertext undecryptable):
import secrets
from base64 import urlsafe_b64encode as b64e, urlsafe_b64decode as b64d
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.backends import default_backend
backend = default_backend()
def aes_cfb_encrypt(message, key):
algorithm = algorithms.AES(key)
iv = secrets.token_bytes(algorithm.block_size // 8)
cipher = Cipher(algorithm, modes.CFB(iv), backend=backend)
encryptor = cipher.encryptor()
ciphertext = encryptor.update(message) + encryptor.finalize()
return b64e(iv + ciphertext)
def aes_cfb_decrypt(ciphertext, key):
iv_ciphertext = b64d(ciphertext)
algorithm = algorithms.AES(key)
size = algorithm.block_size // 8
iv, encrypted = iv_ciphertext[:size], iv_ciphertext[size:]
cipher = Cipher(algorithm, modes.CFB(iv), backend=backend)
decryptor = cipher.decryptor()
return decryptor.update(encrypted) + decryptor.finalize()
This lacks the added armoring of an HMAC signature and there is no timestamp; you’d have to add those yourself.
The above also illustrates how easy it is to combine basic cryptography building blocks incorrectly; All ?? V????y‘s incorrect handling of the IV value can lead to a data breach or all encrypted messages being unreadable because the IV is lost. Using Fernet instead protects you from such mistakes.
If you previously implemented AES ECB encryption and need to still support this in Python 3, you can do so still with cryptography
too. The same caveats apply, ECB is not secure enough for real-life applications. Re-implementing that answer for Python 3, adding automatic handling of padding:
from base64 import urlsafe_b64encode as b64e, urlsafe_b64decode as b64d
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.primitives import padding
from cryptography.hazmat.backends import default_backend
backend = default_backend()
def aes_ecb_encrypt(message, key):
cipher = Cipher(algorithms.AES(key), modes.ECB(), backend=backend)
encryptor = cipher.encryptor()
padder = padding.PKCS7(cipher.algorithm.block_size).padder()
padded = padder.update(msg_text.encode()) + padder.finalize()
return b64e(encryptor.update(padded) + encryptor.finalize())
def aes_ecb_decrypt(ciphertext, key):
cipher = Cipher(algorithms.AES(key), modes.ECB(), backend=backend)
decryptor = cipher.decryptor()
unpadder = padding.PKCS7(cipher.algorithm.block_size).unpadder()
padded = decryptor.update(b64d(ciphertext)) + decryptor.finalize()
return unpadder.update(padded) + unpadder.finalize()
Again, this lacks the HMAC signature, and you shouldn’t use ECB anyway. The above is there merely to illustrate that cryptography
can handle the common cryptographic building blocks, even the ones you shouldn’t actually use.
it should. Typically that's how you do multiple selectors. Otherwise it may not like you trying to assign the return values of three uploads to the same var.
I would suggest using .each
or maybe push the returns to an array rather than assigning them to that value.
As mentioned in the comments height:100% relies on the height of the parent container being explicitly defined. One way to achieve what you want is to use absolute/relative positioning, and specifying the left/right/top/bottom properties to "stretch" the content out to fill the available space. I have implemented what I gather you want to achieve in jsfiddle. Try resizing the Result window and you will see the content resizes automatically.
The limitation of this approach in your case is that you have to specify an explicit margin-top on the parent container to offset its contents down to make room for the header content. You can make it dynamic if you throw in javascript though.
I also faced a similar problem when trying to find a package that finds quartiles. That's not to say the others are wrong but to say this is how I personally would have defined quartiles. It is similar to Shikar's results with using mid-point but also works on lists that have an odd length. If the quartile position is between lengths, it will use the average of the neighbouring values. (i.e. position always treated as either the exact position or 0.5 of the position)
import math
def find_quartile_postions(size):
if size == 1:
# All quartiles are the first (only) element
return 0, 0, 0
elif size == 2:
# Lower quartile is first element, Upper quartile is second element, Median is average
# Set to 0.5, 0.5, 0.5 if you prefer all quartiles to be the mean value
return 0, 0.5, 1
else:
# Lower quartile is element at 1/4th position, median at 1/2th, upper at 3/4
# Quartiles can be between positions if size + 1 is not divisible by 4
return (size + 1) / 4 - 1, (size + 1) / 2 - 1, 3 * (size + 1) / 4 - 1
def find_quartiles(num_array):
size = len(num_array)
if size == 0:
quartiles = [0,0,0]
else:
sorted_array = sorted(num_array)
lower_pos, median_pos, upper_pos = find_quartile_postions(size)
# Floor so can work in arrays
floored_lower_pos = math.floor(lower_pos)
floored_median_pos = math.floor(median_pos)
floored_upper_pos = math.floor(upper_pos)
# If position is an integer, the quartile is the elem at position
# else the quartile is the mean of the elem & the elem one position above
lower_quartile = (sorted_array[floored_lower_pos]
if (lower_pos % 1 == 0)
else (sorted_array[floored_lower_pos] + sorted_array[floored_lower_pos + 1]) / 2
)
median = (sorted_array[floored_median_pos]
if (median_pos % 1 == 0)
else (sorted_array[floored_median_pos] + sorted_array[floored_median_pos + 1]) / 2
)
upper_quartile = (sorted_array[floored_upper_pos]
if (upper_pos % 1 == 0)
else (sorted_array[floored_upper_pos] + sorted_array[floored_upper_pos + 1]) / 2
)
quartiles = [lower_quartile, median, upper_quartile]
return quartiles
<script type="text/javascript"></script>
because its the right way and compatible with all browsers
Starting from Rob's answer, I am currently using the following syntax.Since the question has received a lot of attention,I decided to share it with you :
var requrl = '@Url.Action("Action", "Controller", null, Request.Url.Scheme, null)';
$.ajax({
type: "POST",
url: requrl,
data: "{queryString:'" + searchVal + "'}",
contentType: "application/json; charset=utf-8",
dataType: "html",
success: function (data) {
alert("here" + data.d.toString());
}
});
I figured it out! The page was rendering using IE8 mode... had
<meta http-equiv="X-UA-Compatible" content="IE=8">
in the header... changed it to
<meta http-equiv="X-UA-Compatible" content="IE=9">
9 and it worked!
just because the OOP rule: Data Hiding and Encapsulation. It is a very bad practice to declare a object's as public and change it on the fly in most situations. Also there are many other reasons , but the root is Encapsulation in OOP. and "buy a book or go read on Object Oriented Programming ", you will understand everything on this after you read any book on OOP.
With many files and many cores, fread xargs cat
(described below) is about 50x faster than the fastest solution in the top 3 answers.
rbindlist lapply read.delim 500s <- 1st place & accepted answer
rbindlist lapply fread 250s <- 2nd & 3rd place answers
rbindlist mclapply fread 10s
fread xargs cat 5s
Time to read 121401 csvs into a single data.table. Each time is an average of three runs then rounded. Each csv has 3 columns, one header row, and, on average, 4.510 rows. Machine is a GCP VM with 96 cores.
The top three answers by @A5C1D2H2I1M1N2O1R2T1, @leerssej, and @marbel and are all essentially the same: apply fread (or read.delim) to each file, then rbind/rbindlist the resulting data.tables. I usually use the rbindlist(lapply(list.files("*.csv"),fread))
form.
This is better than other R-internal alternatives, and fine for a small number of large csvs, but not the best for a large number of small csvs when speed matters. In that case, it can be much faster to first use cat
, as @Spacedman suggests in the 4th-ranked answer. I'll add some detail on how to do this from within R:
x = fread(cmd='cat *.csv', header=F)
However, what if each csv has a header?
x = fread(cmd="awk 'NR==1||FNR!=1' *.csv", header=T)
And what if you have so many files that the *.csv
shell glob fails?
x = fread(cmd='find . -name "*.csv" | xargs cat', header=F)
And what if all files have a header AND there are too many files?
header = fread(cmd='find . -name "*.csv" | head -n1 | xargs head -n1', header=T)
x = fread(cmd='find . -name "*.csv" | xargs tail -q -n+2', header=F)
names(x) = names(header)
And what if the resulting concatenated csv is too big for system memory?
system('find . -name "*.csv" | xargs cat > combined.csv')
x = fread('combined.csv', header=F)
With headers?
system('find . -name "*.csv" | head -n1 | xargs head -n1 > combined.csv')
system('find . -name "*.csv" | xargs tail -q -n+2 >> combined.csv')
x = fread('combined.csv', header=T)
Finally, what if you don't want all .csv in a directory, but rather a specific set of files? (Also, they all have headers.) (This is my use case.)
fread(text=paste0(system("xargs cat|awk 'NR==1||$1!=\"<column one name>\"'",input=paths,intern=T),collapse="\n"),header=T,sep="\t")
and this is about the same speed as plain fread xargs cat :)
Note: for data.table pre-v1.11.6 (19 Sep 2018), omit the cmd=
from fread(cmd=
.
Addendum: using the parallel library's mclapply in place of serial lapply, e.g., rbindlist(lapply(list.files("*.csv"),fread))
is also much faster than rbindlist lapply fread.
To sum up, if you're interested in speed, and have many files and many cores, fread xargs cat is about 50x faster than the fastest solution in the top 3 answers.
First check the variables declared using proper Datatypes. I had a same problem then I have checked, by mistake I declared SAPUser as int datatype so that the error occurred. One more thing XML file stores its data using concept like array but its first index starts having +1. e.g. if error is in(7,2) then check for 6th line always.....
Instructions for finding MSBuild:
&"${env:ProgramFiles(x86)}\Microsoft Visual Studio\Installer\vswhere.exe" -latest -prerelease -products * -requires Microsoft.Component.MSBuild -find MSBuild\**\Bin\MSBuild.exe
"%ProgramFiles(x86)%\Microsoft Visual Studio\Installer\vswhere.exe" -latest -prerelease -products * -requires Microsoft.Component.MSBuild -find MSBuild\**\Bin\MSBuild.exe
Instructions for finding VSTest:
&"${env:ProgramFiles(x86)}\Microsoft Visual Studio\Installer\vswhere.exe" -latest -prerelease -products * -requires Microsoft.VisualStudio.PackageGroup.TestTools.Core -find Common7\IDE\CommonExtensions\Microsoft\TestWindow\vstest.console.exe
"%ProgramFiles(x86)%\Microsoft Visual Studio\Installer\vswhere.exe" -latest -prerelease -products * -requires Microsoft.VisualStudio.PackageGroup.TestTools.Core -find Common7\IDE\CommonExtensions\Microsoft\TestWindow\vstest.console.exe
(Note that the instructions above are slightly modified from Microsoft's official ones. In particular, I've included the -prerelease
flag to allow Preview and RC installations to be picked up, and the -products *
to detect Visual Studio Build Tools installations.)
It only took over two years but finally in 2019, Microsoft has listened and given us a way to find these vital executables! If you have Visual Studio 2017 and/or 2019 installed, the vswhere
utility can be queried for the location of MSBuild et al. Since vswhere
is guaranteed by Microsoft to be located at %ProgramFiles(x86)%\Microsoft Visual Studio\Installer\vswhere.exe
, there is no bootstrapping and no path hardcoding required anymore.
The magic is the -find
parameter, added in version 2.6.2. You can determine the version you have installed by running vswhere
, or checking its file properties. If you have an older version, you can simply download the latest one and overwrite the existing %ProgramFiles(x86)%\Microsoft Visual Studio\Installer\vswhere.exe
.
vswhere.exe
is a standalone executable, so you can download and run it from anywhere you have an internet connection. That means your build scripts can check if the environment they're running on is setup correctly, to name one option.
edit your ~/.vimrc
, and add different file types for different indents,e.g. I want html/rb
indent for 2 spaces, and js/coffee
files indent for 4 spaces:
" by default, the indent is 2 spaces.
set shiftwidth=2
set softtabstop=2
set tabstop=2
" for html/rb files, 2 spaces
autocmd Filetype html setlocal ts=2 sw=2 expandtab
autocmd Filetype ruby setlocal ts=2 sw=2 expandtab
" for js/coffee/jade files, 4 spaces
autocmd Filetype javascript setlocal ts=4 sw=4 sts=0 expandtab
autocmd Filetype coffeescript setlocal ts=4 sw=4 sts=0 expandtab
autocmd Filetype jade setlocal ts=4 sw=4 sts=0 expandtab
If you don't mind using system()
, doing system("taskkill /f /im process.exe")
would be significantly easier than these other methods.
<div class="content">
Counter-Strike 1.6 Steam
<img src="images/CSsteam.png">
<a href="#">Koupit</a>
</div>
/*Use this css*/
content {
width: 182px; /*328 co je 1/3 - 20margin left*/
height: 121px;
line-height: 20px;
margin-top: 0px;
margin-left: 9px;
margin-right:0px;
display:inline-block;
position:relative;
}
content a{
display:inline-block;
padding:10px;
position:absolute;
bottom:10px;
right:10px;
}
This should do it:
DialogResult dialogResult = MessageBox.Show("Sure", "Some Title", MessageBoxButtons.YesNo);
if(dialogResult == DialogResult.Yes)
{
//do something
}
else if (dialogResult == DialogResult.No)
{
//do something else
}
DECLARE @FromDate DATETIME = '1992-01-2623:59:59.000',
@ToDate DATETIME = '2016-08-10 00:00:00.000',
@Years INT, @Months INT, @Days INT, @tmpFromDate DATETIME
SET @Years = DATEDIFF(YEAR, @FromDate, @ToDate)
- (CASE WHEN DATEADD(YEAR, DATEDIFF(YEAR, @FromDate, @ToDate),
@FromDate) > @ToDate THEN 1 ELSE 0 END)
SET @tmpFromDate = DATEADD(YEAR, @Years , @FromDate)
SET @Months = DATEDIFF(MONTH, @tmpFromDate, @ToDate)
- (CASE WHEN DATEADD(MONTH,DATEDIFF(MONTH, @tmpFromDate, @ToDate),
@tmpFromDate) > @ToDate THEN 1 ELSE 0 END)
SET @tmpFromDate = DATEADD(MONTH, @Months , @tmpFromDate)
SET @Days = DATEDIFF(DAY, @tmpFromDate, @ToDate)
- (CASE WHEN DATEADD(DAY, DATEDIFF(DAY, @tmpFromDate, @ToDate),
@tmpFromDate) > @ToDate THEN 1 ELSE 0 END)
SELECT @FromDate FromDate, @ToDate ToDate,
@Years Years, @Months Months, @Days Days
Use a convert function to get all entries for a particular day.
Select * from tblErrorLog where convert(date,errorDate,101) = '12/20/2008'
See CAST and CONVERT for more info
Compilating answers here and there, here's a complete set of arr tools to get the work done:
Function getArraySize(arr As Variant)
' returns array size for a n dimention array
' usage result(k) = size of the k-th dimension
Dim ndims As Long
Dim arrsize() As Variant
ndims = getDimensions(arr)
ReDim arrsize(ndims - 1)
For i = 1 To ndims
arrsize(i - 1) = getDimSize(arr, i)
Next i
getArraySize = arrsize
End Function
Function getDimSize(arr As Variant, dimension As Integer)
' returns size for the given dimension number
getDimSize = UBound(arr, dimension) - LBound(arr, dimension) + 1
End Function
Function getDimensions(arr As Variant) As Long
' returns number of dimension in an array (ex. sheet range = 2 dimensions)
On Error GoTo Err
Dim i As Long
Dim tmp As Long
i = 0
Do While True
i = i + 1
tmp = UBound(arr, i)
Loop
Err:
getDimensions = i - 1
End Function
The difference between Response.Write()
and Response.Output.Write()
in ASP.NET. The short answer is that the latter gives you String.Format-style
output and the former doesn't. The long answer follows.
In ASP.NET the Response
object is of type HttpResponse
and when you say Response.Write
you're really saying (basically) HttpContext.Current.Response.Write
and calling one of the many overloaded Write
methods of HttpResponse
.
Response.Write
then calls .Write()
on it's internal TextWriter
object:
public void Write(object obj){ this._writer.Write(obj);}
HttpResponse
also has a Property called Output
that is of type, yes, TextWriter
, so:
public TextWriter get_Output(){ return this._writer; }
Which means you can do the Response
whatever a TextWriter
will let you. Now, TextWriters support a Write()
method aka String.Format
, so you can do this:
Response.Output.Write("Scott is {0} at {1:d}", "cool",DateTime.Now);
But internally, of course, this is happening:
public virtual void Write(string format, params object[] arg)
{
this.Write(string.Format(format, arg));
}
Here's a rundown on static_cast<>
and dynamic_cast<>
specifically as they pertain to pointers. This is just a 101-level rundown, it does not cover all the intricacies.
This takes the pointer in ptr
and tries to safely cast it to a pointer of type Type*
. This cast is done at compile time. It will only perform the cast if the types are related. If the types are not related, you will get a compiler error. For example:
class B {};
class D : public B {};
class X {};
int main()
{
D* d = new D;
B* b = static_cast<B*>(d); // this works
X* x = static_cast<X*>(d); // ERROR - Won't compile
return 0;
}
This again tries to take the pointer in ptr
and safely cast it to a pointer of type Type*
. But this cast is executed at runtime, not compile time. Because this is a run-time cast, it is useful especially when combined with polymorphic classes. In fact, in certian cases the classes must be polymorphic in order for the cast to be legal.
Casts can go in one of two directions: from base to derived (B2D) or from derived to base (D2B). It's simple enough to see how D2B casts would work at runtime. Either ptr
was derived from Type
or it wasn't. In the case of D2B dynamic_cast<>s, the rules are simple. You can try to cast anything to anything else, and if ptr
was in fact derived from Type
, you'll get a Type*
pointer back from dynamic_cast
. Otherwise, you'll get a NULL pointer.
But B2D casts are a little more complicated. Consider the following code:
#include <iostream>
using namespace std;
class Base
{
public:
virtual void DoIt() = 0; // pure virtual
virtual ~Base() {};
};
class Foo : public Base
{
public:
virtual void DoIt() { cout << "Foo"; };
void FooIt() { cout << "Fooing It..."; }
};
class Bar : public Base
{
public :
virtual void DoIt() { cout << "Bar"; }
void BarIt() { cout << "baring It..."; }
};
Base* CreateRandom()
{
if( (rand()%2) == 0 )
return new Foo;
else
return new Bar;
}
int main()
{
for( int n = 0; n < 10; ++n )
{
Base* base = CreateRandom();
base->DoIt();
Bar* bar = (Bar*)base;
bar->BarIt();
}
return 0;
}
main()
can't tell what kind of object CreateRandom()
will return, so the C-style cast Bar* bar = (Bar*)base;
is decidedly not type-safe. How could you fix this? One way would be to add a function like bool AreYouABar() const = 0;
to the base class and return true
from Bar
and false
from Foo
. But there is another way: use dynamic_cast<>
:
int main()
{
for( int n = 0; n < 10; ++n )
{
Base* base = CreateRandom();
base->DoIt();
Bar* bar = dynamic_cast<Bar*>(base);
Foo* foo = dynamic_cast<Foo*>(base);
if( bar )
bar->BarIt();
if( foo )
foo->FooIt();
}
return 0;
}
The casts execute at runtime, and work by querying the object (no need to worry about how for now), asking it if it the type we're looking for. If it is, dynamic_cast<Type*>
returns a pointer; otherwise it returns NULL.
In order for this base-to-derived casting to work using dynamic_cast<>
, Base, Foo and Bar must be what the Standard calls polymorphic types. In order to be a polymorphic type, your class must have at least one virtual
function. If your classes are not polymorphic types, the base-to-derived use of dynamic_cast
will not compile. Example:
class Base {};
class Der : public Base {};
int main()
{
Base* base = new Der;
Der* der = dynamic_cast<Der*>(base); // ERROR - Won't compile
return 0;
}
Adding a virtual function to base, such as a virtual dtor, will make both Base and Der polymorphic types:
class Base
{
public:
virtual ~Base(){};
};
class Der : public Base {};
int main()
{
Base* base = new Der;
Der* der = dynamic_cast<Der*>(base); // OK
return 0;
}
Not directly answering the question but I got a similar question recently where I was asked to count the number of times a sub-string is repeated in a given string. Here is the function I wrote:
def count_substring(string, sub_string):
cnt = 0
len_ss = len(sub_string)
for i in range(len(string) - len_ss + 1):
if string[i:i+len_ss] == sub_string:
cnt += 1
return cnt
The find() function probably returns the index of the fist occurrence only. Storing the index in place of just counting, can give us the distinct set of indices the sub-string gets repeated within the string.
Disclaimer: I am 'extremly' new to Python programming.
I think you have to draw the listitems yourself to achieve this.
Here's a post with the same kind of question.
Also take a look at...
<scope>compile</scope>
Maven Dependencies. This is the default but I've found in some cases explicitly setting that scope also Maven to find local libraries in the local repository.
I couldn't find a neat way in the end so I went for create a directory called local_modules
and then added this bashscript to the package.json in scripts->preinstall
#!/bin/sh
for i in $(find ./local_modules -type d -maxdepth 1) ; do
packageJson="${i}/package.json"
if [ -f "${packageJson}" ]; then
echo "installing ${i}..."
npm install "${i}"
fi
done
when they say to write
String s = "Silly";
instead of
String s = new String("Silly");
they mean it when creating a String object because both of the above statements create a String object but the new String() version creates two String objects: one in heap and the other in string constant pool. Hence using more memory.
But when you write
CaseInsensitiveString cis = new CaseInsensitiveString("Polish");
you are not creating a String instead you are creating an object of class CaseInsensitiveString. Hence you need to use the new operator.
In my case i had copied a classlibrary, and not changed the "Assembly Name" in the project properties, so one DLL was overwriting the other...
I ran:
lsbom -f -l -s -pf /var/db/receipts/org.nodejs.pkg.bom \
| while read i; do
sudo rm /usr/local/${i}
done
sudo rm -rf /usr/local/lib/node \
/usr/local/lib/node_modules \
/var/db/receipts/org.nodejs.*
Coded into gist 2697848
Update
It seems the receipts .bom
file name may have changed so you may need to replace org.nodejs.pkg.bom
with org.nodejs.node.pkg.bom
in the above. The gist has been updated accordingly.
Why not just, a=a(~~a)
or a(~a)=[]
. It's equivalent to the other approaches but certainly less key strokes.
Try my way :
robocopy.exe "Desktop\Test folder 1" "Desktop\Test folder 2" /XD "C:\Users\Steve\Desktop\Test folder 2\XXX dont touch" /MIR
Had to put /XD
before /MIR
while including the full Destination Source directly after /XD
.
This can be done in in 3 lines of code:
// grab the window frame and adjust it for orientation
UIView *rootView = [[[UIApplication sharedApplication] keyWindow]
rootViewController].view;
CGRect originalFrame = [[UIScreen mainScreen] bounds];
CGRect adjustedFrame = [rootView convertRect:originalFrame fromView:nil];
Chosen answer (nor any of the other answers) didn't work for me, but this did:
img {outline:1px solid transparent;}
Here is how I would do it if working with a large number of "to remove" values that would take a long time to manually remove.
I program with RoR on the Mac OS with textmate, and it's awesome.
I would suggest "Programming Ruby 1.9" (The Pickaxe Book) for Ruby and Agile Web Development with Rails" to learn Rails, both published by the Pragmatic Bookshelf.
Good luck!
SELECT *
FROM myTable
WHERE URL = LEFT('mysyte.com/?id=2®ion=0&page=1', LEN(URL))
Or use CHARINDEX http://msdn.microsoft.com/en-us/library/aa258228(v=SQL.80).aspx
In .NET Core 2.2, add this line to your Program.cs:
using ...
using System.Runtime.CompilerServices;
[assembly: InternalsVisibleTo("MyAssembly.Unit.Tests")]
namespace
{
...
I am assuming you have a remote with all relevant changes already pushed to it. I did not care about local changes and simply wanted to avoid deleting and recloning a large repository. If you do have important local changes you might want to be more careful.
I had the same problem after my laptop crashed.
Probably because it was a large repository I had quite a few corrupt object files, which only appeared one at a time when calling git fsck --full
, so I wrote a small shell one-liner to automatically delete one of them:
$ sudo rm `git fsck --full 2>&1 | grep -oE -m 1 ".git/objects/[0-9a-f]{2}/[0-9a-f]*"`
2>&1
redirects the error message to stdout to be able to grep it-o
only returns the part of a line that actually matches-E
enables advanced regexes-m 1
make sure only the first match is returned[0-9a-f]{2}
matches any of the characters between 0 and 9 and a and f if two of them occur together[0-9a-f]*
matches any number of the characters between 0 and 9 and a and f occuring togetherIt still only deletes one file at a time, so you might want to call it in a loop like:
$ while true; do sudo rm `git fsck --full 2>&1 | grep -oE -m 1 ".git/objects/[0-9a-f]{2}/[0-9a-f]*"`; done
The problem with this is, that it does not output anything useful anymore so you do not know when it is finished (it should just not do anything useful after some time)
To "fix" this I then just added a call of git fsck --full
after each round like so:
$ while true; do sudo rm `git fsck --full 2>&1 | grep -oE -m 1 ".git/objects/[0-9a-f]{2}/[0-9a-f]*"`; git fsck --full; done
It now is approximately half as fast, but it does output it's "state".
After this I played around some with the suggestions in this thread and finally got to a point where I could git stash
and git stash drop
a lot of the broken stuff.
first problem solved
Afterwards I still had the following problem:
unable to resolve reference 'refs/remotes/origin/$branch': reference broken
which could be solved by
$ rm \repo.git\refs\remotes\origin\$branch
$ git fetch
I then did a
$ git gc --prune=now
$ git remote prune origin
for good measure and
git reflog expire --stale-fix --all
to get rid of error: HEAD: invalid reflog entry $blubb
when running git fsck --full
.
A static variable can get an initial value only one time. This means that if you have code such as "static int a=0
" in a sample function, and this code is executed in a first call of this function, but not executed in a subsequent call of the function; variable (a) will still have its current value (for example, a current value of 5), because the static variable gets an initial value only one time.
A constant variable has its value constant in whole of the code. For example, if you set the constant variable like "const int a=5
", then this value for "a" will be constant in whole of your program.
Doing this with simple HTML and javascript by casting the HTML element so as to avoid typescript errors
<form id="Login">
and in the component.ts file,
clearForm(){
(<HTMLFormElement>document.getElementById("Login")).reset();
}
the method clearForm()
can be called anywhere as need be.
SharePoint lists V: Techniques for managing large lists :
Tutorial By Microsoft
Level: Advanced
Length: 40 - 50 minutes
When a SharePoint list gets large, you might see warnings such as, “This list exceeds the list view threshold,” or “Displaying the newest results below.” Find out why these warnings occur, and learn ways to configure your large list so that it still provides useful information.
After completing this course you will be able to:
Part of the problem here is that the strings usually used to represent timezones are not actually unique. "EST" only means "America/New_York" to people in North America. This is a limitation in the C time API, and the Python solution is… to add full tz features in some future version any day now, if anyone is willing to write the PEP.
You can format and parse a timezone as an offset, but that loses daylight savings/summer time information (e.g., you can't distinguish "America/Phoenix" from "America/Los_Angeles" in the summer). You can format a timezone as a 3-letter abbreviation, but you can't parse it back from that.
If you want something that's fuzzy and ambiguous but usually what you want, you need a third-party library like dateutil
.
If you want something that's actually unambiguous, just append the actual tz name to the local datetime string yourself, and split it back off on the other end:
d = datetime.datetime.now(pytz.timezone("America/New_York"))
dtz_string = d.strftime(fmt) + ' ' + "America/New_York"
d_string, tz_string = dtz_string.rsplit(' ', 1)
d2 = datetime.datetime.strptime(d_string, fmt)
tz2 = pytz.timezone(tz_string)
print dtz_string
print d2.strftime(fmt) + ' ' + tz_string
Or… halfway between those two, you're already using the pytz
library, which can parse (according to some arbitrary but well-defined disambiguation rules) formats like "EST". So, if you really want to, you can leave the %Z
in on the formatting side, then pull it off and parse it with pytz.timezone()
before passing the rest to strptime
.