You should be looking for the second tr that has the td that equals ' Color Digest ', then you need to look at either the following sibling of the first td in the tr, or the second td.
Try the following:
//tr[td='Color Digest'][2]/td/following-sibling::td[1]
or
//tr[td='Color Digest'][2]/td[2]
http://www.xpathtester.com/saved/76bb0bca-1896-43b7-8312-54f924a98a89
print(link_addres.contents[0])
It will print the context of the anchor tags
example:
statement_title = statement.find('h2',class_='briefing-statement__title')
statement_title_text = statement_title.a.contents[0]
If it's okay to write down just an opinion, that's mine:
I totally and absolutely disagree with the `Single return statement theory' and find it mostly speculative and even destructive regarding the code readability, logic and descriptive aspects.
That habit of having one-single-return is even poor for bare procedural programming not to mention more high-level abstractions (functional, combinatory etc.). And furthermore, I wish all the code written in that style to go through some special rewriting parser to make it have multiple return statements!
A function (if it's really a function/query according to `Query-Command separation' note - see Eiffel programming lang. for example) just MUST define as many return points as the control flow scenarios it has. It is much more clear and mathematically consistent; and it is the way to write functions (i.e. Queries)
But I would not be so militant for the mutation messages that your agent does receive - the procedure calls.
You can use this
foreach ($array as $key => $value)
{
if($key==1)
{
$new_array[]=$other_array;
}
$new_array[]=$value;
}
All the answers above are correct. In case you want to see it in action, don't forget you have Console in a browser where you can see the actual result crystal clear :
I have an HTML :
<div id="contents"></div>
Go to console (cntrl+shift+c)
and use these commands to see your result clearly
document.getElementById('contents')
>>> div#contents
$('#contents')
>>> [div#contents,
context: document,
selector: "#contents",
jquery: "1.10.1",
constructor: function,
init: function …]
As we can see, in the first case we got the tag itself (that is, strictly speaking, an HTMLDivElement object). In the latter we actually don’t have a plain object, but an array of objects. And as mentioned by other answers above, you can use the following command:
$('#contents')[0]
>>> div#contents
Solution is very simple - Run Visual Studio Application in Admin mode !
This allow you to send an object:
private List<object> ConvertArrayToList(dynamic array)
You can get the value of a registry key as follows
@echo OFF
setlocal ENABLEEXTENSIONS
set REG_NAME="HKEY_CURRENT_USER\Software\Test"
set KEY_NAME=TestVal
FOR /F "usebackq skip=2 tokens=1-3" %%A IN (`REG QUERY %REG_NAME% /v %KEY_NAME% 2^>nul`) DO (
@echo %%A : %%C
)
pause
those who wonder how to add reg keys, here is a way.
REGEDIT4
; @ECHO OFF
; CLS
; REGEDIT.EXE /S "%~f0"
; EXIT
[HKEY_CURRENT_USER\Software\Test]
"TestVal"="Succeeded"
There is a limit, but you can split your values into separate blocks of in()
Select *
From table
Where Col IN (123,123,222,....)
or Col IN (456,878,888,....)
Assuming a simple case, where your field is public
:
List list; // from your method
for(Object x : list) {
Class<?> clazz = x.getClass();
Field field = clazz.getField("fieldName"); //Note, this can throw an exception if the field doesn't exist.
Object fieldValue = field.get(x);
}
But this is pretty ugly, and I left out all of the try-catches, and makes a number of assumptions (public field, reflection available, nice security manager).
If you can change your method to return a List<Foo>
, this becomes very easy because the iterator then can give you type information:
List<Foo> list; //From your method
for(Foo foo:list) {
Object fieldValue = foo.fieldName;
}
Or if you're consuming a Java 1.4 interface where generics aren't available, but you know the type of the objects that should be in the list...
List list;
for(Object x: list) {
if( x instanceof Foo) {
Object fieldValue = ((Foo)x).fieldName;
}
}
No reflection needed :)
For those using macOS mkfile might be a good alternative to fallocate or dd
mkfile 100m some100mfile.pdf
reference - https://stackoverflow.com/a/33478049/711401
You can simply use linq
Directory.EnumerateFiles(LoanFolder).Select(file => Path.GetFileName(file));
Note: EnumeratesFiles is more efficient compared to Directory.GetFiles as you can start enumerating the collection of names before the whole collection is returned.
The simplest way I've found to do this in Windows is with WinRAR:
I think currently your api's actually responding the way it should. The first 100 records on the page in the overall order of objects you are maintaining. Your explanation tells that you are using some kind of ordering ids to define the order of your objects for pagination.
Now, in case you want that page 2 should always start from 101 and end at 200, then you must make the number of entries on the page as variable, since they are subject to deletion.
You should do something like the below pseudocode:
page_max = 100
def get_page_results(page_no) :
start = (page_no - 1) * page_max + 1
end = page_no * page_max
return fetch_results_by_id_between(start, end)
First off, in a real application, you would never get database connection info in a servlet; you would configure it in your app server.
There are ways, however, of testing Servlets without having a container running. One is to use mock objects. Spring provides a set of very useful mocks for things like HttpServletRequest, HttpServletResponse, HttpServletSession, etc:
Using these mocks, you could test things like
What happens if username is not in the request?
What happens if username is in the request?
etc
You could then do stuff like:
import static org.junit.Assert.assertEquals;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.junit.Before;
import org.junit.Test;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
public class MyServletTest {
private MyServlet servlet;
private MockHttpServletRequest request;
private MockHttpServletResponse response;
@Before
public void setUp() {
servlet = new MyServlet();
request = new MockHttpServletRequest();
response = new MockHttpServletResponse();
}
@Test
public void correctUsernameInRequest() throws ServletException, IOException {
request.addParameter("username", "scott");
request.addParameter("password", "tiger");
servlet.doPost(request, response);
assertEquals("text/html", response.getContentType());
// ... etc
}
}
JLabel label = new JLabel("fax", SwingConstants.RIGHT);
After running "kubeinit" command, kubernetes asks you to run following as regular user
mkdir -p $HOME/.kube
sudo cp -i /etc/kubernetes/admin.conf $HOME/.kube/config
sudo chown $(id -u):$(id -g) $HOME/.kube/config
But if you run this as a regular user, you will get "The connection to the server localhost:8080 was refused - did you specify the right host or port?" when trying to access as a root user and vice versa. So try accessing "kubectl" as the user who executed the above commands.
They serve the actual image inside CSS so there will be less HTTP requests per page.
I have used following code to read "xls and xlsx" :
include 'PHPExcel/IOFactory.php';
$location='sample-excel-files.xlsx';
$objPHPExcel = PHPExcel_IOFactory::load($location);
$sheet = $objPHPExcel->getSheet(0);
$total_rows = $sheet->getHighestRow();
$total_columns = $sheet->getHighestColumn();
$set_excel_query_all=array();
for($row =2; $row <= $total_rows; $row++) {
$singlerow = $sheet->rangeToArray('A' . $row . ':' . $total_columns . $row, NULL, TRUE, FALSE);
$single_row=$singlerow[0];
$set_excel_query['store_id']=$single_row[0];
$set_excel_query['employee_uid']=$single_row[1];
$set_excel_query['opus_id']=$single_row[2];
$set_excel_query['item_description']=$single_row[3];
if($single_row[4])
{
$set_excel_query['opus_transaction_date']= date('Y-m-d', PHPExcel_Shared_Date::ExcelToPHP($single_row[4]));
}
$set_excel_query['opus_transaction_num']=$single_row[5];
$set_excel_query['opus_invoice_num']=$single_row[6];
$set_excel_query['customer_name']=$single_row[7];
$set_excel_query['mobile_num']=$single_row[8];
$set_excel_query['opus_amount']=$single_row[9];
$set_excel_query['rq4_amount']=$single_row[10];
$set_excel_query['difference']=$single_row[11];
$set_excel_query['ocomment']=$single_row[12];
$set_excel_query['mark_delete']=$single_row[13];
if($single_row[14])
{
$set_excel_query['upload_date']= date('Y-m-d', PHPExcel_Shared_Date::ExcelToPHP($single_row[14]));
}
$set_excel_query_all[]=$set_excel_query;
}
print_r($set_excel_query_all);
I wrote with parameters that are predefined
They are not "predefined" logically, somewhere inside your code. But as arguments of SP they have no default values and are required. To avoid passing those params explicitly you have to define default values in SP definition:
Alter Procedure [Test]
@StartDate AS varchar(6) = NULL,
@EndDate AS varchar(6) = NULL
AS
...
NULLs or empty strings or something more sensible - up to you. It does not matter since you are overwriting values of those arguments in the first lines of SP.
Now you can call it without passing any arguments e.g.
exec dbo.TEST
You need to set the scope of the dependency to 'provided' in your POM.
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.4</version>
<scope>provided</scope>
</dependency>
Then everything will be fine.
I set the opacity to 0. This made it disappear but still function when you click on it.
You can do some tricks like that:
<style>
@page {
size: 21cm 29.7cm;
size: landscape
/*margin: 30mm 45mm 30mm 45mm;*/
}
.whater{
opacity: 0.05;
height: 100%;
width: 100%;
position: absolute;
z-index: 9999;
}
</style>
In body tag:
<img src="YOUR IMAGE URL" class="whater"/>
'Effectively final' is a variable which would not give compiler error if it were to be appended by 'final'
From a article by 'Brian Goetz',
Informally, a local variable is effectively final if its initial value is never changed -- in other words, declaring it final would not cause a compilation failure.
char * const a;
*a
is writable, but a
is not; in other words, you can modify the value pointed to by a
, but you cannot modify a
itself. a
is a constant pointer to char
.
const char * a;
a
is writable, but *a
is not; in other words, you can modify a
(pointing it to a new location), but you cannot modify the value pointed to by a
.
Note that this is identical to
char const * a;
In this case, a
is a pointer to a const char
.
Trying to run cleanup while your files are open gave me problems. as soon as I closed my application (Visual studio) I ran clean up and it was successful
In a Linux server, using default implementation of ses
will expect files in .aws/credentials
file. You can put following content in credential file at the location below and it will work. /home/local/<your service account>/.aws/credentials
.
[default]
aws_access_key_id=<your access key>
aws_secret_access_key=<your secret access key>
I've been using Bitvise SSH Server and it's really great. From install to administration it does it all through a GUI so you won't be putting together a sshd_config file. Plus if you use their client, Tunnelier, you get some bonus features (like mapping shares, port forwarding setup up server side, etc.) If you don't use their client it will still work with the Open Source SSH clients.
It's not Open Source and it costs $39.95, but I think it's worth it.
UPDATE 2009-05-21 11:10: The pricing has changed. The current price is $99.95 per install for commercial, but now free for non-commercial/personal use. Here is the current pricing.
public View recentView;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Create a relative layout and add a button
relativeLayout = new RelativeLayout(this);
btn = new Button(this);
btn.setId((int)System.currentTimeMillis());
recentView = btn;
btn.setText("Click me");
relativeLayout.addView(btn);
setContentView(relativeLayout);
btn.setOnClickListener(new View.OnClickListener() {
@Overr ide
public void onClick(View view) {
//Create a textView, set a random ID and position it below the most recently added view
textView = new TextView(ActivityName.this);
textView.setId((int)System.currentTimeMillis());
layoutParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
layoutParams.addRule(RelativeLayout.BELOW, recentView.getId());
textView.setText("Time: "+System.currentTimeMillis());
relativeLayout.addView(textView, layoutParams);
recentView = textView;
}
});
}
This can be modified to display each element of a String array in different TextViews.
First you need to download the latest support repository (17 by the time I write this) from internal SDK manager of Android Studio or from the stand alone SDK manager. Then you can add compile 'com.android.support:appcompat-v7:23.0.0'
or any other support library you want to your build.gradle file. (Don't forget the last .0
)
CodeLens is not available in the Community editions. You need Professional or higher to switch it on.
In VS2015, one way to "get" CodeLens was to install the SQL Server Developer Tools (SSDT) but I believe this has been rectified in VS2017.
Still you can get all method reference by right clicking on the method and "Find All references"
You need the javax.mail.jar
library.
Download it from the Java EE JavaMail GitHub page and add it to your IntelliJ project:
javax.mail.jar
File > Project Structure...
+
button (Add New Project Library)javax.mail.jar
fileMost of the time you can't - depending on the host. You can contact the support team where your hosting is subscribed to, and if they confirmed that it is really not allowed, you can just set up the composer on your dev machine, and commit and push all dependencies to your live server using Git or whatever you prefer.
If you don't want something complicated, then:
import warnings
warnings.filterwarnings("ignore", category=FutureWarning)
You should add next permission:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
And then here is usages in code:
val externalFilesDir = context.getExternalFilesDir(DIRECTORY_DOWNLOADS)
Apply the (soft) shadow on the view's layer, like this:
UILabel *label = [[UIabel alloc] init];
label.layer.shadowColor = [[UIColor whiteColor] CGColor];
label.layer.shadowOpacity = 1.0;
You should add then
function to instance. Promise
will recognize it as a thenable object with Promise.resolve
automatically
const asyncSymbol = Symbol();
class MyClass {
constructor() {
this.asyncData = null
}
then(resolve, reject) {
return (this[asyncSymbol] = this[asyncSymbol] || new Promise((innerResolve, innerReject) => {
this.asyncData = { a: 1 }
setTimeout(() => innerResolve(this.asyncData), 3000)
})).then(resolve, reject)
}
}
async function wait() {
const asyncData = await new MyClass();
alert('run 3s later')
alert(asyncData.a)
}
You just need to add an "A" record in the DNS manager on Godaddy. In that "A" record put your IP from dreamhost.
I know this works since I'm doing the very same thing.
One possibility which has not been mentioned so far is that you might not be editing the file you think you are. i.e. your editor might have a different cwd than you had in mind.
Run 'more' on the file you're compiling to double check that it does indeed have the contents you hope it does. Hope that helps!
Strong: Basically Used With Properties we used to get or send data from/into another classes. Weak: Usually all outlets, connections are of Weak type from Interface.
Nonatomic: Such type of properties are used in conditions when we don't want to share our outlet or object into different simultaneous Threads. In other words, Nonatomic instance make our properties to deal with one thread at a time. Hopefully it helpful for you.
This is also an option:
x==2 && dosomething();
dosomething()
will only be called if x==2
is evaluated to true. This is called Short-circuiting.
It is not commonly used in cases like this and you really shouldn't write code like this. I encourage this simpler approach:
if(x==2) dosomething();
You should write readable code at all times; if you are worried about file size, just create a minified version of it with help of one of the many JS compressors. (e.g Google's Closure Compiler)
%d
--> for int
%u
--> for unsigned int
%ld
--> for long int
or long
%lu
--> for unsigned long int
or long unsigned int
or unsigned long
%lld
--> for long long int
or long long
%llu
--> for unsigned long long int
or unsigned long long
<input type="text" value="Your value">
Use the value
attribute for the pre filled in values.
Add both http and https configuration:
export JAVA_OPTS="$JAVA_OPTS -Dhttp.proxyHost=yourserver -Dhttp.proxyPort=8080 -Dhttp.proxyUser=username -Dhttp.proxyPassword=password"
export JAVA_OPTS="$JAVA_OPTS -Dhttps.proxyHost=yourserver -Dhttps.proxyPort=8080 -Dhttps.proxyUser=username -Dhttps.proxyPassword=password"
(https config is must, since many urls referred by the sbt libraries are https)
In fact, I even had an extra setting 'http.proxySet'
to 'true'
in both configuration entries.
Simple answer is here:
<div style="text-align: right;">
anything:
<select id="locality-dropdown" name="locality" class="cls" style="width: 200px; height: 28px; overflow:auto;">
</select>
</div>
Steps to convert .py to .exe in Python 3.6
pip install cx_Freeze
.pip install idna
..py
program named myfirstprog.py
.setup.py
on the current directory of your script.setup.py
file, copy the code below and save it.python setup.py build
build
. It has another folder in it. Within that folder you can find your application. Run it. Make yourself happy.See the original script in my blog.
setup.py:
from cx_Freeze import setup, Executable
base = None
executables = [Executable("myfirstprog.py", base=base)]
packages = ["idna"]
options = {
'build_exe': {
'packages':packages,
},
}
setup(
name = "<any name>",
options = options,
version = "<any number>",
description = '<any description>',
executables = executables
)
EDIT:
myfirstprog.py
you should put your .py
extension file name as created in step 4;import
ed package in your .py
into packages
list (ex: packages = ["idna", "os","sys"]
)any name, any number, any description
in setup.py
file should not remain the same, you should change it accordingly (ex:name = "<first_ever>", version = "0.11", description = ''
)import
ed packages must be installed before you start step 8.You'll need to compile it using:
g++ inputfile.cpp -o outputbinary
The file you are referring has a missing #include <cstdlib>
directive, if you also include that in your file, everything shall compile fine.
When you're working with strings in PHP you'll need to pay special attention to the formation, using "
or '
$string = 'Hello, world!';
$string = "Hello, world!";
Both of these are valid, the following is not:
$string = "Hello, world';
You must also note that '
inside of a literal started with "
will not end the string, and vice versa. So when you have a string which contains '
, it is generally best practice to use double quotation marks.
$string = "It's ok here";
Escaping the string is also an option
$string = 'It\'s ok here too';
More information on this can be found within the documentation
I ran across this post today as I was running into the same issue and had the same problem of the javascript not running with the CDATA tags listed above. I corrected the CDATA tags to look like:
<script type="text/javascript">
//<![CDATA[
your javascript code here
//]]>
</script>
Then everything worked perfectly!
I think (I'm not certain) that foreign key constraints won't do precisely what you want given your table design. Perhaps the best thing to do is to define a stored procedure that will delete a category the way you want, and then call that procedure whenever you want to delete a category.
CREATE PROCEDURE `DeleteCategory` (IN category_ID INT)
LANGUAGE SQL
NOT DETERMINISTIC
MODIFIES SQL DATA
SQL SECURITY DEFINER
BEGIN
DELETE FROM
`products`
WHERE
`id` IN (
SELECT `products_id`
FROM `categories_products`
WHERE `categories_id` = category_ID
)
;
DELETE FROM `categories`
WHERE `id` = category_ID;
END
You also need to add the following foreign key constraints to the linking table:
ALTER TABLE `categories_products` ADD
CONSTRAINT `Constr_categoriesproducts_categories_fk`
FOREIGN KEY `categories_fk` (`categories_id`) REFERENCES `categories` (`id`)
ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `Constr_categoriesproducts_products_fk`
FOREIGN KEY `products_fk` (`products_id`) REFERENCES `products` (`id`)
ON DELETE CASCADE ON UPDATE CASCADE
The CONSTRAINT clause can, of course, also appear in the CREATE TABLE statement.
Having created these schema objects, you can delete a category and get the behaviour you want by issuing CALL DeleteCategory(category_ID)
(where category_ID is the category to be deleted), and it will behave how you want. But don't issue a normal DELETE FROM
query, unless you want more standard behaviour (i.e. delete from the linking table only, and leave the products
table alone).
You can use this, it works fine:
<input type="date" class="form1"
value="{{date | date:MM/dd/yyyy}}"
ng-model="date"
name="id"
validatedateformat
data-date-format="mm/dd/yyyy"
maxlength="10"
id="id"
calendar
maxdate="todays"
ng-click="openCalendar('id')">
<span class="input-group-addon">
<span class="glyphicon glyphicon-calendar" ng-click="openCalendar('id')"></span>
</span>
</input>
If you're trying to query an Oracle database, you might want to use
select owner, table_name
from all_tab_columns
where column_name = 'ColName';
Like ?egDwight said, you can use the HTML entity &infin
; or ∞
. A easy source of getting these codes, is to look at this entity list.
You can also use them in CSS, which was what I was looking for, just like font-awesome does. A simple CSS based solution would be to have something like:
.infinity-ico:before {
content: '\221E';
}
I use this function in all my js projects
You call it: hideAndResetModals("#IdModalDialog")
You define if:
function hideAndResetModals(modalID)
{
$(modalID).modal('hide');
clearValidation(modalID); //You implement it if you need it. If not, you can remote this line
$(modalID).on('hidden.bs.modal', function ()
{
$(modalID).find('form').trigger('reset');
});
}
Two Answers
1. Answer to the asked question.
2. A simple change equals a better way!
Answer 1 - Pass the Vars Array to the __construct() in a class, you could also leave the construct empty and pass the Arrays through your functions instead.
<?php
// Create an Array with all needed Sub Arrays Example:
// Example Sub Array 1
$content_arrays["modals"]= array();
// Example Sub Array 2
$content_arrays["js_custom"] = array();
// Create a Class
class Array_Pushing_Example_1 {
// Public to access outside of class
public $content_arrays;
// Needed in the class only
private $push_value_1;
private $push_value_2;
private $push_value_3;
private $push_value_4;
private $values;
private $external_values;
// Primary Contents Array as Parameter in __construct
public function __construct($content_arrays){
// Declare it
$this->content_arrays = $content_arrays;
}
// Push Values from in the Array using Public Function
public function array_push_1(){
// Values
$this->push_values_1 = array(1,"2B or not 2B",3,"42",5);
$this->push_values_2 = array("a","b","c");
// Loop Values and Push Values to Sub Array
foreach($this->push_values_1 as $this->values){
$this->content_arrays["js_custom"][] = $this->values;
}
// Loop Values and Push Values to Sub Array
foreach($this->push_values_2 as $this->values){
$this->content_arrays["modals"][] = $this->values;
}
// Return Primary Array with New Values
return $this->content_arrays;
}
// GET Push Values External to the Class with Public Function
public function array_push_2($external_values){
$this->push_values_3 = $external_values["values_1"];
$this->push_values_4 = $external_values["values_2"];
// Loop Values and Push Values to Sub Array
foreach($this->push_values_3 as $this->values){
$this->content_arrays["js_custom"][] = $this->values;
}
// Loop Values and Push Values to Sub Array
foreach($this->push_values_4 as $this->values){
$this->content_arrays["modals"][] = $this->values;
}
// Return Primary Array with New Values
return $this->content_arrays;
}
}
// Start the Class with the Contents Array as a Parameter
$content_arrays = new Array_Pushing_Example_1($content_arrays);
// Push Internal Values to the Arrays
$content_arrays->content_arrays = $content_arrays->array_push_1();
// Push External Values to the Arrays
$external_values = array();
$external_values["values_1"] = array("car","house","bike","glass");
$external_values["values_2"] = array("FOO","foo");
$content_arrays->content_arrays = $content_arrays->array_push_2($external_values);
// The Output
echo "Array Custom Content Results 1";
echo "<br>";
echo "<br>";
echo "Modals - Count: ".count($content_arrays->content_arrays["modals"]);
echo "<br>";
echo "-------------------";
echo "<br>";
// Get Modals Array Results
foreach($content_arrays->content_arrays["modals"] as $modals){
echo $modals;
echo "<br>";
}
echo "<br>";
echo "JS Custom - Count: ".count($content_arrays->content_arrays["js_custom"]);
echo "<br>";
echo "-------------------";
echo "<br>";
// Get JS Custom Array Results
foreach($content_arrays->content_arrays["js_custom"] as $js_custom){
echo $js_custom;
echo "<br>";
}
echo "<br>";
?>
Answer 2 - A simple change however would put it inline with modern standards. Just declare your Arrays in the Class.
<?php
// Create a Class
class Array_Pushing_Example_2 {
// Public to access outside of class
public $content_arrays;
// Needed in the class only
private $push_value_1;
private $push_value_2;
private $push_value_3;
private $push_value_4;
private $values;
private $external_values;
// Declare Contents Array and Sub Arrays in __construct
public function __construct(){
// Declare them
$this->content_arrays["modals"] = array();
$this->content_arrays["js_custom"] = array();
}
// Push Values from in the Array using Public Function
public function array_push_1(){
// Values
$this->push_values_1 = array(1,"2B or not 2B",3,"42",5);
$this->push_values_2 = array("a","b","c");
// Loop Values and Push Values to Sub Array
foreach($this->push_values_1 as $this->values){
$this->content_arrays["js_custom"][] = $this->values;
}
// Loop Values and Push Values to Sub Array
foreach($this->push_values_2 as $this->values){
$this->content_arrays["modals"][] = $this->values;
}
// Return Primary Array with New Values
return $this->content_arrays;
}
// GET Push Values External to the Class with Public Function
public function array_push_2($external_values){
$this->push_values_3 = $external_values["values_1"];
$this->push_values_4 = $external_values["values_2"];
// Loop Values and Push Values to Sub Array
foreach($this->push_values_3 as $this->values){
$this->content_arrays["js_custom"][] = $this->values;
}
// Loop Values and Push Values to Sub Array
foreach($this->push_values_4 as $this->values){
$this->content_arrays["modals"][] = $this->values;
}
// Return Primary Array with New Values
return $this->content_arrays;
}
}
// Start the Class without the Contents Array as a Parameter
$content_arrays = new Array_Pushing_Example_2();
// Push Internal Values to the Arrays
$content_arrays->content_arrays = $content_arrays->array_push_1();
// Push External Values to the Arrays
$external_values = array();
$external_values["values_1"] = array("car","house","bike","glass");
$external_values["values_2"] = array("FOO","foo");
$content_arrays->content_arrays = $content_arrays->array_push_2($external_values);
// The Output
echo "Array Custom Content Results 1";
echo "<br>";
echo "<br>";
echo "Modals - Count: ".count($content_arrays->content_arrays["modals"]);
echo "<br>";
echo "-------------------";
echo "<br>";
// Get Modals Array Results
foreach($content_arrays->content_arrays["modals"] as $modals){
echo $modals;
echo "<br>";
}
echo "<br>";
echo "JS Custom - Count: ".count($content_arrays->content_arrays["js_custom"]);
echo "<br>";
echo "-------------------";
echo "<br>";
// Get JS Custom Array Results
foreach($content_arrays->content_arrays["js_custom"] as $js_custom){
echo $js_custom;
echo "<br>";
}
echo "<br>";
?>
Both options output the same information and allow a function to push and retrieve information from an Array and sub Arrays to any place in the code(Given that the data has been pushed first). The second option gives more control over how the data is used and protected. They can be used as is just modify to your needs but if they were used to extend a Controller they could share their values among any of the Classes the Controller is using. Neither method requires the use of a Global(s).
Output:
Array Custom Content Results
Modals - Count: 5
a
b
c
FOO
foo
JS Custom - Count: 9
1
2B or not 2B
3
42
5
car
house
bike
glass
pids=$(pgrep <name>)
will get you the pids of all processes with the given name. To kill them all, use
kill -9 $pids
To refrain from using a variable and directly kill all processes with a given name issue
pkill -9 <name>
A bit old but just in case someone new is looking for a solution, updating your PHP version can fix the issue.
Also you should be committing your composer.lock file and doing a composer install on a production environment which is less resource intensive.
More details here: https://github.com/composer/composer/issues/1898#issuecomment-23453850
The best practice is definitely to avoid loops or recursions in Matlab.
Between sum(A(:))
and sum(sum(A))
.
In my experience, arrays in Matlab seems to be stored in a continuous block in memory as stacked column vectors. So the shape of A does not quite matter in sum()
. (One can test reshape()
and check if reshaping is fast in Matlab. If it is, then we have a reason to believe that the shape of an array is not directly related to the way the data is stored and manipulated.)
As such, there is no reason sum(sum(A))
should be faster. It would be slower if Matlab actually creates a row vector recording the sum of each column of A first and then sum over the columns. But I think sum(sum(A))
is very wide-spread amongst users. It is likely that they hard-code sum(sum(A))
to be a single loop, the same to sum(A(:))
.
Below I offer some testing results. In each test, A=rand(size) and size is specified in the displayed texts.
First is using tic toc.
Size 100x100
sum(A(:))
Elapsed time is 0.000025 seconds.
sum(sum(A))
Elapsed time is 0.000018 seconds.
Size 10000x1
sum(A(:))
Elapsed time is 0.000014 seconds.
sum(A)
Elapsed time is 0.000013 seconds.
Size 1000x1000
sum(A(:))
Elapsed time is 0.001641 seconds.
sum(A)
Elapsed time is 0.001561 seconds.
Size 1000000
sum(A(:))
Elapsed time is 0.002439 seconds.
sum(A)
Elapsed time is 0.001697 seconds.
Size 10000x10000
sum(A(:))
Elapsed time is 0.148504 seconds.
sum(A)
Elapsed time is 0.155160 seconds.
Size 100000000
Error using rand
Out of memory. Type HELP MEMORY for your options.
Error in test27 (line 70)
A=rand(100000000,1);
Below is using cputime
Size 100x100
The cputime for sum(A(:)) in seconds is
0
The cputime for sum(sum(A)) in seconds is
0
Size 10000x1
The cputime for sum(A(:)) in seconds is
0
The cputime for sum(sum(A)) in seconds is
0
Size 1000x1000
The cputime for sum(A(:)) in seconds is
0
The cputime for sum(sum(A)) in seconds is
0
Size 1000000
The cputime for sum(A(:)) in seconds is
0
The cputime for sum(sum(A)) in seconds is
0
Size 10000x10000
The cputime for sum(A(:)) in seconds is
0.312
The cputime for sum(sum(A)) in seconds is
0.312
Size 100000000
Error using rand
Out of memory. Type HELP MEMORY for your options.
Error in test27_2 (line 70)
A=rand(100000000,1);
In my experience, both timers are only meaningful up to .1s. So if you have similar experience with Matlab timers, none of the tests can discern sum(A(:))
and sum(sum(A))
.
I tried the largest size allowed on my computer a few more times.
Size 10000x10000
sum(A(:))
Elapsed time is 0.151256 seconds.
sum(A)
Elapsed time is 0.143937 seconds.
Size 10000x10000
sum(A(:))
Elapsed time is 0.149802 seconds.
sum(A)
Elapsed time is 0.145227 seconds.
Size 10000x10000
The cputime for sum(A(:)) in seconds is
0.2808
The cputime for sum(sum(A)) in seconds is
0.312
Size 10000x10000
The cputime for sum(A(:)) in seconds is
0.312
The cputime for sum(sum(A)) in seconds is
0.312
Size 10000x10000
The cputime for sum(A(:)) in seconds is
0.312
The cputime for sum(sum(A)) in seconds is
0.312
They seem equivalent.
Either one is good. But sum(sum(A))
requires that you know the dimension of your array is 2.
I think you can use REGEXP instead of LIKE
SELECT trecord FROM `tbl` WHERE (trecord REGEXP '^ALA[0-9]')
This looks like a homework question, so I'll just give you a few pointers:
Try to give good distinctive variable names. Here you used "fileName" first for the directory, and then for the file. That is confusing, and won't help you solve the problem. Use different names for different things.
You're not using Scanner for anything, and it's not needed here, get rid of it.
Furthermore, the accept method should return a boolean value. Right now, you are trying to return a String. Boolean means that it should either return true or false. For example return a > 0;
may return true or false, depending on the value of a. But return fileName;
will just return the value of fileName, which is a String.
What is the style item to make it disappear?
In order to remove the shadow add this to your app theme:
<style name="MyAppTheme" parent="android:Theme.Holo.Light">
<item name="android:windowContentOverlay">@null</item>
</style>
UPDATE:
As @Quinny898 stated, on Android 5.0 this has changed, you have to call setElevation(0)
on your action bar. Note that if you're using the support library you must call it to that like so:
getSupportActionBar().setElevation(0);
I use os.system
import os
os.system("pdftoppm -png {} {}".format(path2pdf, os.path.join(tmpdirname, "temp")))
You can read here about the behaviour of attributes in many different browsers, including IE.
element.setAttribute()
should do the trick, even in IE. Did you try it? If it doesn't work, then maybe
element.attributeName = 'value'
might work.
Answer is indeed the one provided by zerkms, as stated on Option 1:
Option 1: which does not risk damage to data integrity:
- Remove constraints
- Perform TRUNCATE
- Delete manually the rows that now have references to nowhere
- Create constraints
The tricky part is Removing constraints, so I want to tell you how, in case someone needs to know how to do that:
Run SHOW CREATE TABLE <Table Name>
query to see what is your FOREIGN KEY's name (Red frame in below image):
Run ALTER TABLE <Table Name> DROP FOREIGN KEY <Foreign Key Name>
. This will remove the foreign key constraint.
Drop the associated Index (through table structure page), and you are done.
to re-create foreign keys:
ALTER TABLE <Table Name>
ADD FOREIGN KEY (<Field Name>) REFERENCES <Foreign Table Name>(<Field Name>);
commit your code using
git commit -m "first commit"
then config your mail id using
git config user.email "[email protected]"
this is work for me
Transaction can be defined as a collection of task that are considered as minimum processing unit. Each minimum processing unit can not be divided further.
The main operation of a transaction are read and write.
All transaction must contain four properties that commonly known as ACID properties for the purpose of ensuring accuracy , completeness and data integrity.
Add to VM options: -Dspring.profiles.active=dev
Or you can add it to the build.gradle file to make it work: bootRun.systemProperties = System.properties.
I can now successfully retrieve the version of an APK file from its binary XML data.
This topic is where I got the key to my answer (I also added my version of Ribo's code): How to parse the AndroidManifest.xml file inside an .apk package
Additionally, here's the XML parsing code I wrote, specifically to fetch the version:
XML Parsing
/**
* Verifies at Conductor APK path if package version if newer
*
* @return True if package found is newer, false otherwise
*/
public static boolean checkIsNewVersion(String conductorApkPath) {
boolean newVersionExists = false;
// Decompress found APK's Manifest XML
// Source: https://stackoverflow.com/questions/2097813/how-to-parse-the-androidmanifest-xml-file-inside-an-apk-package/4761689#4761689
try {
if ((new File(conductorApkPath).exists())) {
JarFile jf = new JarFile(conductorApkPath);
InputStream is = jf.getInputStream(jf.getEntry("AndroidManifest.xml"));
byte[] xml = new byte[is.available()];
int br = is.read(xml);
//Tree tr = TrunkFactory.newTree();
String xmlResult = SystemPackageTools.decompressXML(xml);
//prt("XML\n"+tr.list());
if (!xmlResult.isEmpty()) {
InputStream in = new ByteArrayInputStream(xmlResult.getBytes());
// Source: http://developer.android.com/training/basics/network-ops/xml.html
XmlPullParser parser = Xml.newPullParser();
parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
parser.setInput(in, null);
parser.nextTag();
String name = parser.getName();
if (name.equalsIgnoreCase("Manifest")) {
String pakVersion = parser.getAttributeValue(null, "versionName");
//NOTE: This is specific to my project. Replace with whatever is relevant on your side to fetch your project's version
String curVersion = SharedData.getPlayerVersion();
int isNewer = SystemPackageTools.compareVersions(pakVersion, curVersion);
newVersionExists = (isNewer == 1);
}
}
}
} catch (Exception ex) {
android.util.Log.e(TAG, "getIntents, ex: "+ex);
ex.printStackTrace();
}
return newVersionExists;
}
Version Comparison (seen as SystemPackageTools.compareVersions in previous snippet) NOTE: This code is inspired from the following topic: Efficient way to compare version strings in Java
/**
* Compare 2 version strings and tell if the first is higher, equal or lower
* Source: https://stackoverflow.com/questions/6701948/efficient-way-to-compare-version-strings-in-java
*
* @param ver1 Reference version
* @param ver2 Comparison version
*
* @return 1 if ver1 is higher, 0 if equal, -1 if ver1 is lower
*/
public static final int compareVersions(String ver1, String ver2) {
String[] vals1 = ver1.split("\\.");
String[] vals2 = ver2.split("\\.");
int i=0;
while(i<vals1.length&&i<vals2.length&&vals1[i].equals(vals2[i])) {
i++;
}
if (i<vals1.length&&i<vals2.length) {
int diff = Integer.valueOf(vals1[i]).compareTo(Integer.valueOf(vals2[i]));
return diff<0?-1:diff==0?0:1;
}
return vals1.length<vals2.length?-1:vals1.length==vals2.length?0:1;
}
I hope this helps.
For above query apply below css for a
animation-iteration-count: 1
There is very little overall difference between GCC 4.8 and clang 3.3 in terms of speed of the resulting binary. In most cases code generated by both compilers performs similarly. Neither of these two compilers dominates the other one.
Benchmarks telling that there is a significant performance gap between GCC and clang are coincidental.
Program performance is affected by the choice of the compiler. If a developer or a group of developers is exclusively using GCC then the program can be expected to run slightly faster with GCC than with clang, and vice versa.
From developer viewpoint, a notable difference between GCC 4.8+ and clang 3.3 is that GCC has the -Og
command line option. This option enables optimizations that do not interfere with debugging, so for example it is always possible to get accurate stack traces. The absence of this option in clang makes clang harder to use as an optimizing compiler for some developers.
In my case it was POST submission of a json to be processed and get a return value. I cross checked logs of my app server with and without nginx. What i got was my location was not getting appended to proxy_pass url and the version of HTTP protocol version is different.
My earlier location block was
location /xxQuery {
proxy_method POST;
proxy_pass http://127.0.0.1:xx00/;
client_max_body_size 10M;
}
I changed it to
location /xxQuery {
proxy_method POST;
proxy_http_version 1.1;
proxy_pass http://127.0.0.1:xx00/xxQuery;
client_max_body_size 10M;
}
It worked.
If checked:
$( "SELECTOR" ).attr( "checked" ) // Returns ‘true’ if present on the element, returns undefined if not present
$( "SELECTOR" ).prop( "checked" ) // Returns true if checked, false if unchecked.
$( "SELECTOR" ).is( ":checked" ) // Returns true if checked, false if unchecked.
Get the checked val:
$( "SELECTOR:checked" ).val()
Get the checked val numbers:
$( "SELECTOR:checked" ).length
Check or uncheck checkbox
$( "SELECTOR" ).prop( "disabled", false );
$( "SELECTOR" ).prop( "checked", true );
there is the class I mentioned in the comment we had with Sean Patrick Floyd : I did it with a peculiar use which needs WeakReference, but you can change it by any object with ease.
Hoping this can help someone someday :)
import java.lang.ref.WeakReference;
import java.util.LinkedList;
import java.util.NoSuchElementException;
import java.util.Queue;
/**
*
* @author leBenj
*/
public class Array2DWeakRefsBuffered<T>
{
private final WeakReference<T>[][] _array;
private final Queue<T> _buffer;
private final int _width;
private final int _height;
private final int _bufferSize;
@SuppressWarnings( "unchecked" )
public Array2DWeakRefsBuffered( int w , int h , int bufferSize )
{
_width = w;
_height = h;
_bufferSize = bufferSize;
_array = new WeakReference[_width][_height];
_buffer = new LinkedList<T>();
}
/**
* Tests the existence of the encapsulated object
* /!\ This DOES NOT ensure that the object will be available on next call !
* @param x
* @param y
* @return
* @throws IndexOutOfBoundsException
*/public boolean exists( int x , int y ) throws IndexOutOfBoundsException
{
if( x >= _width || x < 0 )
{
throw new IndexOutOfBoundsException( "Index out of bounds (get) : [ x = " + x + "]" );
}
if( y >= _height || y < 0 )
{
throw new IndexOutOfBoundsException( "Index out of bounds (get) : [ y = " + y + "]" );
}
if( _array[x][y] != null )
{
T elem = _array[x][y].get();
if( elem != null )
{
return true;
}
}
return false;
}
/**
* Gets the encapsulated object
* @param x
* @param y
* @return
* @throws IndexOutOfBoundsException
* @throws NoSuchElementException
*/
public T get( int x , int y ) throws IndexOutOfBoundsException , NoSuchElementException
{
T retour = null;
if( x >= _width || x < 0 )
{
throw new IndexOutOfBoundsException( "Index out of bounds (get) : [ x = " + x + "]" );
}
if( y >= _height || y < 0 )
{
throw new IndexOutOfBoundsException( "Index out of bounds (get) : [ y = " + y + "]" );
}
if( _array[x][y] != null )
{
retour = _array[x][y].get();
if( retour == null )
{
throw new NoSuchElementException( "Dereferenced WeakReference element at [ " + x + " ; " + y + "]" );
}
}
else
{
throw new NoSuchElementException( "No WeakReference element at [ " + x + " ; " + y + "]" );
}
return retour;
}
/**
* Add/replace an object
* @param o
* @param x
* @param y
* @throws IndexOutOfBoundsException
*/
public void set( T o , int x , int y ) throws IndexOutOfBoundsException
{
if( x >= _width || x < 0 )
{
throw new IndexOutOfBoundsException( "Index out of bounds (set) : [ x = " + x + "]" );
}
if( y >= _height || y < 0 )
{
throw new IndexOutOfBoundsException( "Index out of bounds (set) : [ y = " + y + "]" );
}
_array[x][y] = new WeakReference<T>( o );
// store local "visible" references : avoids deletion, works in FIFO mode
_buffer.add( o );
if(_buffer.size() > _bufferSize)
{
_buffer.poll();
}
}
}
Example of how to use it :
// a 5x5 array, with at most 10 elements "bufferized" -> the last 10 elements will not be taken by GC process
Array2DWeakRefsBuffered<Image> myArray = new Array2DWeakRefsBuffered<Image>(5,5,10);
Image img = myArray.set(anImage,0,0);
if(myArray.exists(3,3))
{
System.out.println("Image at 3,3 is still in memory");
}
A good approach is to have a common base class for all your entities. In this base class, you can have your id property if it is commonly named in all your entities (a common design), your creation and last update date properties.
For the creation date, you simply keep a java.util.Date property. Be sure, to always initialize it with new Date().
For the last update field, you can use a Timestamp property, you need to map it with @Version. With this Annotation the property will get updated automatically by Hibernate. Beware that Hibernate will also apply optimistic locking (it's a good thing).
@user755806 I do not believe that your question was answered. I took your code but used the 'foo' example string, added a lower function and also found the length of the hash returned. In sqlplus or Oracle's sql developer Java database client you can use this to call the md5sum of a value. The column formats clean up the presentation.
column hash_key format a34;
column hash_key_len format 999999;
select dbms_obfuscation_toolkit.md5(
input => UTL_RAW.cast_to_raw('foo')) as hash_key,
length(dbms_obfuscation_toolkit.md5(
input => UTL_RAW.cast_to_raw('foo'))) as hash_key_len
from dual;
The result set
HASH_KEY HASH_KEY_LEN
---------------------------------- ------------
acbd18db4cc2f85cedef654fccc4a4d8 32
is the same value that is returned from a Linux md5sum command.
echo -n foo | md5sum
acbd18db4cc2f85cedef654fccc4a4d8 -
WARNING: This solution has security risks.
Try running the container as privileged:
sudo docker run --privileged=true -i -v /data1/Downloads:/Downloads ubuntu bash
Another option (that I have not tried) would be to create a privileged container and then create non-privileged containers inside of it.
Simple one, add before Main
[DllImport("USER32.DLL", CharSet = CharSet.Unicode)]
public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
[DllImport("USER32.DLL")]
public static extern bool SetForegroundWindow(IntPtr hWnd);
Code inside Main/Method:
string className = "IEFrame";
string windowName = "New Tab - Windows Internet Explorer";
IntPtr IE = FindWindow(className, windowName);
if (IE == IntPtr.Zero)
{
return;
}
SetForegroundWindow(IE);
InputSimulator.SimulateKeyPress(VirtualKeyCode.F5);
Note:
Add InputSimulator as reference. To download Click here
To find Class & Window name, use WinSpy++. To download Click here
If you can change the order of the elements:
int[] myArray = new int[]{1, 3, 8, 5, 7, };
Arrays.sort(myArray);
int max = myArray[myArray.length - 1];
If you can't change the order of the elements:
int[] myArray = new int[]{1, 3, 8, 5, 7, };
int max = Integer.MIN_VALUE;
for(int i = 0; i < myArray.length; i++) {
if(myArray[i] > max) {
max = myArray[i];
}
}
The above answers require you to malloc a new stream object.
public <T>
boolean containsByLambda(Collection<? extends T> c, Predicate<? super T> p) {
for (final T z : c) {
if (p.test(z)) {
return true;
}
}
return false;
}
public boolean containsTabById(TabPane tabPane, String id) {
return containsByLambda(tabPane.getTabs(), z -> z.getId().equals(id));
}
...
if (containsTabById(tabPane, idToCheck))) {
...
}
Here's a pure CSS solution, similar to DarkBee's answer, but without the need for an extra .wrapper
div:
.dimmed {
position: relative;
}
.dimmed:after {
content: " ";
z-index: 10;
display: block;
position: absolute;
height: 100%;
top: 0;
left: 0;
right: 0;
background: rgba(0, 0, 0, 0.5);
}
I'm using rgba here, but of course you can use other transparency methods if you like.
You could solve this with some simple gazpacho parsing:
from gazpacho import Soup
soup = Soup(html)
tds = soup.find("td", {"class": "pos"})
tds[1].find("strong").text
Which will output:
text I am looking for
'SET' is forgotten
ALTER TABLE ONLY users ALTER COLUMN lang SET DEFAULT 'en_GB';
AFAIK all you can do is omit the returns to make things more compact in C++:
switch(Answer)
{
case 1: case 2: case 3: case 4:
cout << "You need more cars.";
break;
...
}
(You could remove the other returns as well, of course.)
This is a tricky subject. In the end, if you invoke pip
it will invoke either pip2
or pip3
, depending on how you set your system up.
here is updated code of the redim preseve method with variabel declaration, hope @Control Freak is fine with it:)
Option explicit
'redim preserve both dimensions for a multidimension array *ONLY
Public Function ReDimPreserve(aArrayToPreserve As Variant, nNewFirstUBound As Variant, nNewLastUBound As Variant) As Variant
Dim nFirst As Long
Dim nLast As Long
Dim nOldFirstUBound As Long
Dim nOldLastUBound As Long
ReDimPreserve = False
'check if its in array first
If IsArray(aArrayToPreserve) Then
'create new array
ReDim aPreservedArray(nNewFirstUBound, nNewLastUBound)
'get old lBound/uBound
nOldFirstUBound = UBound(aArrayToPreserve, 1)
nOldLastUBound = UBound(aArrayToPreserve, 2)
'loop through first
For nFirst = LBound(aArrayToPreserve, 1) To nNewFirstUBound
For nLast = LBound(aArrayToPreserve, 2) To nNewLastUBound
'if its in range, then append to new array the same way
If nOldFirstUBound >= nFirst And nOldLastUBound >= nLast Then
aPreservedArray(nFirst, nLast) = aArrayToPreserve(nFirst, nLast)
End If
Next
Next
'return the array redimmed
If IsArray(aPreservedArray) Then ReDimPreserve = aPreservedArray
End If
End Function
You can use the following code
name ='mypic'
plt.savefig('path_to_file/{}'.format(name))
If you want to save in same folder where your code lies,ignore the path_to_file and just format with name. If you have folder name 'Images' in the just one level outside of your python script, you can use,
name ='mypic'
plt.savefig('Images/{}'.format(name))
The default file type in saving is '.png' file format. If you want to save in loop, then you can use the unique name for each file such as counter of the for loop. If i is the counter,
plt.savefig('Images/{}'.format(i))
Hope this helps.
For me the inclusion of "Require local" helped to solve Error 403. The alias config file looks like this:
Alias /mytest/ "C:/mytest/"
<Directory "C:/mytest/">
Options Indexes FollowSymLinks MultiViews
AllowOverride all
Order allow,deny
Allow from all
Require local
</Directory>
[TestMethod]
public void BraceEscapingTest()
{
var result = String.Format("Foo {{0}}", "1,2,3"); //"1,2,3" is not parsed
Assert.AreEqual("Foo {0}", result);
result = String.Format("Foo {{{0}}}", "1,2,3");
Assert.AreEqual("Foo {1,2,3}", result);
result = String.Format("Foo {0} {{bar}}", "1,2,3");
Assert.AreEqual("Foo 1,2,3 {bar}", result);
result = String.Format("{{{0:N}}}", 24); //24 is not parsed, see @Guru Kara answer
Assert.AreEqual("{N}", result);
result = String.Format("{0}{1:N}{2}", "{", 24, "}");
Assert.AreEqual("{24.00}", result);
result = String.Format("{{{0}}}", 24.ToString("N"));
Assert.AreEqual("{24.00}", result);
}
This is very short, very clear, but gives my sensibilities the creeping horrors. It's also a bit awkward to adapt to different delimiters, especially if a String (not char).
for (Item i : list)
sb.append(',').append(i);
if (sb.charAt(0)==',') sb.deleteCharAt(0);
Inspired by: Last iteration of enhanced for loop in java
Nowadays (2016) in Chrome Dev Tools console, you can quickly execute this function below to show all event listeners that have been attached to an element.
getEventListeners(document.querySelector('your-element-selector'));
Ugh- nothing worked for me! I have a CentOS 7.4 machine running mariadb 5.5.64.
What I had to do was this, right after installation of mariadb from yum;
# systemctl restart mariadb
# mysql_secure_installation
The mysql_secure_installation
will take you through a number of steps, including "Set root password? [Y/n]". Just say "y" and give it a password. Answer the other questions as you wish.
Then you can get in with your password, using
# mysql -u root -p
It will survive
# systemctl restart mariadb
The Key
Then, I checked the /bin/mysql_secure_installation
source code to find out how it was magically able to change the root password and none of the other answers here could. The import bit is:
do_query "UPDATE mysql.user SET Password=PASSWORD('$esc_pass') WHERE User='root';"
...It says SET Password=...
and not SET authentication_string = PASSWORD...
. So, the proper procedure for this version (5.5.64) is:
login using mysql -u root -p , using the password you already set.
Or, stop the database and start it with:
mysql_safe --skip-grant-tables --skip-networking &
From the mysql> prompt:
use mysql;
select host,user,password from user where user = 'root';
(observe your existing passwords for root).
UPDATE mysql.user set Password = PASSWORD('your_new_cleartext_password') where user = 'root' AND host = 'localhost';
select host,user,password from user where user = 'root';
flush privileges;
quit;
kill the running mysqld_safe. restart mariadb. Login as root: mysql -u -p
. Use your new password.
If you want, you can set all the root passwords at once. I think this is wise:
mysql -u root -p
(login)
use mysql;
select host,user,password from user where user = 'root';
UPDATE mysql.user set Password = PASSWORD('your_new_cleartext_password') where user = 'root';
select host,user,password from user where user = 'root';
flush privileges;
quit;
This will perform updates on all the root passwords: ie, for "localhost", "127.0.0.1", and "::1"
In the future, when I go to RHEL8 or what have you, I will try to remember to check the /bin/mysql_secure_installation and see how the guys did it, who were the ones that configured mariadb for this OS.
You can also do this by passing function with onclick event
<a onclick="getColor(this);" color="red">
<script type="text/javascript">
function getColor(el)
{
color = $(el).attr('color');
alert(color);
}
</script>
I had a similar problem. I had the right settings in my web.config file but was running the application pool in Classic mode rather than Integrated mode
You can use File.WriteAllBytes
I used used fadeIn animation to replace new image for old one
ObjectAnimator.ofFloat(imageView, View.ALPHA, 0.2f, 1.0f).setDuration(1000).start();
int resolution =Toolkit.getDefaultToolkit().getScreenResolution();
System.out.println(resolution);
For .NET
People :
string instanceId = new StreamReader(
HttpWebRequest.Create("http://169.254.169.254/latest/meta-data/instance-id")
.GetResponse().GetResponseStream())
.ReadToEnd();
SVN ignore
is easy to manage in TortoiseSVN. Open TortoiseSVN and right-click on file menu then select Add to ignore list.
This will add the files in the svn:ignore
property.
When we checking in the files then those file which is matched with svn:ignore
that will be ignored and will not commit.
In Visual Studio project we have added following files to ignore:
bin obj
*.exe
*.dll
*.pdb
*.suo
We are managing source code on SVN of Comparetrap using this method successfully
You can give opacity value as
div {opacity: 0.4;}
For IE
, you can specify as
div { filter:alpha(opacity=10));}
Lower the value - Higher the transparency.
NOTE: this topic is about installation issues with MS project templates.
I came here via a search in Google, I was looking for a missing Template option in Visual Studio 2017 File menu: in VS-2015, it was Export to Template and I used it to add my own standard Project Items.
Meanwhile, I found an answer.. my issue was not related to default templates and it does not need install things. The option Export to Template has been moved to the VS-2017 Project menu !
for run phpunit test in laravel by many way ..
vendor/bin/phpunit --filter methodName className pathTofile.php
vendor/bin/phpunit --filter 'namespace\\directoryName\\className::methodName'
for test single class :
vendor/bin/phpunit --filter tests/Feature/UserTest.php
vendor/bin/phpunit --filter 'Tests\\Feature\\UserTest'
vendor/bin/phpunit --filter 'UserTest'
for test single method :
vendor/bin/phpunit --filter testExample
vendor/bin/phpunit --filter 'Tests\\Feature\\UserTest::testExample'
vendor/bin/phpunit --filter testExample UserTest tests/Feature/UserTest.php
for run tests from all class within namespace :
vendor/bin/phpunit --filter 'Tests\\Feature'
for more way run test see more
Little bit late to the party but had some problems with getting something useful out from a ReadableStream
produced from a Odata $batch request using the Sharepoint Framework.
Had similar issues as OP, but the solution in my case was to use a different conversion method than .json()
. In my case .text()
worked like a charm. Some fiddling was however necessary to get some useful JSON from the textfile.
The accepted answer is not incorrect.
For grouped styles one can also use the ngStyle directive.
<some-element [ngStyle]="{'font-style': styleExpression, 'font-weight': 12}">...</some-element>
The official docs are here
C# 6.0 adds readonly auto properties
public object MyProperty { get; }
So when you don't need to support older compilers you can have a truly readonly property with code that's just as concise as a readonly field.
Versioning:
I think it doesn't make much difference if you are only interested in source compatibility.
Using a property is better for binary compatibility since you can replace it by a property which has a setter without breaking compiled code depending on your library.
Convention:
You are following the convention. In cases like this where the differences between the two possibilities are relatively minor following the convention is better. One case where it might come back to bite you is reflection based code. It might only accept properties and not fields, for example a property editor/viewer.
Serialization
Changing from field to property will probably break a lot of serializers. And AFAIK XmlSerializer
does only serialize public properties and not public fields.
Using an Autoproperty
Another common Variation is using an autoproperty with a private setter. While this is short and a property it doesn't enforce the readonlyness. So I prefer the other ones.
Readonly field is selfdocumenting
There is one advantage of the field though:
It makes it clear at a glance at the public interface that it's actually immutable (barring reflection). Whereas in case of a property you can only see that you cannot change it, so you'd have to refer to the documentation or implementation.
But to be honest I use the first one quite often in application code since I'm lazy. In libraries I'm typically more thorough and follow the convention.
Text inside an ifdef/endif
or ifndef/endif
pair will be left in or removed by the pre-processor depending on the condition. ifdef
means "if the following is defined" while ifndef
means "if the following is not defined".
So:
#define one 0
#ifdef one
printf("one is defined ");
#endif
#ifndef one
printf("one is not defined ");
#endif
is equivalent to:
printf("one is defined ");
since one
is defined so the ifdef
is true and the ifndef
is false. It doesn't matter what it's defined as. A similar (better in my opinion) piece of code to that would be:
#define one 0
#ifdef one
printf("one is defined ");
#else
printf("one is not defined ");
#endif
since that specifies the intent more clearly in this particular situation.
In your particular case, the text after the ifdef
is not removed since one
is defined. The text after the ifndef
is removed for the same reason. There will need to be two closing endif
lines at some point and the first will cause lines to start being included again, as follows:
#define one 0
+--- #ifdef one
| printf("one is defined "); // Everything in here is included.
| +- #ifndef one
| | printf("one is not defined "); // Everything in here is excluded.
| | :
| +- #endif
| : // Everything in here is included again.
+--- #endif
First, create a empty DataFrame with column names, after that, inside the for loop, you must define a dictionary (a row) with the data to append:
df = pd.DataFrame(columns=['A'])
for i in range(5):
df = df.append({'A': i}, ignore_index=True)
df
A
0 0
1 1
2 2
3 3
4 4
If you want to add a row with more columns, the code will looks like this:
df = pd.DataFrame(columns=['A','B','C'])
for i in range(5):
df = df.append({'A': i,
'B': i * 2,
'C': i * 3,
}
,ignore_index=True
)
df
A B C
0 0 0 0
1 1 2 3
2 2 4 6
3 3 6 9
4 4 8 12
InstallUtil classes ( ServiceInstaller ) are considered an anti-pattern by the Windows Installer community. It's a fragile, out of process, reinventing of the wheel that ignores the fact that Windows Installer has built-in support for Services.
Visual Studio deployment projects ( also not highly regarded and deprecated in the next release of Visual Studio ) do not have native support for services. But they can consume merge modules. So I would take a look at this blog article to understand how to create a merge module using Windows Installer XML that can express the service and then consume that merge module in your VDPROJ solution.
Augmenting InstallShield using Windows Installer XML - Windows Services
The key is to give the anchor links a display property of "block" and a width property of 100%.
Making list-items clickable (example):
HTML:
<ul>
<li><a href="">link1</a></li>
<li><a href="">link2</a></li>
<li><a href="">link3</a></li>
</ul>
CSS:
ul {
list-style-type: none;
margin: 0;
padding: 0;
}
ul li a {
display: block;
width: 100%;
text-decoration: none;
padding: 5px;
}
ul li a:hover {
background-color: #ccc;
}
CPU Virtualization is enabled by default on all MacBooks with compatible CPUs (i7 is compatible). You can try to reset PRAM if you think it was disabled somehow, but I doubt it.
I think the issue might be in the old version of OS. If your MacBook is i7, then you better upgrade OS to something newer.
One more decision with es2015 arrow function
const isBoolean = val => typeof val === 'boolean';
Simple:
if ( $name eq 'tom' && $password eq '123!'
|| $name eq 'frank' && $password eq '321!'
) {
(use the high-precedence &&
and ||
in expressions, reserving and
and or
for flow control, to avoid common precedence errors)
Better:
my %password = (
'tom' => '123!',
'frank' => '321!',
);
if ( exists $password{$name} && $password eq $password{$name} ) {
In Python, you can do:
test = float("inf")
In Python 3.5, you can do:
import math
test = math.inf
And then:
test > 1
test > 10000
test > x
Will always be true. Unless of course, as pointed out, x is also infinity or "nan" ("not a number").
Additionally (Python 2.x ONLY), in a comparison to Ellipsis
, float(inf)
is lesser, e.g:
float('inf') < Ellipsis
would return true.
If you want the output to print to the terminal it is best to use Rscript
Rscript a.R
Note that when using R CMD BATCH a.R
that instead of redirecting output to standard out and displaying on the terminal a new file called a.Rout will be created.
R CMD BATCH a.R
# Check the output
cat a.Rout
One other thing to note about using Rscript is that it doesn't load the methods
package by default which can cause confusion. So if you're relying on anything that methods provides you'll want to load it explicitly in your script.
If you really want to use the ./a.R
way of calling the script you could add an appropriate #!
to the top of the script
#!/usr/bin/env Rscript
sayHello <- function(){
print('hello')
}
sayHello()
I will also note that if you're running on a *unix system there is the useful littler package which provides easy command line piping to R. It may be necessary to use littler to run shiny apps via a script? Further details can be found in this question.
There are mostly all browser support RGBa code in CSS but only IE8 and below level does not support RGBa css code. For This here is solution. For The solution you must follow this code and it’s better to go with it’s sequence otherwise you will not get perfect output as you wish. This code is used by me and it’s mostly perfect. make comment if it’s perfect.
.class
{
/* Web browsers that does not support RGBa */
background: rgb(0, 0, 0);
/* IE9/FF/chrome/safari supported */
background: rgba(0, 0, 0, 0.6);
/* IE 8 suppoerted */
/* Here some time problem for Hover than you can use background color/image */
-ms-filter: "progid:DXImageTransform.Microsoft.gradient(startColorstr=#88000000, endColorstr=#88000000)";
/* Below IE7 supported */
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr=#88000000, endColorstr=#88000000);
}
Several of the questions/comments I've seen around this subject sound to me as if the person is using Namespace
where they mean 'module alias'. As Ryan Cavanaugh mentioned in one of his comments you can have a 'Wrapper' module re-export several modules.
If you really want to import it all from the same module name/alias, combine a wrapper module with a paths mapping in your tsconfig.json
.
Example:
./path/to/CompanyName.Products/Foo.ts
export class Foo {
...
}
./path/to/CompanyName.Products/Bar.ts
export class Bar {
...
}
./path/to/CompanyName.Products/index.ts
export { Foo } from './Foo';
export { Bar } from './Bar';
tsconfig.json
{
"compilerOptions": {
...
paths: {
...
"CompanyName.Products": ["./path/to/CompanyName.Products/index"],
...
}
...
}
...
}
main.ts
import { Foo, Bar } from 'CompanyName.Products'
Note: The module resolution in the output .js files will need to be handled somehow, such as with this https://github.com/tleunen/babel-plugin-module-resolver
Example .babelrc
to handle the alias resolution:
{
"plugins": [
[ "module-resolver", {
"cwd": "babelrc",
"alias": {
"CompanyName.Products": "./path/to/typescript/build/output/CompanyName.Products/index.js"
}
}],
... other plugins ...
]
}
Generally git pull
is enough, but I'm not sure what layout you have chosen (or has github chosen for you).
The first methods seem to work in the browsers that I tested, but the option tags doesn't really correspond to actual elements in all browsers, so the result may vary.
Just use the selectedIndex
property of the DOM element:
alert($("#dropDownMenuKategorie")[0].selectedIndex);
Since version 1.6 jQuery has the prop
method that can be used to read properties:
alert($("#dropDownMenuKategorie").prop('selectedIndex'));
This method takes all views inside a layout, this is similar to Alexander Kulyakhtin's answer. The difference is, it accepts any type of parent layouts & returns an Array List of views.
public List<View> getAllViews(ViewGroup layout){
List<View> views = new ArrayList<>();
for(int i =0; i< layout.getChildCount(); i++){
views.add(layout.getChildAt(i));
}
return views;
}
I'm not sure what your reasons are, and even if you could pull it off somehow with Reflection Emit (I' not sure that you can), it doesn't sound like a good idea. What is probably a better idea is to have some kind of Dictionary and you can wrap access to the dictionary through methods in your class. That way you can store the data from the database in this dictionary, and then retrieve them using those methods.
After hours of searching and looking for answer, finally I made it!!!!! Code is below :))))
HTML:
<form id="fileinfo" enctype="multipart/form-data" method="post" name="fileinfo">
<label>File to stash:</label>
<input type="file" name="file" required />
</form>
<input type="button" value="Stash the file!"></input>
<div id="output"></div>
jQuery:
$(function(){
$('#uploadBTN').on('click', function(){
var fd = new FormData($("#fileinfo"));
//fd.append("CustomField", "This is some extra data");
$.ajax({
url: 'upload.php',
type: 'POST',
data: fd,
success:function(data){
$('#output').html(data);
},
cache: false,
contentType: false,
processData: false
});
});
});
In the upload.php
file you can access the data passed with $_FILES['file']
.
Thanks everyone for trying to help:)
I took the answer from here (with some changes) MDN
Since its mentioned in Android documentation that AAPT has been deprecated, getting the package name using AAPT2 command in Linux is as follows:
./aapt2 dump packagename <path_to_apk>
Since I am using an older version of Gradle build, I had to download a newer version of AAPT2 as mentioned here :
Download AAPT2 from Google Maven
Using the build-tools in my sdk - 25.0.3, 26.0.1 and 27.0.3, executing the aapt2 command shows an error: Unable to open 'packagename': No such file or directory. That's why I went for the newer versions of AAPT2.
I used 3.3.0-5013011 for linux.
If you want to avoid adding extra dependencies, I found node's process.argv
to be useful:
gulp.task('mytask', function() {
console.log(process.argv);
});
So the following:
gulp mytask --option 123
should display:
[ 'node', 'path/to/gulp.js', 'mytask', '--option', '123']
If you are sure that the desired parameter is in the right position, then the flags aren't needed.** Just use (in this case):
var option = process.argv[4]; //set to '123'
BUT: as the option may not be set, or may be in a different position, I feel that a better idea would be something like:
var option, i = process.argv.indexOf("--option");
if(i>-1) {
option = process.argv[i+1];
}
That way, you can handle variations in multiple options, like:
//task should still find 'option' variable in all cases
gulp mytask --newoption somestuff --option 123
gulp mytask --option 123 --newoption somestuff
gulp mytask --flag --option 123
** Edit: true for node scripts, but gulp interprets anything without a leading "--" as another task name. So using gulp mytask 123
will fail because gulp can't find a task called '123'.
You can just put // in front of $yourUrl in href:
<a href="//<?=$yourUrl?>"></a>
I encountered the same problem when I try to run Ant build using the following command:
java -cp ant.jar:ant-launcher.jar org.apache.tools.ant.Main
The output of the command is:
BUILD FAILED
XXX/build.xml:8: Unable to find a javac compiler;
com.sun.tools.javac.Main is not on the classpath.
Perhaps JAVA_HOME does not point to the JDK.
It is currently set to "/usr/lib/jvm/java-6-openjdk/jre"
It seems the java executable is picking "/usr/lib/jvm/java-6-openjdk/jre" as JAVA_HOME, as opposed to "/usr/lib/jvm/java-6-openjdk" where JDK is installed.
I resolved this issue by setting fork="yes"
in my <javac>
task.
Take a look at: http://ant.apache.org/manual/Tasks/javac.html
For domain specific Multi PHP Cron Job, do like this,
/usr/local/bin/ea-php56 /home/username/domain_path/path/to/cron/script
In the above example, replace “ea-php56” with the PHP version assigned to the domain you wish to use.
Hope this helps someone.
You can use a case in this case, to separate versions one example is using FACT os (which returns the version etc of your system... the command facter will return the details:
root@sytem# facter -p os
{"name"=>"CentOS", "family"=>"RedHat", "release"=>{"major"=>"7", "minor"=>"0", "full"=>"7.0.1406"}}
#we capture release hash
$curr_os = $os['release']
case $curr_os['major'] {
'7': { .... something }
*: {something}
}
That is an fast example, Might have typos, or not exactly working. But using system facts you can see what happens.
The OS fact provides you 3 main variables: name, family, release... Under release you have a small dictionary with more information about your os! combining these you can create cases to meet your targets.
In JUnit 5 you can inject TestInfo
which simplifies test meta data providing to test methods. For example:
@Test
@DisplayName("This is my test")
@Tag("It is my tag")
void test1(TestInfo testInfo) {
assertEquals("This is my test", testInfo.getDisplayName());
assertTrue(testInfo.getTags().contains("It is my tag"));
}
See more: JUnit 5 User guide, TestInfo javadoc.
Selected answer works for one drop down menu only. For multiple solution would be:
$('body').click(function(event){
$dropdowns.not($dropdowns.has(event.target)).hide();
});
There is an alternative to using COPY, which is the multirow values syntax that Postgres supports. From the documentation:
INSERT INTO films (code, title, did, date_prod, kind) VALUES
('B6717', 'Tampopo', 110, '1985-02-10', 'Comedy'),
('HG120', 'The Dinner Game', 140, DEFAULT, 'Comedy');
The above code inserts two rows, but you can extend it arbitrarily, until you hit the maximum number of prepared statement tokens (it might be $999, but I'm not 100% sure about that). Sometimes one cannot use COPY, and this is a worthy replacement for those situations.
I only use MicrosoftAdvertising.Mobile and Microsoft.Advertising.Mobile.UI and I am served ads. The SDK should only add the DLLs not reference itself.
Note: You need to explicitly set width and height Make sure the phone dialer, and web browser capabilities are enabled
Followup note: Make sure that after you've removed the SDK DLL, that the xmlns references are not still pointing to it. The best route to take here is
Here is the xmlns reference:
xmlns:AdNamepace="clr-namespace:Microsoft.Advertising.Mobile.UI;assembly=Microsoft.Advertising.Mobile.UI"
Then the ad itself:
<AdNamespace:AdControl x:Name="myAd" Height="80" Width="480" AdUnitId="yourAdUnitIdHere" ApplicationId="yourIdHere"/>
As the question is asked years ago, and Android is evolved a lot on this URI scheme.
From original URI scheme, to deep link, and now Android App Links.
Android now recommends to use HTTP URLs, not define your own URI scheme. Because Android App Links use HTTP URLs that link to a website domain you own, so no other app can use your links. You can check the comparison of deep link and Android App links from here
Now you can easily add a URI scheme by using Android Studio option: Tools > App Links Assistant. Please refer the detail to Android document: https://developer.android.com/studio/write/app-link-indexing.html
here is an easy way to use join.
''.join(('a', 'b', 'c', 'd', 'g', 'x', 'r', 'e'))
If you don't want the image to affect the layout at all (and float on top of other content) you can apply the following CSS to the image:
position:absolute;
right:0;
top:0;
If you want it to float at the right of a particular parent section, you can add position: relative
to that section.
You can use LEN in combination with SUBSTRING:
SELECT SUBSTRING(myColumn, 7, LEN(myColumn)) from myTable
Check if you are returning a @ResponseBody or a @ResponseStatus
I had a similar problem. My Controller looked like that:
@RequestMapping(value="/user", method = RequestMethod.POST)
public String updateUser(@RequestBody User user){
return userService.updateUser(user).getId();
}
When calling with a POST request I always got the following error:
HTTP Status 405 - Request method 'POST' not supported
After a while I figured out that the method was actually called, but because there is no @ResponseBody and no @ResponseStatus Spring MVC raises the error.
To fix this simply add a @ResponseBody
@RequestMapping(value="/user", method = RequestMethod.POST)
public @ResponseBody String updateUser(@RequestBody User user){
return userService.updateUser(user).getId();
}
or a @ResponseStatus to your method.
@RequestMapping(value="/user", method = RequestMethod.POST)
@ResponseStatus(value=HttpStatus.OK)
public String updateUser(@RequestBody User user){
return userService.updateUser(user).getId();
}
You can declare local variables in MySQL triggers, with the DECLARE
syntax.
Here's an example:
DROP TABLE IF EXISTS foo;
CREATE TABLE FOO (
i SERIAL PRIMARY KEY
);
DELIMITER //
DROP TRIGGER IF EXISTS bar //
CREATE TRIGGER bar AFTER INSERT ON foo
FOR EACH ROW BEGIN
DECLARE x INT;
SET x = NEW.i;
SET @a = x; -- set user variable outside trigger
END//
DELIMITER ;
SET @a = 0;
SELECT @a; -- returns 0
INSERT INTO foo () VALUES ();
SELECT @a; -- returns 1, the value it got during the trigger
When you assign a value to a variable, you must ensure that the query returns only a single value, not a set of rows or a set of columns. For instance, if your query returns a single value in practice, it's okay but as soon as it returns more than one row, you get "ERROR 1242: Subquery returns more than 1 row
".
You can use LIMIT
or MAX()
to make sure that the local variable is set to a single value.
CREATE TRIGGER bar AFTER INSERT ON foo
FOR EACH ROW BEGIN
DECLARE x INT;
SET x = (SELECT age FROM users WHERE name = 'Bill');
-- ERROR 1242 if more than one row with 'Bill'
END//
CREATE TRIGGER bar AFTER INSERT ON foo
FOR EACH ROW BEGIN
DECLARE x INT;
SET x = (SELECT MAX(age) FROM users WHERE name = 'Bill');
-- OK even when more than one row with 'Bill'
END//
Add:
DELIMITER
at the beginning and end of the SP.validar_egreso
; at the beginning@variableName
.This works for me. (I modified some part of your script so ANYONE can run it with out having your tables).
DROP PROCEDURE IF EXISTS `validar_egreso`;
DELIMITER $$
CREATE DEFINER='root'@'localhost' PROCEDURE `validar_egreso` (
IN codigo_producto VARCHAR(100),
IN cantidad INT,
OUT valido INT(11)
)
BEGIN
DECLARE resta INT;
SET resta = 0;
SELECT (codigo_producto - cantidad) INTO resta;
IF(resta > 1) THEN
SET valido = 1;
ELSE
SET valido = -1;
END IF;
SELECT valido;
END $$
DELIMITER ;
-- execute the stored procedure
CALL validar_egreso(4, 1, @val);
-- display the result
select @val;
Never try to edit to @_ variable!!!! They must be not touched.. Or you get some unsuspected effect. For example...
my $size=1234;
sub sub1{
$_[0]=500;
}
sub1 $size;
Before call sub1 $size contain 1234. But after 500(!!) So you Don't edit this value!!! You may pass two or more values and change them in subroutine and all of them will be changed! I've never seen this effect described. Programs I've seen also leave @_ array readonly. And only that you may safely pass variable don't changed internal subroutine You must always do that:
sub sub2{
my @m=@_;
....
}
assign @_ to local subroutine procedure variables and next worked with them. Also in some deep recursive algorithms that returun array you may use this approach to reduce memory used for local vars. Only if return @_ array the same.
You can use HttpClient and HttpPost to build and send the request.
HttpClient client= new DefaultHttpClient();
HttpPost request = new HttpPost("www.example.com");
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("paramName", "paramValue"));
request.setEntity(new UrlEncodedFormEntity(pairs ));
HttpResponse resp = client.execute(request);
Just my two cents for iOS 10 (under NDA, but for people that can use it legally...)
This was tested using Xcode 7.3 (std from Store) AND iPhone 6Plus with 10.0 (14A5261v).
To avoid the TOCTOU issue highlighted by Éric Araujo's comment, you can catch an exception to call the correct method:
def remove_file_or_dir(path: str) -> None:
""" Remove a file or directory """
try:
shutil.rmtree(path)
except NotADirectoryError:
os.remove(path)
Since shutil.rmtree()
will only remove directories and os.remove()
or os.unlink()
will only remove files.
The free and open-source program called cabextract will list and extract the contents of not just .cab-files, but Macrovision's archives too:
% cabextract /tmp/QLWREL.EXE
Extracting cabinet: /tmp/QLWREL.EXE
extracting ikernel.dll
extracting IsProBENT.tlb
....
extracting IScript.dll
extracting iKernel.rgs
All done, no errors.
#$computerList = "Server Name"
#$regVar = "Name of the package "
#$packageName = "Packe name "
$computerList = $args[0]
$regVar = $args[1]
$packageName = $args[2]
foreach ($computer in $computerList)
{
Write-Host "Connecting to $computer...."
Invoke-Command -ComputerName $computer -Authentication Kerberos -ScriptBlock {
param(
$computer,
$regVar,
$packageName
)
Write-Host "Connected to $computer"
if ([IntPtr]::Size -eq 4)
{
$registryLocation = Get-ChildItem "HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\"
Write-Host "Connected to 32bit Architecture"
}
else
{
$registryLocation = Get-ChildItem "HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\"
Write-Host "Connected to 64bit Architecture"
}
Write-Host "Finding previous version of `enter code here`$regVar...."
foreach ($registryItem in $registryLocation)
{
if((Get-itemproperty $registryItem.PSPath).DisplayName -match $regVar)
{
Write-Host "Found $regVar" (Get-itemproperty $registryItem.PSPath).DisplayName
$UninstallString = (Get-itemproperty $registryItem.PSPath).UninstallString
$match = [RegEx]::Match($uninstallString, "{.*?}")
$args = "/x $($match.Value) /qb"
Write-Host "Uninstalling $regVar...."
[diagnostics.process]::start("msiexec", $args).WaitForExit()
Write-Host "Uninstalled $regVar"
}
}
$path = "\\$computer\Msi\$packageName"
Write-Host "Installaing $path...."
$args = " /i $path /qb"
[diagnostics.process]::start("msiexec", $args).WaitForExit()
Write-Host "Installed $path"
} -ArgumentList $computer, $regVar, $packageName
Write-Host "Deployment Complete"
}
Use the set()
method: see doc
arraylist.set(index,newvalue);
Try:
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=file.csv");
header("Pragma: no-cache");
header("Expires: 0");
echo "record1,record2,record3\n";
die;
etc
Edit: Here's a snippet of code I use to optionally encode CSV fields:
function maybeEncodeCSVField($string) {
if(strpos($string, ',') !== false || strpos($string, '"') !== false || strpos($string, "\n") !== false) {
$string = '"' . str_replace('"', '""', $string) . '"';
}
return $string;
}
For someone who want to use onchange event directly on file input, set onchange="somefunction()
, example code from the link:
<html>
<body>
<script language="JavaScript">
function inform(){
document.form1.msg.value = "Filename has been changed";
}
</script>
<form name="form1">
Please choose a file.
<input type="file" name="uploadbox" size="35" onChange='inform()'>
<br><br>
Message:
<input type="text" name="msg" size="40">
</form>
</body>
</html>
Use the following:
bower install --save git://github.com/USER/REPOS_NAME.git
More here: http://bower.io/#getting-started
^(-?\d+\.)?-?\d+$
allow:
23425.23425
10.10
100
0
0.00
-100
-10.10
10.-10
-10.-10
-23425.23425
-23425.-23425
0.234
In response to Haim Evgi's code, I added !== false to the end for it to work for me
$iPod = stripos($_SERVER['HTTP_USER_AGENT'],"iPod") !== false;
$iPhone = stripos($_SERVER['HTTP_USER_AGENT'],"iPhone") !== false;
$iPad = stripos($_SERVER['HTTP_USER_AGENT'],"iPad") !== false;
$Android = stripos($_SERVER['HTTP_USER_AGENT'],"Android") !== false;
This line calls the selector secondMethod after 3 seconds:
[self performSelector:@selector(secondMethod) withObject:nil afterDelay:3.0 ];
Use it on your second operation with your desired delay. If you have a lot of code, place it in its own method and call that method with performSelector:
. It wont block the UI like sleep
Edit: If you do not want a second method you could add a category to be able to use blocks with performSelector:
@implementation NSObject (PerformBlockAfterDelay)
- (void)performBlock:(void (^)(void))block
afterDelay:(NSTimeInterval)delay
{
block = [block copy];
[self performSelector:@selector(fireBlockAfterDelay:)
withObject:block
afterDelay:delay];
}
- (void)fireBlockAfterDelay:(void (^)(void))block
{
block();
}
@end
Or perhaps even cleaner:
void RunBlockAfterDelay(NSTimeInterval delay, void (^block)(void))
{
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_SEC*delay),
dispatch_get_current_queue(), block);
}
Convert the image to a byte[]
and store that in the database.
Add this column to your model:
public byte[] Content { get; set; }
Then convert your image to a byte array and store that like you would any other data:
public byte[] ImageToByteArray(System.Drawing.Image imageIn)
{
using(var ms = new MemoryStream())
{
imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
return ms.ToArray();
}
}
public Image ByteArrayToImage(byte[] byteArrayIn)
{
using(var ms = new MemoryStream(byteArrayIn))
{
var returnImage = Image.FromStream(ms);
return returnImage;
}
}
Source: Fastest way to convert Image to Byte array
var image = new ImageEntity()
{
Content = ImageToByteArray(image)
};
_context.Images.Add(image);
_context.SaveChanges();
When you want to get the image back, get the byte array from the database and use the ByteArrayToImage
and do what you wish with the Image
This stops working when the byte[]
gets to big. It will work for files under 100Mb
What is gone is gone. The only protection I know of is regular backup.
I was getting this message while validating (in MVC project). For me, adding ValidationMessageFor element fixed the issue.
To be precise, line number 43 in jquery.validate.unobtrusive.js caused the issue:
replace = $.parseJSON(container.attr("data-valmsg-replace")) !== false;
When I create a root class, whose methods I defined using the arrow functions. When inheriting and overwriting the original function I noticed the same issue.
class C {
x = () => 1;
};
class CC extends C {
x = (foo) => super.x() + foo;
};
let add = new CC;
console.log(add.x(4));
this is solved by defining the method of the parent class without arrow functions
class C {
x() {
return 1;
};
};
class CC extends C {
x = foo => super.x() + foo;
};
let add = new CC;
console.log(add.x(4));
Example: Inside myWindow() on line 3 is the code you need to set the window in the center of the screen.
JFrame window;
public myWindow() {
window = new JFrame();
window.setSize(1200,800);
window.setLocationRelativeTo(null); // this line set the window in the center of thr screen
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.getContentPane().setBackground(Color.BLACK);
window.setLayout(null); // disable the default layout to use custom one.
window.setVisible(true); // to show the window on the screen.
}
In other words, you want to pipe stdout into one filter (tee bbb.out
) and stderr into another filter (tee ccc.out
). There is no standard way to pipe anything other than stdout into another command, but you can work around that by juggling file descriptors.
{ { ./aaa.sh | tee bbb.out; } 2>&1 1>&3 | tee ccc.out; } 3>&1 1>&2
See also How to grep standard error stream (stderr)? and When would you use an additional file descriptor?
In bash (and ksh and zsh), but not in other POSIX shells such as dash, you can use process substitution:
./aaa.sh > >(tee bbb.out) 2> >(tee ccc.out)
Beware that in bash, this command returns as soon as ./aaa.sh
finishes, even if the tee
commands are still executed (ksh and zsh do wait for the subprocesses). This may be a problem if you do something like ./aaa.sh > >(tee bbb.out) 2> >(tee ccc.out); process_logs bbb.out ccc.out
. In that case, use file descriptor juggling or ksh/zsh instead.
Since cP/WHM took away the ability to modify User privileges as root in PHPMyAdmin, you have to use the command line to:
mysql> GRANT FILE ON *.* TO 'user'@'localhost';
Step 2 is to allow that user to dump a file in a specific folder. There are a few ways to do this but I ended up putting a folder in :
/home/user/tmp/db
and
chown mysql:mysql /home/user/tmp/db
That allows the mysql user to write the file. As previous posters have said, you can use the MySQL temp folder too, I don't suppose it really matters but you definitely don't want to make it 0777 permission (world-writeable) unless you want the world to see your data. There is a potential problem if you want to rinse-repeat the process as INTO OUTFILE
won't work if the file exists. If your files are owned by a different user then just trying to unlink($file)
won't work. If you're like me (paranoid about 0777) then you can set your target directory using:
chmod($dir,0777)
just prior to doing the SQL command, then
chmod($dir,0755)
immediately after, followed by unlink(file)
to delete the file. This keeps it all running under your web user and no need to invoke the mysql user.
In SQL Server 2008, you can use:
CONVERT(DATE, getdate(), 101)
Implementing the SearchView without the use of the menu.xml
file and open through button
In your Activity
we need to use the method of the onCreateOptionsMenu
method in which we will programmatically inflate the SearchView
private MenuItem searchMenu;
private String mSearchString="";
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
SearchManager searchManager = (SearchManager) StoreActivity.this.getSystemService(Context.SEARCH_SERVICE);
SearchView mSearchView = new SearchView(getSupportActionBar().getThemedContext());
mSearchView.setQueryHint(getString(R.string.prompt_search)); /// YOUR HINT MESSAGE
mSearchView.setMaxWidth(Integer.MAX_VALUE);
searchMenu = menu.add("searchMenu").setVisible(false).setActionView(mSearchView);
searchMenu.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM | MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW);
assert searchManager != null;
mSearchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
mSearchView.setIconifiedByDefault(false);
SearchView.OnQueryTextListener queryTextListener = new SearchView.OnQueryTextListener() {
public boolean onQueryTextChange(String newText) {
mSearchString = newText;
return true;
}
public boolean onQueryTextSubmit(String query) {
mSearchString = query;
searchMenu.collapseActionView();
return true;
}
};
mSearchView.setOnQueryTextListener(queryTextListener);
return true;
}
And in your Activity class, you can open the SearchView
on any button click on toolbar like below
YOUR_BUTTON.setOnClickListener(view -> {
searchMenu.expandActionView();
});
Maybe you were trying to do this?
#include <stdio.h>
int func(int * B){
/* B + OFFSET = 5 () You are pointing to the same region as B[OFFSET] */
*(B + 2) = 5;
}
int main(void) {
int B[10];
func(B);
/* Let's say you edited only 2 and you want to show it. */
printf("b[0] = %d\n\n", B[2]);
return 0;
}
How to insert table values from one server/database to another database?
1 Creating Linked Servers {if needs} (SQL server 2008 R2 - 2012) http://technet.microsoft.com/en-us/library/ff772782.aspx#SSMSProcedure
2 configure the linked server to use Credentials a) http://technet.microsoft.com/es-es/library/ms189811(v=sql.105).aspx
EXEC sp_addlinkedsrvlogin 'NAMEOFLINKEDSERVER', 'false', null, 'REMOTEUSERNAME', 'REMOTEUSERPASSWORD'
-- CHECK SERVERS
SELECT * FROM sys.servers
-- TEST LINKED SERVERS
EXEC sp_testlinkedserver N'NAMEOFLINKEDSERVER'
INSERT INTO NEW LOCAL TABLE
SELECT * INTO NEWTABLE
FROM [LINKEDSERVER\INSTANCE].remoteDATABASE.remoteSCHEMA.remoteTABLE
OR
INSERT AS NEW VALUES IN REMOTE TABLE
INSERT
INTO [LINKEDSERVER\INSTANCE].remoteDATABASE.remoteSCHEMA.remoteTABLE
SELECT *
FROM localTABLE
INSERT AS NEW LOCAL TABLE VALUES
INSERT
INTO localTABLE
SELECT *
FROM [LINKEDSERVER\INSTANCE].remoteDATABASE.remoteSCHEMA.remoteTABLE
This is clearly a problem that a lot of programmers have and to which Google has yet to provide a satisfactory, supported solution.
There are a lot of crossed intentions and misunderstandings floating around posts on this topic, so please read this whole answer before responding.
Below I include a more "refined" and well-commented version of the hack from other answers on this page, also incorporating ideas from these very closely related questions:
Change background color of android menu
How to change the background color of the options menu?
Android: customize application's menu (e.g background color)
http://www.macadamian.com/blog/post/android_-_theming_the_unthemable/
Android MenuItem Toggle Button
Is it possible to make the Android options menu background non-translucent?
http://www.codeproject.com/KB/android/AndroidMenusMyWay.aspx
Setting the menu background to be opaque
I tested this hack on 2.1 (simulator), 2.2 (2 real devices), and 2.3 (2 real devices). I don't have any 3.X tablets to test on yet but will post any needed changes here when/if I do. Given that 3.X tablets use Action Bars instead of Options Menus, as explained here:
http://developer.android.com/guide/topics/ui/menus.html#options-menu
this hack will almost certainly do nothing (no harm and no good) on 3.X tablets.
STATEMENT OF THE PROBLEM (read this before trigger-replying with a negative comment):
The Options menu has vastly different styles on different devices. Pure black with white text on some, pure white with black text on some. I and many other developers wish to control the background color of the Options menu cells as well as the color of the Options menu text.
Certain app developers only need to set the cell background color (not the text color), and they can do this in a cleaner manner using the android:panelFullBackground style described in another answer. However, there is currently no way to control the Options menu text color with styles, and so one can only use this method to change the background to another color that won't make the text "disappear."
We would love to do this with a documented, future-proof solution, but one is simply not available as of Android <= 2.3. So we have to use a solution that works in current versions and is designed to minimize the chances of crashing/breaking in future versions. We want a solution that fails gracefully back to the default behavior if it has to fail.
There are many legitimate reasons why one may need to control the look of Options menus (typically to match a visual style for the rest of the app) so I won't dwell on that.
There is a Google Android bug posted about this: please add your support by starring this bug (note Google discourages "me too" comments: just a star is enough):
http://code.google.com/p/android/issues/detail?id=4441
SUMMARY OF SOLUTIONS SO FAR:
Several posters have suggested a hack involving LayoutInflater.Factory. The suggested hack worked for Android <= 2.2 and failed for Android 2.3 because the hack made an undocumented assumption: that one could call LayoutInflater.getView() directly without currently being inside a call to LayoutInflater.inflate() on the same LayoutInflater instance. New code in Android 2.3 broke this assumption and led to a NullPointerException.
My slightly refined hack below does not rely on this assumption.
Furthermore, the hacks also rely on using an internal, undocumented class name "com.android.internal.view.menu.IconMenuItemView" as a string (not as a Java type). I do not see any way to avoid this and still accomplish the stated goal. However, it is possible to do the hack in a careful way that will fall back if "com.android.internal.view.menu.IconMenuItemView" does not appear on the current system.
Again, understand that this is a hack and by no means am I claiming this will work on all platforms. But we developers are not living in a fantasy academic world where everything has to be by the book: we have a problem to solve and we have to solve it as best we can. For example, it seems unlikely that "com.android.internal.view.menu.IconMenuItemView" will exist on 3.X tablets since they use Action Bars instead of Options Menus.
Finally, some developers have solved this problem by totally suppressing the Android Options Menu and writing their own menu class (see some of the links above). I haven't tried this, but if you have time to write your own View and figure out how to replace Android's view (I'm sure the devil's in the details here) then it might be a nice solution that doesn't require any undocumented hacks.
HACK:
Here is the code.
To use this code, call addOptionsMenuHackerInflaterFactory() ONCE from your activity onCreate() or your activity onCreateOptionsMenu(). It sets a default factory that will affect subsequent creation of any Options Menu. It does not affect Options Menus that have already been created (the previous hacks used a function name of setMenuBackground(), which is very misleading since the function doesn't set any menu properties before it returns).
@SuppressWarnings("rawtypes")
static Class IconMenuItemView_class = null;
@SuppressWarnings("rawtypes")
static Constructor IconMenuItemView_constructor = null;
// standard signature of constructor expected by inflater of all View classes
@SuppressWarnings("rawtypes")
private static final Class[] standard_inflater_constructor_signature =
new Class[] { Context.class, AttributeSet.class };
protected void addOptionsMenuHackerInflaterFactory()
{
final LayoutInflater infl = getLayoutInflater();
infl.setFactory(new Factory()
{
public View onCreateView(final String name,
final Context context,
final AttributeSet attrs)
{
if (!name.equalsIgnoreCase("com.android.internal.view.menu.IconMenuItemView"))
return null; // use normal inflater
View view = null;
// "com.android.internal.view.menu.IconMenuItemView"
// - is the name of an internal Java class
// - that exists in Android <= 3.2 and possibly beyond
// - that may or may not exist in other Android revs
// - is the class whose instance we want to modify to set background etc.
// - is the class we want to instantiate with the standard constructor:
// IconMenuItemView(context, attrs)
// - this is what the LayoutInflater does if we return null
// - unfortunately we cannot just call:
// infl.createView(name, null, attrs);
// here because on Android 3.2 (and possibly later):
// 1. createView() can only be called inside inflate(),
// because inflate() sets the context parameter ultimately
// passed to the IconMenuItemView constructor's first arg,
// storing it in a LayoutInflater instance variable.
// 2. we are inside inflate(),
// 3. BUT from a different instance of LayoutInflater (not infl)
// 4. there is no way to get access to the actual instance being used
// - so we must do what createView() would have done for us
//
if (IconMenuItemView_class == null)
{
try
{
IconMenuItemView_class = getClassLoader().loadClass(name);
}
catch (ClassNotFoundException e)
{
// this OS does not have IconMenuItemView - fail gracefully
return null; // hack failed: use normal inflater
}
}
if (IconMenuItemView_class == null)
return null; // hack failed: use normal inflater
if (IconMenuItemView_constructor == null)
{
try
{
IconMenuItemView_constructor =
IconMenuItemView_class.getConstructor(standard_inflater_constructor_signature);
}
catch (SecurityException e)
{
return null; // hack failed: use normal inflater
}
catch (NoSuchMethodException e)
{
return null; // hack failed: use normal inflater
}
}
if (IconMenuItemView_constructor == null)
return null; // hack failed: use normal inflater
try
{
Object[] args = new Object[] { context, attrs };
view = (View)(IconMenuItemView_constructor.newInstance(args));
}
catch (IllegalArgumentException e)
{
return null; // hack failed: use normal inflater
}
catch (InstantiationException e)
{
return null; // hack failed: use normal inflater
}
catch (IllegalAccessException e)
{
return null; // hack failed: use normal inflater
}
catch (InvocationTargetException e)
{
return null; // hack failed: use normal inflater
}
if (null == view) // in theory handled above, but be safe...
return null; // hack failed: use normal inflater
// apply our own View settings after we get back to runloop
// - android will overwrite almost any setting we make now
final View v = view;
new Handler().post(new Runnable()
{
public void run()
{
v.setBackgroundColor(Color.BLACK);
try
{
// in Android <= 3.2, IconMenuItemView implemented with TextView
// guard against possible future change in implementation
TextView tv = (TextView)v;
tv.setTextColor(Color.WHITE);
}
catch (ClassCastException e)
{
// hack failed: do not set TextView attributes
}
}
});
return view;
}
});
}
Thanks for reading and enjoy!
//create authentication base 64 encoding string
let PasswordString = "\(txtUserName.text):\(txtPassword.text)"
let PasswordData = PasswordString.dataUsingEncoding(NSUTF8StringEncoding)
let base64EncodedCredential = PasswordData!.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.Encoding64CharacterLineLength)
//let base64EncodedCredential = PasswordData!.base64EncodedStringWithOptions(nil)
//create authentication url
let urlPath: String = "http://...../auth"
var url: NSURL = NSURL(string: urlPath)
//create and initialize basic authentication request
var request: NSMutableURLRequest = NSMutableURLRequest(URL: url)
request.setValue("Basic \(base64EncodedCredential)", forHTTPHeaderField: "Authorization")
request.HTTPMethod = "GET"
//You can use one of below methods
//1 URL request with NSURLConnectionDataDelegate
let queue:NSOperationQueue = NSOperationQueue()
let urlConnection = NSURLConnection(request: request, delegate: self)
urlConnection.start()
//2 URL Request with AsynchronousRequest
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) {(response, data, error) in
println(NSString(data: data, encoding: NSUTF8StringEncoding))
}
//2 URL Request with AsynchronousRequest with json output
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue(), completionHandler:{ (response: NSURLResponse!, data: NSData!, error: NSError!) -> Void in
var err: NSError
var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary
println("\(jsonResult)")
})
//3 URL Request with SynchronousRequest
var response: AutoreleasingUnsafePointer<NSURLResponse?>=nil
var dataVal: NSData = NSURLConnection.sendSynchronousRequest(request, returningResponse: response, error:nil)
var err: NSError
var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(dataVal, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary
println("\(jsonResult)")
//4 URL Request with NSURLSession
let config = NSURLSessionConfiguration.defaultSessionConfiguration()
let authString = "Basic \(base64EncodedCredential)"
config.HTTPAdditionalHeaders = ["Authorization" : authString]
let session = NSURLSession(configuration: config)
session.dataTaskWithURL(url) {
(let data, let response, let error) in
if let httpResponse = response as? NSHTTPURLResponse {
let dataString = NSString(data: data, encoding: NSUTF8StringEncoding)
println(dataString)
}
}.resume()
// you may be get fatal error if you changed the request.HTTPMethod = "POST" when server request GET request
You can change target for Git Bash shortcut from:
"C:\Program Files\Git\git-bash.exe" --cd-to-home
to
"C:\Program Files\Git\git-cmd.exe" --no-cd --command=usr/bin/bash.exe -l -i
This is the way ConEmu used to start git bash (version 16). Recent version starts it normally and it's how I got there...
This is kind of a hack but the best solution that I have found is to use a description tag with no \item. This will produce an error from the latex compiler; however, the error does not prevent the pdf from being generated.
\begin{description}
<YOUR TEXT HERE>
\end{description}
Choose one from, where :my_date
is a string input parameter of yyyy-MM-dd
format:
SELECT EXTRACT(YEAR FROM CAST(:my_date AS DATE));
or
SELECT DATE_PART('year', CAST(:my_date AS DATE));
Better use CAST
than ::
as there may be conflicts with input parameters.
You can use this utility:
c:\Windows\system32\fsutil.exe create hardlink
ex: url/:id
var sample= app.controller('sample', function ($scope, $routeParams) {
$scope.init = function () {
var qa_id = $routeParams.qa_id;
}
});
EDIT: I am maintaining a similar, but more in-depth answer at: https://stackoverflow.com/a/28380690/895245
To see exactly what is happening, use nc -l
or an ECHO server and an user agent like a browser or cURL.
Save the form to an .html
file:
<form action="http://localhost:8000" method="post" enctype="multipart/form-data">
<p><input type="text" name="text" value="text default">
<p><input type="file" name="file1">
<p><input type="file" name="file2">
<p><button type="submit">Submit</button>
</form>
Create files to upload:
echo 'Content of a.txt.' > a.txt
echo '<!DOCTYPE html><title>Content of a.html.</title>' > a.html
Run:
nc -l localhost 8000
Open the HTML on your browser, select the files and click on submit and check the terminal.
nc
prints the request received. Firefox sent:
POST / HTTP/1.1
Host: localhost:8000
User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:29.0) Gecko/20100101 Firefox/29.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Cookie: __atuvc=34%7C7; permanent=0; _gitlab_session=226ad8a0be43681acf38c2fab9497240; __profilin=p%3Dt; request_method=GET
Connection: keep-alive
Content-Type: multipart/form-data; boundary=---------------------------9051914041544843365972754266
Content-Length: 554
-----------------------------9051914041544843365972754266
Content-Disposition: form-data; name="text"
text default
-----------------------------9051914041544843365972754266
Content-Disposition: form-data; name="file1"; filename="a.txt"
Content-Type: text/plain
Content of a.txt.
-----------------------------9051914041544843365972754266
Content-Disposition: form-data; name="file2"; filename="a.html"
Content-Type: text/html
<!DOCTYPE html><title>Content of a.html.</title>
-----------------------------9051914041544843365972754266--
Aternativelly, cURL should send the same POST request as your a browser form:
nc -l localhost 8000
curl -F "text=default" -F "[email protected]" -F "[email protected]" localhost:8000
You can do multiple tests with:
while true; do printf '' | nc -l localhost 8000; done
<select id="myDropDown">
<option>html5</option>
<option>javascript</option>
<option>jquery</option>
<option>css</option>
<option>sencha</option>
</select>
By jQuery:
var myDropDown=$("#myDropDown");
var length = $('#myDropDown> option').length;
//open dropdown
myDropDown.attr('size',length);
//close dropdown
myDropDown.attr('size',0);
By javascript:
var myDropDown=document.getElementById("myDropDown");
var length = myDropDown.options.length;
//open dropdown
myDropDown.size = length;
//close dropdown
myDropDown.size = 0;
Copied from: Open close select
SELECT convert(datetime, '23/07/2009', 103)
This below code will give selected row, you can parse the values from it and send to the AJAX call.
$(".selected").click(function () {
var row = $(this).parent().parent().parent().html();
});
I was trying to set the log_statement
in some postgres config file but in fact the file was not read by our postgres.
I confirmed that using the request :
select *
from pg_settings
[...]
log_statement none # That was not the value i was expected for !!!
I use this way https://stackoverflow.com/a/41912295/2294168
command: postgres -c config_file=/etc/postgresql.conf
Use CURRENT_TIMESTAMP (or GETDATE() on archaic versions of SQL Server).
Pulling may have created local change.
Add your untracked file:
git add .
Stash changes.
git stash
Drop local changes.
git stash drop
Pull with sudo permission
sudo git pull remote branch
You can use following code for that:
var assignedRoleId = new Array();
$('#RolesListAssigned option').each(function(){
assignedRoleId.push(this.value);
});
If you declare the name for enumeration no error will occur.
If not declared, you have to use a typedef
:
enum enum_name {RANDOM, IMMEDIATE, SEARCH} strategy;
strategy = IMMEDIATE;
It will not display an error...
The linked list holds operations on the shared data structure.
For example, if I have a stack, it will be manipulated with pushes and pops. The linked list would be a set of pushes and pops on the pseudo-shared stack. Each thread sharing that stack will actually have a local copy, and to get to the current shared state, it'll walk the linked list of operations, and apply each operation in order to its local copy of the stack. When it reaches the end of the linked list, its local copy holds the current state (though, of course, it's subject to becoming stale at any time).
In the traditional model, you'd have some sort of locks around each push and pop. Each thread would wait to obtain a lock, then do a push or pop, then release the lock.
In this model, each thread has a local snapshot of the stack, which it keeps synchronized with other threads' view of the stack by applying the operations in the linked list. When it wants to manipulate the stack, it doesn't try to manipulate it directly at all. Instead, it simply adds its push or pop operation to the linked list, so all the other threads can/will see that operation and they can all stay in sync. Then, of course, it applies the operations in the linked list, and when (for example) there's a pop it checks which thread asked for the pop. It uses the popped item if and only if it's the thread that requested this particular pop.
Use the Microsoft.VisualBasic.FileIO.TextFieldParser
class. This will handle parsing a delimited file, TextReader
or Stream
where some fields are enclosed in quotes and some are not.
For example:
using Microsoft.VisualBasic.FileIO;
string csv = "2,1016,7/31/2008 14:22,Geoff Dalgas,6/5/2011 22:21,http://stackoverflow.com,\"Corvallis, OR\",7679,351,81,b437f461b3fd27387c5d8ab47a293d35,34";
TextFieldParser parser = new TextFieldParser(new StringReader(csv));
// You can also read from a file
// TextFieldParser parser = new TextFieldParser("mycsvfile.csv");
parser.HasFieldsEnclosedInQuotes = true;
parser.SetDelimiters(",");
string[] fields;
while (!parser.EndOfData)
{
fields = parser.ReadFields();
foreach (string field in fields)
{
Console.WriteLine(field);
}
}
parser.Close();
This should result in the following output:
2 1016 7/31/2008 14:22 Geoff Dalgas 6/5/2011 22:21 http://stackoverflow.com Corvallis, OR 7679 351 81 b437f461b3fd27387c5d8ab47a293d35 34
See Microsoft.VisualBasic.FileIO.TextFieldParser for more information.
You need to add a reference to Microsoft.VisualBasic
in the Add References .NET tab.
First, you should know what an Optional value is. You can step to The Swift Programming Language for detail.
Second, you should know the optional value has two statuses. One is the full value, and the other is a nil value. So before you implement an optional value, you should check which state it is.
You can use if let ...
or guard let ... else
and so on.
One other way, if you don't want to check the variable state before your implementation, you can also use var buildingName = buildingName ?? "buildingName"
instead.
Additionally for what was said, if you want integer powers of two, then 1 << x
(or 1L << x
) is a faster way to calculate 2x than Math.pow(2,x)
or a multiplication loop, and is guaranteed to give you an int
(or long
) result.
It only uses the lowest 5 (or 6) bits of x
(i.e. x & 31
(or x & 63
)), though, shifting between 0 and 31 (or 63) bits.
router.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Methods", "*");
res.header("Access-Control-Allow-Headers", "*");
next();});
add this to your routes which you are calling from front-end. Ex- if you call for http://localhost:3000/users/register you must add this code fragment on your back-end .js file which this route lays.
In my case, when I'm in an activity that extends from AppCompatActivity
, it did not work(Activity) getApplicationContext ()
, I just putthis
in its place.
Or far simpler than dealing with Spannable
s manually, since you didn't say that you want the background highlighted, just the text:
String styledText = "This is <font color='red'>simple</font>.";
textView.setText(Html.fromHtml(styledText), TextView.BufferType.SPANNABLE);
Often when you need to show so many points on the map, you'd be better off using the server-side approach, this article explains when to use each:
Geocoding Strategies: https://developers.google.com/maps/articles/geocodestrat
The client-side limit is not exactly "10 requests per second", and since it's not explained in the API docs I wouldn't rely on its behavior.
Actually Shay levy's answer is almost correct but i got an weird issue as i mentioned in his comment column. So i split the command into two lines and it works fine.
$Ipaddress= Read-Host "Enter the IP address:"
$Port= Read-host "Enter the port number to access:"
$t = New-Object Net.Sockets.TcpClient
$t.Connect($Ipaddress,$Port)
if($t.Connected)
{
"Port $Port is operational"
}
else
{
"Port $Port is closed, You may need to contact your IT team to open it. "
}
If you need to just empty the style
of an element then:
element.style.cssText = null;
This should do good. Hope it helps!
Same solution as @Al3x for Windows x64, in cmd.exe
:
cd %programfiles%\Oracle\VirtualBox
VBoxManage internalcommands sethduuid "full/path/to/.vdi"
This randomizes the UUID of the disk. Pro tip: Right click the .vdi file while holding shift and select "Copy as path" to obtain "full/path/to/.vdi"
and enable quick edit in cmd.exe, then right click to paste.
I've used this "portable plotter". It's very small, multiplatform, easy to use and you can plug it into different graphical libraries. pplot
(Only for the plots part)
If you use or plan to use Qt, another multiplatform solution is Qwt and Qchart
If you have multiple inputs as text in a form or a table that you need to iterate through, I did this:
var $list = $("#tableOrForm :input[type='text']");
$list.each(function(){
// Go on with your code.
});
What I did was I checked each input to see if the type is set to "text", then it'll grab that element and store it in the jQuery list. Then, it would iterate through that list. You can set a temp variable for the current iteration like this:
var $currentItem = $(this);
This will set the current item to the current iteration of your for each loop. Then you can do whatever you want with the temp variable.
Hope this helps anyone!
This is a common question in C++ programming. There are two valid answers to this. There are advantages and disadvantages to both answers and your choice will depend on context. The common answer is to put all the implementation in the header file, but there's another approach will will be suitable in some cases. The choice is yours.
The code in a template is merely a 'pattern' known to the compiler. The compiler won't compile the constructors cola<float>::cola(...)
and cola<string>::cola(...)
until it is forced to do so. And we must ensure that this compilation happens for the constructors at least once in the entire compilation process, or we will get the 'undefined reference' error. (This applies to the other methods of cola<T>
also.)
The problem is caused by the fact that main.cpp
and cola.cpp
will be compiled separately first. In main.cpp
, the compiler will implicitly instantiate the template classes cola<float>
and cola<string>
because those particular instantiations are used in main.cpp
. The bad news is that the implementations of those member functions are not in main.cpp
, nor in any header file included in main.cpp
, and therefore the compiler can't include complete versions of those functions in main.o
. When compiling cola.cpp
, the compiler won't compile those instantiations either, because there are no implicit or explicit instantiations of cola<float>
or cola<string>
. Remember, when compiling cola.cpp
, the compiler has no clue which instantiations will be needed; and we can't expect it to compile for every type in order to ensure this problem never happens! (cola<int>
, cola<char>
, cola<ostream>
, cola< cola<int> >
... and so on ...)
The two answers are:
cola.cpp
, which particular template classes will be required, forcing it to compile cola<float>
and cola<string>
.main.cpp
) uses the template class.At the end of cola.cpp
, you should add lines explicitly instantiating all the relevant templates, such as
template class cola<float>;
template class cola<string>;
and you add the following two lines at the end of nodo_colaypila.cpp
:
template class nodo_colaypila<float>;
template class nodo_colaypila<std :: string>;
This will ensure that, when the compiler is compiling cola.cpp
that it will explicitly compile all the code for the cola<float>
and cola<string>
classes. Similarly, nodo_colaypila.cpp
contains the implementations of the nodo_colaypila<...>
classes.
In this approach, you should ensure that all the of the implementation is placed into one .cpp
file (i.e. one translation unit) and that the explicit instantation is placed after the definition of all the functions (i.e. at the end of the file).
The common answer is to move all the code from the implementation files cola.cpp
and nodo_colaypila.cpp
into cola.h
and nodo_colaypila.h
. In the long run, this is more flexible as it means you can use extra instantiations (e.g. cola<char>
) without any more work. But it could mean the same functions are compiled many times, once in each translation unit. This is not a big problem, as the linker will correctly ignore the duplicate implementations. But it might slow down the compilation a little.
The default answer, used by the STL for example and in most of the code that any of us will write, is to put all the implementations in the header files. But in a more private project, you will have more knowledge and control of which particular template classes will be instantiated. In fact, this 'bug' might be seen as a feature, as it stops users of your code from accidentally using instantiations you have not tested for or planned for ("I know this works for cola<float>
and cola<string>
, if you want to use something else, tell me first and will can verify it works before enabling it.").
Finally, there are three other minor typos in the code in your question:
#endif
at the end of nodo_colaypila.hnodo_colaypila<T>* ult, pri;
should be nodo_colaypila<T> *ult, *pri;
- both are pointers.nodo_colaypila.h
, not in this implementation file.This helps for HTML5 SQLite:
tx.executeSql('SELECT name, sql FROM sqlite_master WHERE type="table" AND name = "your_table_name";', [], function (tx, results) {
var columnParts = results.rows.item(0).sql.replace(/^[^\(]+\(([^\)]+)\)/g, '$1').split(','); ///// RegEx
var columnNames = [];
for(i in columnParts) {
if(typeof columnParts[i] === 'string')
columnNames.push(columnParts[i].split(" ")[0]);
}
console.log(columnNames);
///// Your code which uses the columnNames;
});
You can reuse the regex in your language to get the column names.
Shorter Alternative:
tx.executeSql('SELECT name, sql FROM sqlite_master WHERE type="table" AND name = "your_table_name";', [], function (tx, results) {
var columnNames = results.rows.item(0).sql.replace(/^[^\(]+\(([^\)]+)\)/g, '$1').replace(/ [^,]+/g, '').split(',');
console.log(columnNames);
///// Your code which uses the columnNames;
});
Because userString is empty. You only declare it
vector<string> userString;
but never add anything, so the for loop won't even run.
Furthermore, you also have ||
which is the logical or, and also ;
which is just a separator which doesn't care what happend to the command before.
$ false || echo "Oops, fail"
Oops, fail
$ true || echo "Will not be printed"
$
$ true && echo "Things went well"
Things went well
$ false && echo "Will not be printed"
$
$ false ; echo "This will always run"
This will always run
Some details about this can be found here Lists of Commands in the Bash Manual.
Try something like this... jsfiddle demo
HTML
<!-- Source: -->
<select id="source" name="source">
<option>MANUAL</option>
<option>ONLINE</option>
</select>
<!-- Status: -->
<select id="status" name="status">
<option>OPEN</option>
<option>DELIVERED</option>
</select>
JS
$(document).ready(function () {
$("#source").change(function () {
var el = $(this);
if (el.val() === "ONLINE") {
$("#status").append("<option>SHIPPED</option>");
} else if (el.val() === "MANUAL") {
$("#status option:last-child").remove();
}
});
});
Before proceeding, ensure that you: Have completed a full database backup!
Step 1: Database Level Changes
Identifying the Collation and Character set of your database
SELECT DEFAULT_CHARACTER_SET_NAME, DEFAULT_COLLATION_NAME FROM
information_schema.SCHEMATA S
WHERE schema_name = 'your_database_name'
AND
(DEFAULT_CHARACTER_SET_NAME != 'utf8'
OR
DEFAULT_COLLATION_NAME not like 'utf8%');
Fixing the collation for the database
ALTER DATABASE databasename CHARACTER SET utf8 COLLATE utf8_unicode_ci;
Step 2: Table Level Changes
Identifying Database Tables with the incorrect character set or collation
SELECT CONCAT(
'ALTER TABLE ', table_name, ' CHARACTER SET utf8 COLLATE utf8_general_ci; ',
'ALTER TABLE ', table_name, ' CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci; ')
FROM information_schema.TABLES AS T, information_schema.`COLLATION_CHARACTER_SET_APPLICABILITY` AS C
WHERE C.collation_name = T.table_collation
AND T.table_schema = 'your_database_name'
AND
(C.CHARACTER_SET_NAME != 'utf8'
OR
C.COLLATION_NAME not like 'utf8%')
Adjusting table columns' collation and character set
Capture upper sql output and run it. (like following)
ALTER TABLE rma CHARACTER SET utf8 COLLATE utf8_general_ci;ALTER TABLE rma CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci;
ALTER TABLE rma_history CHARACTER SET utf8 COLLATE utf8_general_ci;ALTER TABLE rma_history CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci;
ALTER TABLE rma_products CHARACTER SET utf8 COLLATE utf8_general_ci;ALTER TABLE rma_products CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci;
ALTER TABLE rma_report_period CHARACTER SET utf8 COLLATE utf8_general_ci;ALTER TABLE rma_report_period CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci;
ALTER TABLE rma_reservation CHARACTER SET utf8 COLLATE utf8_general_ci;ALTER TABLE rma_reservation CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci;
ALTER TABLE rma_supplier_return CHARACTER SET utf8 COLLATE utf8_general_ci;ALTER TABLE rma_supplier_return CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci;
ALTER TABLE rma_supplier_return_history CHARACTER SET utf8 COLLATE utf8_general_ci;ALTER TABLE rma_supplier_return_history CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci;
ALTER TABLE rma_supplier_return_product CHARACTER SET utf8 COLLATE utf8_general_ci;ALTER TABLE rma_supplier_return_product CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci;
const tifOptions = [];
for (const [key, value] of Object.entries(tifs)) {
tifOptions.push(<option value={key} key={key}>{value}</option>);
}
return (
<select id="tif" name="tif" onChange={this.handleChange}>
{ tifOptions }
</select>
)
Since the value of $var
is the empty string, this:
if [ $var == $var1 ]; then
expands to this:
if [ == abcd ]; then
which is a syntax error.
You need to quote the arguments:
if [ "$var" == "$var1" ]; then
You can also use =
rather than ==
; that's the original syntax, and it's a bit more portable.
If you're using bash, you can use the [[
syntax, which doesn't require the quotes:
if [[ $var = $var1 ]]; then
Even then, it doesn't hurt to quote the variable reference, and adding quotes:
if [[ "$var" = "$var1" ]]; then
might save a future reader a moment trying to remember whether [[
... ]]
requires them.
PHP will work only on the .php
file extension.
If you are on Apache you can also set, in your httpd.conf
file, the extensions for PHP. You'll have to find the line:
AddType application/x-httpd-php .php .html
^^^^^
and add how many extensions, that should be read with the PHP interpreter, as you want.
A thread safe rotation function is the following (it works much better):
-(UIImage*)imageByRotatingImage:(UIImage*)initImage fromImageOrientation:(UIImageOrientation)orientation
{
CGImageRef imgRef = initImage.CGImage;
CGFloat width = CGImageGetWidth(imgRef);
CGFloat height = CGImageGetHeight(imgRef);
CGAffineTransform transform = CGAffineTransformIdentity;
CGRect bounds = CGRectMake(0, 0, width, height);
CGSize imageSize = CGSizeMake(CGImageGetWidth(imgRef), CGImageGetHeight(imgRef));
CGFloat boundHeight;
UIImageOrientation orient = orientation;
switch(orient) {
case UIImageOrientationUp: //EXIF = 1
return initImage;
break;
case UIImageOrientationUpMirrored: //EXIF = 2
transform = CGAffineTransformMakeTranslation(imageSize.width, 0.0);
transform = CGAffineTransformScale(transform, -1.0, 1.0);
break;
case UIImageOrientationDown: //EXIF = 3
transform = CGAffineTransformMakeTranslation(imageSize.width, imageSize.height);
transform = CGAffineTransformRotate(transform, M_PI);
break;
case UIImageOrientationDownMirrored: //EXIF = 4
transform = CGAffineTransformMakeTranslation(0.0, imageSize.height);
transform = CGAffineTransformScale(transform, 1.0, -1.0);
break;
case UIImageOrientationLeftMirrored: //EXIF = 5
boundHeight = bounds.size.height;
bounds.size.height = bounds.size.width;
bounds.size.width = boundHeight;
transform = CGAffineTransformMakeTranslation(imageSize.height, imageSize.width);
transform = CGAffineTransformScale(transform, -1.0, 1.0);
transform = CGAffineTransformRotate(transform, 3.0 * M_PI / 2.0);
break;
case UIImageOrientationLeft: //EXIF = 6
boundHeight = bounds.size.height;
bounds.size.height = bounds.size.width;
bounds.size.width = boundHeight;
transform = CGAffineTransformMakeTranslation(0.0, imageSize.width);
transform = CGAffineTransformRotate(transform, 3.0 * M_PI / 2.0);
break;
case UIImageOrientationRightMirrored: //EXIF = 7
boundHeight = bounds.size.height;
bounds.size.height = bounds.size.width;
bounds.size.width = boundHeight;
transform = CGAffineTransformMakeScale(-1.0, 1.0);
transform = CGAffineTransformRotate(transform, M_PI / 2.0);
break;
case UIImageOrientationRight: //EXIF = 8
boundHeight = bounds.size.height;
bounds.size.height = bounds.size.width;
bounds.size.width = boundHeight;
transform = CGAffineTransformMakeTranslation(imageSize.height, 0.0);
transform = CGAffineTransformRotate(transform, M_PI / 2.0);
break;
default:
[NSException raise:NSInternalInconsistencyException format:@"Invalid image orientation"];
}
// Create the bitmap context
CGContextRef context = NULL;
void * bitmapData;
int bitmapByteCount;
int bitmapBytesPerRow;
// Declare the number of bytes per row. Each pixel in the bitmap in this
// example is represented by 4 bytes; 8 bits each of red, green, blue, and
// alpha.
bitmapBytesPerRow = (bounds.size.width * 4);
bitmapByteCount = (bitmapBytesPerRow * bounds.size.height);
bitmapData = malloc( bitmapByteCount );
if (bitmapData == NULL)
{
return nil;
}
// Create the bitmap context. We want pre-multiplied ARGB, 8-bits
// per component. Regardless of what the source image format is
// (CMYK, Grayscale, and so on) it will be converted over to the format
// specified here by CGBitmapContextCreate.
CGColorSpaceRef colorspace = CGImageGetColorSpace(imgRef);
context = CGBitmapContextCreate (bitmapData,bounds.size.width,bounds.size.height,8,bitmapBytesPerRow,
colorspace, kCGBitmapAlphaInfoMask & kCGImageAlphaPremultipliedLast);
if (context == NULL)
// error creating context
return nil;
CGContextScaleCTM(context, -1.0, -1.0);
CGContextTranslateCTM(context, -bounds.size.width, -bounds.size.height);
CGContextConcatCTM(context, transform);
// Draw the image to the bitmap context. Once we draw, the memory
// allocated for the context for rendering will then contain the
// raw image data in the specified color space.
CGContextDrawImage(context, CGRectMake(0,0,width, height), imgRef);
CGImageRef imgRef2 = CGBitmapContextCreateImage(context);
CGContextRelease(context);
free(bitmapData);
UIImage * image = [UIImage imageWithCGImage:imgRef2 scale:initImage.scale orientation:UIImageOrientationUp];
CGImageRelease(imgRef2);
return image;
}