Try with this code:
return View::make('user/regprofile', array
(
'students' => $students
)
);
Or if you want to pass more variables into view:
return View::make('user/regprofile', array
(
'students' => $students,
'variable_1' => $variable_1,
'variable_2' => $variable_2
)
);
The ideal scenario is to have <add value="default.aspx" />
in config so the application can be deployed to any server without having to reconfigure. IMHO I think the implementation within IIS is poor.
We've used the following to make our default document setup more robust and as a result more SEO friendly by using canonical URL's:
<configuration>
<system.webServer>
<defaultDocument>
<files>
<remove value="default.aspx" />
<add value="default.aspx" />
</files>
</defaultDocument>
</system.webServer>
</configuration>
Works OK for us.
http://graph.facebook.com/517267866/?fields=picture&type=large
Would return the URL in JSON
Let's go to the source -- 2.6.32, for example. The message is printed by show_signal_msg() function in arch/x86/mm/fault.c if the show_unhandled_signals sysctl is set.
"error" is not an errno nor a signal number, it's a "page fault error code" -- see definition of enum x86_pf_error_code.
"[7fa44d2f8000+f6f000]" is starting address and size of virtual memory area where offending object was mapped at the time of crash. Value of "ip" should fit in this region. With this info in hand, it should be easy to find offending code in gdb.
I hope the following code will help or solve your problem or you think not that understandable visit http://phppot.com/jquery/jquery-dependent-dropdown-list-countries-and-states/.
HTML DYNAMIC DEPENDENT SELECT
<div class="frmDronpDown">
<div class="row">
<label>Country:</label><br/>
<select name="country" id="country-list" class="demoInputBox" onChange="getState(this.value);">
<option value="">Select Country</option>
<?php
foreach($results as $country) {
?>
<option value="<?php echo $country["id"]; ?>"><?php echo $country["name"]; ?></option>
<?php
}
?>
</select>
</div>
<div class="row">
<label>State:</label><br/>
<select name="state" id="state-list" class="demoInputBox">
<option value="">Select State</option>
</select>
</div>
GETTING STATES VIA AJAX
<script> function getState(val) { $.ajax({
type: "POST",
url: "get_state.php",
data:'country_id='+val,
success: function(data){
$("#state-list").html(data);
}
});} </script>
READ STATE DATABASE USING PHP
<?php require_once("dbcontroller.php"); $db_handle = new DBController();if(!empty($_POST["country_id"])) {
$query ="SELECT * FROM states WHERE countryID = '" . $_POST["country_id"] . "'";
$results = $db_handle->runQuery($query); ?> <option value="">Select State</option><?php foreach($results as $state) { ?> <option value="<?php echo $state["id"]; ?>"><?php echo $state["name"]; ?></option><?php } } ?>
For me turning on and off the setting on
iOS Simulator -> Hardware -> Keyboard -> Connect Hardware Keyboard
proved to fix the issue on simulators.
Simply remove "DEFINER=your user name
@localhost
" and run the SQL from phpmyadminwill works fine.
I just installed Oracle Instant Client 18_3 with the SDK. The PATH and ENV variable is set as instructed on the install page but I get the OCl.dll not found error. I searched the entire drive recursively and no such DLL exists.
So now what?
With the install instructions (not updated for 18_3) and downloads there are MISTAKES at step 13, so watch out for that.
When you create the folder structure for the downloads just write them the old way "c:\oraclient". Then when you unzip the basic, SDK and instant Client install for Windows 10_x64 extract them to "C:\oraclient\", because they all write to the same default folder. Then, when you set the ENV variable (which is no longer ORACLE_HOME, but now is OCI_LIB64) and the PATH, you will point to "C:\oraclient\instantclient_18_3".
To be sure you got it all right drill down and look for any duplicate "instantclient_18_3" folders. If you do have those cut and paste the CONTENTS to the root folder "C:\oraclient\instantclient_18_3\" folder.
Whoever works on the documentation at Oracle needs to troubleshoot better. I've seen "C:\oreclient_dir_install", "c:\oracle", "c:\oreclient" and "c:\oraclient" all mentioned as install directories, all for Windows x64 installs
BTW, install the C++ redist it helps. The 18.3 Basic package requires the Microsoft Visual Studio 2013 Redistributable.
There are two ways to count total number of records that the query will return. First this
$query = $this->db->query('select blah blah');
return $query->num_rows();
This will return number of rows the query brought.
Second
return $this->db->count_all_results('select blah blah');
Simply count_all_results will require to run the query again.
No there isn't and it's probably not there, because there are very few valid uses for it. I would think twice before using it. Also, it is indeed easy to create yourself.
Please refer to this discussion about why it's even in .NET.
I guess UnsupportedOperationException
comes close, although it doesn't say the operation is just not implemented, but unsupported even. That could imply no valid implementation is possible. Why would the operation be unsupported? Should it even be there?
Interface segregation or Liskov substitution issues maybe?
If it's work in progress I'd go for ToBeImplementedException
, but I've never caught myself defining a concrete method and then leave it for so long it makes it into production and there would be a need for such an exception.
This link contains relevant information on detecting versions of Internet Explorer:
http://tanalin.com/en/articles/ie-version-js/
Example:
if (document.all && !document.addEventListener) {
alert('IE8 or older.');
}
You can simply do:
double approxRollingAverage (double avg, double new_sample) {
avg -= avg / N;
avg += new_sample / N;
return avg;
}
Where N
is the number of samples where you want to average over.
Note that this approximation is equivalent to an exponential moving average.
See: Calculate rolling / moving average in C++
The top answer was correct at the time but is now wrong; you can do it in pure javascript. But the one answer using javascript doesn't work any more, and the other answers are pretty limited or don't use pure javascript.
I made my own solution that works well and lets you control the volume, frequency, and wavetype.
//if you have another AudioContext class use that one, as some browsers have a limit
var audioCtx = new (window.AudioContext || window.webkitAudioContext || window.audioContext);
//All arguments are optional:
//duration of the tone in milliseconds. Default is 500
//frequency of the tone in hertz. default is 440
//volume of the tone. Default is 1, off is 0.
//type of tone. Possible values are sine, square, sawtooth, triangle, and custom. Default is sine.
//callback to use on end of tone
function beep(duration, frequency, volume, type, callback) {
var oscillator = audioCtx.createOscillator();
var gainNode = audioCtx.createGain();
oscillator.connect(gainNode);
gainNode.connect(audioCtx.destination);
if (volume){gainNode.gain.value = volume;}
if (frequency){oscillator.frequency.value = frequency;}
if (type){oscillator.type = type;}
if (callback){oscillator.onended = callback;}
oscillator.start(audioCtx.currentTime);
oscillator.stop(audioCtx.currentTime + ((duration || 500) / 1000));
};
Someone suggested I edit this to note it only works on some browsers. However Audiocontext seems to be supported on all modern browsers, as far as I can tell. It isn't supported on IE, but that has been discontinued by Microsoft. If you have any issues with this on a specific browser please report it.
I faced the exact same problem that java would work but javac would not on a cmd prompt in Windows 8.
The problem occured because I forgot to remove '>'
at the end of the path name, i.e., it was like this:
C:\Program Files\Java\jdk*\bin>
where it was suppose to be like this:
C:\Program Files\Java\jdk*\bin
If you want the sum of all bars to be equal unity, weight each bin by the total number of values:
weights = np.ones_like(myarray) / len(myarray)
plt.hist(myarray, weights=weights)
Hope that helps, although the thread is quite old...
Note for Python 2.x: add casting to float()
for one of the operators of the division as otherwise you would end up with zeros due to integer division
Came across this old question looking for solution myself.
Use psutil:
import psutil
import sys
from subprocess import Popen
for process in psutil.process_iter():
if process.cmdline() == ['python', 'your_script.py']:
sys.exit('Process found: exiting.')
print('Process not found: starting it.')
Popen(['python', 'your_script.py'])
The above answer is useful but in graphs, it is difficult to distinguish between darker gradients of black. One alternative I found is to use gradients of gray colors as follows
palette(gray.colors(10, 0.9, 0.4))
plot(rep(1,10),col=1:10,pch=19,cex=3))
More info on gray scale here.
Added
When I used the code above for different colours like blue and black, the gradients were not that clear.
heat.colors()
seems more useful.
This document has more detailed information and options. pdf
For me this worked:
Downloading the App: https://postgresapp.com/downloads.html
Running commands to configure $PATH - note though that it didn't work for me. https://postgresapp.com/documentation/cli-tools.html
Manually add it to the .bash_profile document:
cd # to get to your home folder
open .bash_profile # to open your bash_profile
In your bash profile add:
# Postgres
export PATH=/Applications/Postgres.app/Contents/Versions/latest/bin
Save the file. Restart the terminal. Type 'psql'. Done.
Short answer: No practical, performance, or storage, difference.
Long answer:
There is essentially no difference (in MySQL) between VARCHAR(3000)
(or any other large limit) and TEXT
. The former will truncate at 3000 characters; the latter will truncate at 65535 bytes. (I make a distinction between bytes and characters because a character can take multiple bytes.)
For smaller limits in VARCHAR
, there are some advantages over TEXT
.
CHARACTER SET
.INDEXes
are limited in how big a column can be indexed. (767 or 3072 bytes; this is version and settings dependent)SELECTs
are handled in two different ways -- MEMORY (faster) or MyISAM (slower). When 'large' columns are involved, the slower technique is automatically picked. (Significant changes coming in version 8.0; so this bullet item is subject to change.)TEXT
datatypes (as opposed to VARCHAR
) jump straight to MyISAM. That is, TINYTEXT
is automatically worse for generated temp tables than the equivalent VARCHAR
. (But this takes the discussion in a third direction!)VARBINARY
is like VARCHAR
; BLOB
is like TEXT
.Rebuttal to other answers
The original question asked one thing (which datatype to use); the accepted answer answered something else (off-record storage). That answer is now out of date.
When this thread was started and answered, there were only two "row formats" in InnoDB. Soon afterwards, two more formats (DYNAMIC
and COMPRESSED
) were introduced.
The storage location for TEXT
and VARCHAR()
is based on size, not on name of datatype. For an updated discussion of on/off-record storage of large text/blob columns, see this .
look at last one
t = pd.DataFrame({'a': range(0, 10000), 'b': range(10000, 20000)})
B = []
C = []
A = time.time()
for i,r in t.iterrows():
C.append((r['a'], r['b']))
B.append(round(time.time()-A,5))
C = []
A = time.time()
for ir in t.itertuples():
C.append((ir[1], ir[2]))
B.append(round(time.time()-A,5))
C = []
A = time.time()
for r in zip(t['a'], t['b']):
C.append((r[0], r[1]))
B.append(round(time.time()-A,5))
C = []
A = time.time()
for r in range(len(t)):
C.append((t.loc[r, 'a'], t.loc[r, 'b']))
B.append(round(time.time()-A,5))
C = []
A = time.time()
[C.append((x,y)) for x,y in zip(t['a'], t['b'])]
B.append(round(time.time()-A,5))
B
0.46424
0.00505
0.00245
0.09879
0.00209
and(re.search("bla_bla_pattern", str_item, re.IGNORECASE) == None)
is working.
As a small helper function:
def rindex(mylist, myvalue):
return len(mylist) - mylist[::-1].index(myvalue) - 1
A UDF will only return a value it won't allow you to change the properties of a cell/sheet/workbook. Move your code to a Worksheet_Change event or similar to change properties.
Eg
Private Sub worksheet_change(ByVal target As Range)
target.Font.Bold = True
End Sub
The easiest way is to use to_datetime
:
df['col'] = pd.to_datetime(df['col'])
It also offers a dayfirst
argument for European times (but beware this isn't strict).
Here it is in action:
In [11]: pd.to_datetime(pd.Series(['05/23/2005']))
Out[11]:
0 2005-05-23 00:00:00
dtype: datetime64[ns]
You can pass a specific format:
In [12]: pd.to_datetime(pd.Series(['05/23/2005']), format="%m/%d/%Y")
Out[12]:
0 2005-05-23
dtype: datetime64[ns]
None of these answer point out an important difference about these two operations. Drop table is an operation that can be rolled back. However, truncate cannot be rolled back ['TRUNCATE TABLE' can be rolled back as well]. In this way dropping a very large table can be very expensive if there are many rows, because they all have to be recorded in a temporary space in case you decide to roll it back.
Usually, if I want to get rid of a large table, I will truncate it, then drop it. This way the data will be nixed without record, and the table can be dropped, and that drop will be very inexpensive because no data needs to be recorded.
It is important to point out though that truncate just deletes data, leaving the table, while drop will, in fact, delete the data and the table itself. (assuming foreign keys don't preclude such an action)
A callback function is simply a function you pass into another function so that function can call it at a later time. This is commonly seen in asynchronous APIs; the API call returns immediately because it is asynchronous, so you pass a function into it that the API can call when it's done performing its asynchronous task.
The simplest example I can think of in JavaScript is the setTimeout()
function. It's a global function that accepts two arguments. The first argument is the callback function and the second argument is a delay in milliseconds. The function is designed to wait the appropriate amount of time, then invoke your callback function.
setTimeout(function () {
console.log("10 seconds later...");
}, 10000);
You may have seen the above code before but just didn't realize the function you were passing in was called a callback function. We could rewrite the code above to make it more obvious.
var callback = function () {
console.log("10 seconds later...");
};
setTimeout(callback, 10000);
Callbacks are used all over the place in Node because Node is built from the ground up to be asynchronous in everything that it does. Even when talking to the file system. That's why a ton of the internal Node APIs accept callback functions as arguments rather than returning data you can assign to a variable. Instead it will invoke your callback function, passing the data you wanted as an argument. For example, you could use Node's fs
library to read a file. The fs
module exposes two unique API functions: readFile
and readFileSync
.
The readFile
function is asynchronous while readFileSync
is obviously not. You can see that they intend you to use the async calls whenever possible since they called them readFile
and readFileSync
instead of readFile
and readFileAsync
. Here is an example of using both functions.
Synchronous:
var data = fs.readFileSync('test.txt');
console.log(data);
The code above blocks thread execution until all the contents of test.txt
are read into memory and stored in the variable data
. In node this is typically considered bad practice. There are times though when it's useful, such as when writing a quick little script to do something simple but tedious and you don't care much about saving every nanosecond of time that you can.
Asynchronous (with callback):
var callback = function (err, data) {
if (err) return console.error(err);
console.log(data);
};
fs.readFile('test.txt', callback);
First we create a callback function that accepts two arguments err
and data
. One problem with asynchronous functions is that it becomes more difficult to trap errors so a lot of callback-style APIs pass errors as the first argument to the callback function. It is best practice to check if err
has a value before you do anything else. If so, stop execution of the callback and log the error.
Synchronous calls have an advantage when there are thrown exceptions because you can simply catch them with a try/catch
block.
try {
var data = fs.readFileSync('test.txt');
console.log(data);
} catch (err) {
console.error(err);
}
In asynchronous functions it doesn't work that way. The API call returns immediately so there is nothing to catch with the try/catch
. Proper asynchronous APIs that use callbacks will always catch their own errors and then pass those errors into the callback where you can handle it as you see fit.
In addition to callbacks though, there is another popular style of API that is commonly used called the promise. If you'd like to read about them then you can read the entire blog post I wrote based on this answer here.
I tested the following batch file on Windows 7 x64/x86 and Windows XP x86 and it's fine, but I haven't tried Windows XP x64 yet, but this will probably work:
If Defined ProgramW6432 (Do x64 stuff or end if you are aiming for x86) else (Do x86 stuff or end if you are aiming for x64)
Delete current line and copy to clipboard:
d + d
Paste After The Cursor
p
Paste Before The Cursor
Shift + p
Select Whole Line (I use this ALL the time)
Shift + v
Then j or k to move down and up respectively
Essentially d + d is the equivalent of Shift + v then d
Here's an answer with optional chaining, and perhaps the smallest isObj
function for this question.
const isObj = o => o?.constructor === Object;_x000D_
_x000D_
// True for this_x000D_
console.log(isObj({})); // object!_x000D_
_x000D_
// False for these_x000D_
console.log(isObj(0)); // number_x000D_
console.log(isObj([])); // array_x000D_
console.log(isObj('lol')); // string_x000D_
console.log(isObj(null)); // null_x000D_
console.log(isObj(undefined)); // undefined_x000D_
console.log(isObj(() => {})); // function_x000D_
console.log(isObj(Object)); // class
_x000D_
//Pour inserer :
$pdf = addslashes(file_get_contents($_FILES['inputname']['tmp_name']));
$filetype = addslashes($_FILES['inputname']['type']);//pour le test
$namepdf = addslashes($_FILES['inputname']['name']);
if (substr($filetype, 0, 11) == 'application'){
$mysqli->query("insert into tablepdf(pdf_nom,pdf)value('$namepdf','$pdf')");
}
//Pour afficher :
$row = $mysqli->query("SELECT * FROM tablepdf where id=(select max(id) from tablepdf)");
foreach($row as $result){
$file=$result['pdf'];
}
header('Content-type: application/pdf');
echo file_get_contents('data:application/pdf;base64,'.base64_encode($file));
There's still no simple answer. It depends on your scenario. MSDN has documentation to help you decide.
There are other options covered here. Instead of storing in the file system directly or in a BLOB, you can use the FileStream or File Table in SQL Server 2012. The advantages to File Table seem like a no-brainier (but admittedly I have no personal first-hand experience with them.)
The article is definitely worth a read.
A class that emulates enum behaviour but using string
instead of int
can be created as follows...
public class GrainType
{
private string _typeKeyWord;
private GrainType(string typeKeyWord)
{
_typeKeyWord = typeKeyWord;
}
public override string ToString()
{
return _typeKeyWord;
}
public static GrainType Wheat = new GrainType("GT_WHEAT");
public static GrainType Corn = new GrainType("GT_CORN");
public static GrainType Rice = new GrainType("GT_RICE");
public static GrainType Barley = new GrainType("GT_BARLEY");
}
Usage...
GrainType myGrain = GrainType.Wheat;
PrintGrainKeyword(myGrain);
then...
public void PrintGrainKeyword(GrainType grain)
{
Console.Writeline("My Grain code is " + grain.ToString()); // Displays "My Grain code is GT_WHEAT"
}
I have faced the similar issue while host the appication in IIS
Solution
I change the Pool Identity and its work me
ApplicationPoolIdentity -> NetworkService
you must have record in table or array record in database.
example:
SELECT * FROM tabel_record
WHERE table_record.fieldName IN (SELECT fieldName FROM table_reference);
You could use a label (see JsFiddle)
CSS
label { display: inline-block; width: 210px; text-align: right; }
HTML
<html>
<label for="name">Name:</label><input id="name" type="text"><br />
<label for="email">Email Address:</label><input id="email" type="text"><br />
<label for="desc">Description of the input value:</label><input id="desc" type="text"><br />
</html>
Or you could use those labels in a table (JsFiddle)
<html>
<table>
<tbody>
<tr><td><label for="name">Name:</label></td><td><input id="name" type="text"></td></tr>
<tr><td><label for="email">Email Address:</label></td><td><input id="email" type = "text"></td></tr>
<tr><td><label for="desc">Description of the input value:</label></td><td><input id="desc" type="text"></td></tr>
</tbody>
</table>
</html>
const page_number = 3;
window.location.hash = page_number as string; // Error
"Conversion of type 'number' to type 'string' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first." -> You will get this error if you try to typecast number to string. So, first convert it to unknown and then to string.
window.location.hash = (page_number as unknown) as string; // Correct way
An excerpt from an apple technical note (Thanks to matthias-bauch)
Xcode includes all your command-line tools. If it is installed on your system, remove it to uninstall your tools.
If your tools were downloaded separately from Xcode, then they are located at
/Library/Developer/CommandLineTools
on your system. Delete the CommandLineTools folder to uninstall them.
you could easily delete using terminal:
Here is an article that explains how to remove the command line tools but do it at your own risk.Try this only if any of the above doesn't work.
Very easy with responsive voice. Just include the js and voila!
<script src='https://code.responsivevoice.org/responsivevoice.js'></script>
<input onclick="responsiveVoice.speak('This is the text you want to speak');" type='button' value=' Play' />
You say you've had problems with Navicat. For the record, I use Navicat and I haven't experienced the issue you describe. You might want to dig around, see if there's a reason for your problem and/or a solution, because given the question asked, my first recommendation would have been Navicat.
But if you want alternative suggestions, here are a few that I know of and have used:
MySQL has its own tool which you can download for free, called MySQL Workbench. Download it from here: http://wb.mysql.com/. My experience is that it's powerful, but I didn't really like the UI. But that's just my personal taste.
Another free program you might want to try is HeidiSQL. It's more similar to Navicat than MySQL Workbench. A colleague of mine loves it.
(interesting to note, by the way, that MariaDB (the forked version of MySQL) is currently shipped with HeidiSQL as its GUI tool)
Finally, if you're running a web server on your machine, there's always the option of a browser-based tool like PHPMyAdmin. It's actually a surprisingly powerful piece of software.
Tried this on my phone and it works perfectly.
Intent intent = new Intent(Intent.ACTION_CALL);
intent.setData(Uri.parse("tel:900..." ));
startActivity(intent);
Add this permission in manifest file.
<uses-permission android:name="android.permission.CALL_PHONE" />
I simply had to add -h localhost
An alternative to cat()
is writeLines()
:
> writeLines("File not supplied.\nUsage: ./program F=filename")
File not supplied.
Usage: ./program F=filename
>
An advantage is that you don't have to remember to append a "\n"
to the string passed to cat()
to get a newline after your message. E.g. compare the above to the same cat()
output:
> cat("File not supplied.\nUsage: ./program F=filename")
File not supplied.
Usage: ./program F=filename>
and
> cat("File not supplied.\nUsage: ./program F=filename","\n")
File not supplied.
Usage: ./program F=filename
>
The reason print()
doesn't do what you want is that print()
shows you a version of the object from the R level - in this case it is a character string. You need to use other functions like cat()
and writeLines()
to display the string. I say "a version" because precision may be reduced in printed numerics, and the printed object may be augmented with extra information, for example.
There is many debuggers with different features, based on which you make choice. My priorities was satisfied with pry-moves which was:
Token: The kind for (keywords,identifier,punctuation character, multi-character operators) is ,simply, a Token.
Pattern: A rule for formation of token from input characters.
Lexeme : Its a sequence of characters in SOURCE PROGRAM matched by a pattern for a token. Basically, its an element of Token.
Given that the XML field is named 'xmlField'...
SELECT
[xmlField].value('(/person//firstName/node())[1]', 'nvarchar(max)') as FirstName,
[xmlField].value('(/person//lastName/node())[1]', 'nvarchar(max)') as LastName
FROM [myTable]
Update all changes you made:
git add -u
The deleted files should change from unstaged (usually red color) to staged (green). Then commit to remove the deleted files:
git commit -m "note"
MapReduce is just a computing framework. HBase has nothing to do with it. That said, you can efficiently put or fetch data to/from HBase by writing MapReduce jobs. Alternatively you can write sequential programs using other HBase APIs, such as Java, to put or fetch the data. But we use Hadoop, HBase etc to deal with gigantic amounts of data, so that doesn't make much sense. Using normal sequential programs would be highly inefficient when your data is too huge.
Coming back to the first part of your question, Hadoop is basically 2 things: a Distributed FileSystem (HDFS) + a Computation or Processing framework (MapReduce). Like all other FS, HDFS also provides us storage, but in a fault tolerant manner with high throughput and lower risk of data loss (because of the replication). But, being a FS, HDFS lacks random read and write access. This is where HBase comes into picture. It's a distributed, scalable, big data store, modelled after Google's BigTable. It stores data as key/value pairs.
Coming to Hive. It provides us data warehousing facilities on top of an existing Hadoop cluster. Along with that it provides an SQL like interface which makes your work easier, in case you are coming from an SQL background. You can create tables in Hive and store data there. Along with that you can even map your existing HBase tables to Hive and operate on them.
While Pig is basically a dataflow language that allows us to process enormous amounts of data very easily and quickly. Pig basically has 2 parts: the Pig Interpreter and the language, PigLatin. You write Pig script in PigLatin and using Pig interpreter process them. Pig makes our life a lot easier, otherwise writing MapReduce is always not easy. In fact in some cases it can really become a pain.
I had written an article on a short comparison of different tools of the Hadoop ecosystem some time ago. It's not an in depth comparison, but a short intro to each of these tools which can help you to get started. (Just to add on to my answer. No self promotion intended)
Both Hive and Pig queries get converted into MapReduce jobs under the hood.
HTH
Don't try to scan text with nextLine(); AFTER using nextInt() with the same scanner! It doesn't work well with Java Scanner, and many Java developers opt to just use another Scanner for integers. You can call these scanners scan1 and scan2 if you want.
I you are using Django then you can consider django-tastypie as an alternative to django-piston. It is easier to tune to non-ORM data sources than piston, and has great documentation.
In your html file:
<a href="contact.html" class="button large hpbottom">Get Started</a>
In your css file:
.hpbottom{
text-align: center;
}
There's a use-debounce
package that you can use with ReactJS hooks.
From package's README:
import { useDebounce } from 'use-debounce';
export default function Input() {
const [text, setText] = useState('Hello');
const [value] = useDebounce(text, 1000);
return (
<div>
<input
defaultValue={'Hello'}
onChange={(e) => {
setText(e.target.value);
}}
/>
<p>Actual value: {text}</p>
<p>Debounce value: {value}</p>
</div>
);
}
As you can see from the example above, it is set up to update the variable value
only once every second (1000 milliseconds).
Without seeing your code, it's hard to answer other than a stab in the dark. I would guess that the string you're passing to encodeURIComponent(), which is the correct method to use, is coming from the result of accessing the innerHTML property. The solution is to get the innerText/textContent property value instead:
var str,
el = document.getElementById("myUrl");
if ("textContent" in el)
str = encodeURIComponent(el.textContent);
else
str = encodeURIComponent(el.innerText);
If that isn't the case, you can use the replace() method to replace the HTML entity:
encodeURIComponent(str.replace(/&/g, "&"));
Update the create
action as below:
def create
...
respond_to do |format|
if @reservation.save
format.html do
redirect_to '/'
end
format.json { render json: @reservation.to_json }
else
format.html { render 'new'} ## Specify the format in which you are rendering "new" page
format.json { render json: @reservation.errors } ## You might want to specify a json format as well
end
end
end
You are using respond_to
method but anot specifying the format in which a new
page is rendered. Hence, the error ActionController::UnknownFormat
.
Comparator<Integer> comparator = new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o2.compareTo(o1);
}
};
// option 1
Integer[] array = new Integer[] { 1, 24, 4, 4, 345 };
Arrays.sort(array, comparator);
// option 2
int[] array2 = new int[] { 1, 24, 4, 4, 345 };
List<Integer>list = Ints.asList(array2);
Collections.sort(list, comparator);
array2 = Ints.toArray(list);
sumr
is implemented in terms of foldRight
:
final def sumr(implicit A: Monoid[A]): A = F.foldRight(self, A.zero)(A.append)
foldRight
is not always tail recursive, so you can overflow the stack if the collection is too long. See Why foldRight and reduceRight are NOT tail recursive? for some more discussion of when this is or isn't true.
I would recommend you use the literal notation, and the \s
character class:
//..
return str.replace(/\s/g, '');
//..
There's a difference between using the character class \s
and just ' '
, this will match a lot more white-space characters, for example '\t\r\n'
etc.., looking for ' '
will replace only the ASCII 32 blank space.
The RegExp
constructor is useful when you want to build a dynamic pattern, in this case you don't need it.
Moreover, as you said, "[\s]+"
didn't work with the RegExp
constructor, that's because you are passing a string, and you should "double escape" the back-slashes, otherwise they will be interpreted as character escapes inside the string (e.g.: "\s" === "s"
(unknown escape)).
If you just want a light theme and aren't particular about the specific color, then you can pass a theme id to the AlertDialog.Builder constructor.
AlertDialog.Builder(this, AlertDialog.THEME_HOLO_LIGHT)...
or
AlertDialog.Builder(this, AlertDialog.THEME_DEVICE_DEFAULT_LIGHT)...
You should add a .gitignore file to your project and add /.idea
to it. You should add each directory / file in one line.
If you have an existing .gitignore file then you should simply add a new line to the file and put /.idea
to the new line.
After that run git rm -r --cached .idea
command.
If you faced an error you can run git rm -r -f --cached .idea
command. After all run git add .
and then git commit -m "Removed .idea directory and added a .gitignore file"
and finally push the changes by running git push
command.
If your images are small, consider storing them as base64 in a plain text field.
The reason is that while base64 has an overhead of 33%, with compression that mostly goes away. (See What is the space overhead of Base64 encoding?) Your database will be bigger, but the packets your webserver sends to the client won't be. In html, you can inline base64 in an <img src=""> tag, which can possibly simplify your app because you won't have to serve up the images as binary in a separate browser fetch. Handling images as text also simplifies things when you have to send/receive json, which doesn't handle binary very well.
Yes, I understand you could store the binary in the database and convert it to/from text on the way in and out of the database, but sometimes ORMs make that a hassle. It can be simpler just to treat it as straight text just like all your other fields.
This is definitely the right way to handle thumbnails.
(OP's images are not small, so this is not really an answer to his question.)
If you don't want to read the whole file into memory at once, you can use a few tricks:
With next(iterator)
you can advance to the next line:
with open("filename.txt") as f:
next(f)
next(f)
next(f)
for line in f:
print(f)
Of course, this is slighly ugly, so itertools has a better way of doing this:
from itertools import islice
with open("filename.txt") as f:
# start at line 17 and never stop (None), until the end
for line in islice(f, 17, None):
print(f)
I encountered the same problem in child components where initially it would have to have the current value of the Subject, then subscribe to the Subject to listen to changes. I just maintain the current value in the Service so it is available for components to access, e.g. :
import {Storage} from './storage';
import {Injectable} from 'angular2/core';
import {Subject} from 'rxjs/Subject';
@Injectable()
export class SessionStorage extends Storage {
isLoggedIn: boolean;
private _isLoggedInSource = new Subject<boolean>();
isLoggedIn = this._isLoggedInSource.asObservable();
constructor() {
super('session');
this.currIsLoggedIn = false;
}
setIsLoggedIn(value: boolean) {
this.setItem('_isLoggedIn', value, () => {
this._isLoggedInSource.next(value);
});
this.isLoggedIn = value;
}
}
A component that needs the current value could just then access it from the service, i.e,:
sessionStorage.isLoggedIn
Not sure if this is the right practice :)
You could do it this way:
res.status(400).json(json_response);
This will set the HTTP status code to 400, it works even in express 4.
Use array_shift
function
$myarray = array_shift($myarray);
This will move array elements one level up and you can access any array element without using [0]
key
echo $myarray['email'];
will show [email protected]
While, i would completely suggest using beautiful-soup in general, if anyone is looking to display the visible parts of a malformed html (e.g. where you have just a segment or line of a web-page) for whatever-reason, the the following will remove content between <
and >
tags:
import re ## only use with malformed html - this is not efficient
def display_visible_html_using_re(text):
return(re.sub("(\<.*?\>)", "",text))
I found some issue about that kind of error
# ===============================
# = DATA SOURCE
# ===============================
# Set here configurations for the database connection
# Connection url for the database please let me know "[email protected]"
spring.datasource.url = jdbc:mysql://localhost:3306/bookstoreapiabc
# Username and secret
spring.datasource.username = root
spring.datasource.password =
# Keep the connection alive if idle for a long time (needed in production)
spring.datasource.testWhileIdle = true
spring.datasource.validationQuery = SELECT 1
# ===============================
# = JPA / HIBERNATE
# ===============================
# Use spring.jpa.properties.* for Hibernate native properties (the prefix is
# stripped before adding them to the entity manager).
# Show or not log for each sql query
spring.jpa.show-sql = true
# Hibernate ddl auto (create, create-drop, update): with "update" the database
# schema will be automatically updated accordingly to java entities found in
# the project
spring.jpa.hibernate.ddl-auto = update
# Allows Hibernate to generate SQL optimized for a particular DBMS
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
Issue no 2.
Your local server has two database server and those database server conflict. this conflict like this mysql server & xampp or lampp or wamp server. Please one of the database like mysql server because xampp or lampp server automatically install mysql server on this machine
I didn't post to answer JeremyRR's questions (as they have already been answered); instead, I posted merely to give a suggestion.
To JeremyRR, you could do this:
{
string someString = "testing";
for(int counter = 0; counter <= 10; counter++)
{
cout << someString;
}
// The variable is in scope.
}
// The variable is no longer in scope.
I don't know if you realize (I didn't when I first started programming), that brackets (as long they are in pairs) can be placed anywhere within the code, not just after "if", "for", "while", etc.
My code compiled in Microsoft Visual C++ 2010 Express, so I know it works; also, I have tried to to use the variable outside of the brackets that it was defined in and I received an error, so I know that the variable was "destroyed".
I don't know if it is bad practice to use this method, as a lot of unlabeled brackets could quickly make the code unreadable, but maybe some comments could clear things up.
Using the for-loop like you have, one way is this:
def altElement(a):
b = []
j = False
for i in a:
j = not j
if j:
b.append(i)
print b
j just keeps switching between 0 and 1 to keep track of when to append an element to b.
Following the suggestion by JiminP....
I made a jsFiddle that will "smoothly" transition between two spans in case anyone is interested in seeing this in action. You have two main options:
The first time you click the button, number 1 above will occur. The second time you click the button, number 2 will occur. (I did this so you can visually compare the two effects.)
Try it Out: http://jsfiddle.net/jWcLz/594/
Details:
Number 1 above (the more difficult effect) is accomplished by positioning the spans directly on top of each other via CSS with absolute positioning. Also, the jQuery animates are not chained together, so that they can execute at the same time.
HTML
<div class="onTopOfEachOther">
<span id='a'>Hello</span>
<span id='b' style="display: none;">Goodbye</span>
</div>
<br />
<br />
<input type="button" id="btnTest" value="Run Test" />
CSS
.onTopOfEachOther {
position: relative;
}
.onTopOfEachOther span {
position: absolute;
top: 0px;
left: 0px;
}
JavaScript
$('#btnTest').click(function() {
fadeSwitchElements('a', 'b');
});
function fadeSwitchElements(id1, id2)
{
var element1 = $('#' + id1);
var element2 = $('#' + id2);
if(element1.is(':visible'))
{
element1.fadeToggle(500);
element2.fadeToggle(500);
}
else
{
element2.fadeToggle(500, function() {
element1.fadeToggle(500);
});
}
}
The difference between a tuple and a class is that a tuple has no property names. This is almost never a good thing, and I would only use a tuple when the arguments are fairly meaningless like in an abstract math formula Eg. abstract calculus over 5,6,7 dimensions might take a tuple for the coordinates.
This was kind of an annoying issue for me. No suggestions seemed to help my particular case, since I needed to include the "non-modular" headers in my individual file header file. The work around I used was sticking the import call in the prefix header file.
The best way I found is, download a dll from here
Then, add the dll to your project.
Then, add code:
[DllImportAttribute("HardwareIDExtractorC.dll")]
public static extern String GetIDESerialNumber(byte DriveNumber);
Then, call the hard disk ID from where you need it
GetIDESerialNumber(0).Replace(" ", string.Empty);
Note: go to properties of the dll in explorer and set "Build action" to "Embedded Resource"
a.btn {
text-decoration: none;
}
In the past, I have found it quite difficult to try to upgrade in-place.
Note: my use-case for Anaconda is as an all-in-one Python environment. I don't bother with separate virtual environments. If you're using conda
to create environments, this may be destructive because conda
creates environments with hard-links inside your Anaconda/envs
directory.
So if you use environments, you may first want to export your environments. After activating your environment, do something like:
conda env export > environment.yml
After backing up your environments (if necessary), you may remove your old Anaconda (it's very simple to uninstall Anaconda):
$ rm -rf ~/anaconda3/
and replace it by downloading the new Anaconda, e.g. Linux, 64 bit:
$ cd ~/Downloads
$ wget https://repo.continuum.io/archive/Anaconda3-4.3.0-Linux-x86_64.sh
(see here for a more recent one),
and then executing it:
$ bash Anaconda3-4.3.0-Linux-x86_64.sh
For Mac (and I assume Linux)...
If the zip archive contains a single file, you can use the bash command funzip
, in conjuction with fread
from the data.table
package:
library(data.table)
dt <- fread("curl http://www.newcl.org/data/zipfiles/a1.zip | funzip")
In cases where the archive contains multiple files, you can use tar
instead to extract a specific file to stdout:
dt <- fread("curl http://www.newcl.org/data/zipfiles/a1.zip | tar -xf- --to-stdout *a1.dat")
In my case, it's because we tried to post a notification without specifying the NotificationChannel
:
public static final String NOTIFICATION_CHANNEL_ID_SERVICE = "com.mypackage.service";
public static final String NOTIFICATION_CHANNEL_ID_TASK = "com.mypackage.download_info";
public void initChannel(){
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
nm.createNotificationChannel(new NotificationChannel(NOTIFICATION_CHANNEL_ID_SERVICE, "App Service", NotificationManager.IMPORTANCE_DEFAULT));
nm.createNotificationChannel(new NotificationChannel(NOTIFICATION_CHANNEL_ID_INFO, "Download Info", NotificationManager.IMPORTANCE_DEFAULT));
}
}
The best place to put above code is in onCreate()
method in the Application
class, so that we just need to declare it once for all:
public class App extends Application {
@Override
public void onCreate() {
super.onCreate();
initChannel();
}
}
After we set this up, we can use notification with the channelId
we just specified:
Intent i = new Intent(this, MainActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pi = PendingIntent.getActivity(this, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID_INFO);
.setContentIntent(pi)
.setWhen(System.currentTimeMillis())
.setContentTitle("VirtualBox.exe")
.setContentText("Download completed")
.setSmallIcon(R.mipmap.ic_launcher);
Then, we can use it to post a notification:
int notifId = 45;
NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
nm.notify(notifId, builder.build());
If you want to use it as foreground service's notification:
startForeground(notifId, builder.build());
This works with Firefox Quantum 60+ and Chrome v72 (2019)
//set a header to instruct the browser to call the page every 30 sec
header("Refresh: 30;");
It does not seem to be NECESSARY to pass the page url as well as the refresh period in order to (re)call the same page. I haven't tried this with Safari/Opera or IE/Edge.
If you want to use a library, a quick google search for csv
and django
reveals two libraries - django-csvimport and django-adaptors. Let's read what they have to say about themselves...
Django adaptor is a tool which allow you to transform easily a CSV/XML file into a python object or a django model instance.
django-csvimport is a generic importer tool to allow the upload of CSV files for populating data.
The first requires you to write a model to match the csv file, while the second is more of a command-line importer, which is a huge difference in the way you work with them, and each is good for a different type of project.
So which one to use? That depends on which of those will be better suited for your project in the long run.
However, you can also avoid a library altogether, by writing your own django script to import your csv file, something along the lines of (warning, pseudo-code ahead):
# open file & create csvreader
import csv, yada yada yada
# import the relevant model
from myproject.models import Foo
#loop:
for line in csv file:
line = parse line to a list
# add some custom validation\parsing for some of the fields
foo = Foo(fieldname1=line[1], fieldname2=line[2] ... etc. )
try:
foo.save()
except:
# if the're a problem anywhere, you wanna know about it
print "there was a problem with line", i
It's super easy. Hell, you can do it interactively through the django shell if it's a one-time import. Just - figure out what you want to do with your project, how many files do you need to handle and then - if you decide to use a library, try figuring out which one better suits your needs.
If you are trying to reference a commit in another repo than the issue is in, you can prefix the commit short hash with reponame@
.
Suppose your commit is in the repo named dev
, and the GitLab issue is in the repo named test
. You can leave a comment on the issue and reference the commit by dev@e9c11f0a
(where e9c11f0a is the first 8 letters of the sha hash of the commit you want to link to) if that makes sense.
In XML you can add this line to the EditText
View
where 140 is the maximum number of characters:
android:maxLength="140"
We can catch all the clicks. The idea is to reset focus on an element outside the iFrame after each click:
<input type="text" style="position:fixed;top:-1000px;left:-1000px">
<div id="message"></div>
<iframe id="iframe" src="//example.com"></iframe>
<script>
focus();
addEventListener('blur', function() {
if(document.activeElement = document.getElementById('iframe')) {
message.innerHTML += 'Clicked';
setTimeout(function () {
document.querySelector("input").focus();
message.innerHTML += ' - Reset focus,';
}, 1000);
}
});
</script>
none of above worked for me , i updated the appCompat - v7 version in my app gradle file from 23 to 25.3.1. helped to make it work for me
nodeName
is the attribute you are looking for. For example:
var elt = document.getElementById('foo');
console.log(elt.nodeName);
Note that nodeName
returns the element name capitalized and without the angle brackets, which means that if you want to check if an element is an <div>
element you could do it as follows:
elt.nodeName == "DIV"
While this would not give you the expected results:
elt.nodeName == "<div>"
I think you can use this way without using any css -
<table>
<tr>
<td>foo</td>
</tr>
<tr>
<td>bar</td>
</tr>
<tr>
<td>baz</td>
</tr>
</table>
Right now you are using block level element that way you are getting unwanted result. So you can you inline element like span, small etc.
<span>foo</span><span>bar</span><span>baz</span>
Think about it from the browser's point of view. For readonly the browser will send in a variable/value pair. For disabled, it won't.
Run this, then look at the URL after you hit submit:
<html>
<form action=foo.html method=get>
<input name=dis type=text disabled value="dis">
<input name=read type=text readonly value="read">
<input name=normal type=text value="normal">
<input type=submit>
</form>
</html>
It's possible in ggplot and you can use scale_date for this task
library(ggplot2)
Lines <- "Date Visits
11/1/2010 696537
11/2/2010 718748
11/3/2010 799355
11/4/2010 805800
11/5/2010 701262
11/6/2010 531579
11/7/2010 690068
11/8/2010 756947
11/9/2010 718757
11/10/2010 701768
11/11/2010 820113
11/12/2010 645259"
dm <- read.table(textConnection(Lines), header = TRUE)
dm <- mutate(dm, Date = as.Date(dm$Date, "%m/%d/%Y"))
ggplot(data = dm, aes(Date, Visits)) +
geom_line() +
scale_x_date(format = "%b %d", major = "1 day")
pluck(column_name)
This method is designed to perform select by a single column as direct SQL query Returns Array with values of the specified column name The values has same data type as column.
Examples:
Person.pluck(:id) # SELECT people.id FROM people
Person.uniq.pluck(:role) # SELECT DISTINCT role FROM people
Person.where(:confirmed => true).limit(5).pluck(:id)
see http://api.rubyonrails.org/classes/ActiveRecord/Calculations.html#method-i-pluck
Its introduced rails 3.2 onwards and accepts only single column. In rails 4, it accepts multiple columns
The manual for GNU Make gives a clear definition for all
in its list of standard targets.
If the author of the Makefile is following that convention then the target all
should:
make
should do the same as make all
.To achieve 1 all
is typically defined as a .PHONY
target that depends on the executable(s) that form the entire program:
.PHONY : all
all : executable
To achieve 2 all
should either be the first target defined in the make file or be assigned as the default goal:
.DEFAULT_GOAL := all
If you're ok with creating class methods and want the characters you chop off, try this:
class String
def chop_multiple(amount)
amount.times.inject([self, '']){ |(s, r)| [s.chop, r.prepend(s[-1])] }
end
end
hello, world = "hello world".chop_multiple 5
hello #=> 'hello '
world #=> 'world'
document.getElementsByClassName('btn-pageMenu')
delivers a nodeList. You should use: document.getElementsByClassName('btn-pageMenu')[0].style.display
(if it's the first element from that list you want to change.
If you want to change style.display
for all nodes loop through the list:
var elems = document.getElementsByClassName('btn-pageMenu');
for (var i=0;i<elems.length;i+=1){
elems[i].style.display = 'block';
}
to be complete: if you use jquery it is as simple as:
?$('.btn-pageMenu').css('display'???????????????????????????,'block');??????
LATEST NEWS
Android Studio has officially come out of beta and been released. It is now the official IDE for Android Development - Eclipse won't be supported anymore. It is definitely the IDE of choice for Android Development. Link to download page: http://developer.android.com/sdk/index.html
NEWS
As of Google I/O 2013, the Android team has moved to IntelliJ Idea with the new Android Studio IDE: http://developer.android.com/sdk/installing/studio.html
Great to see Google endorse Idea. It is safe to say that Android Studio, and thus Idea, will from now on be the definitive IDE for Android development! :D
ORIGINAL ANSWER
IntelliJ now has support for Android. See Enabling Android Support from the JetBrains help page and the Google Code project page for the plugin. The Getting Started wiki page is pretty helpful.
If you are used to IntelliJ, I don't think it would be beneficial to switch IDEs just for Android tools. You can work on Android with any text editor (I use Vim). If you're more productive with a specific environment I don't see why you'd have to learn a new one. Not worth it in my opinion. Plus I'm a big IntelliJ fan. The IntelliJ plugin lets you make apk files and push the app to the emulator, that's all you need for Android app development. I'd say you're safe sticking with IntelliJ.
Update: there is now an official free IDE for IntelliJ android dev! http://blogs.jetbrains.com/idea/2010/10/intellij-idea-10-free-ide-for-android-development/
use labelpad parameter:
pl.xlabel("...", labelpad=20)
or set it after:
ax.xaxis.labelpad = 20
//create a variable that contain your button
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new OnClickListener(){
@Override
//On click function
public void onClick(View view) {
//Create the intent to start another activity
Intent intent = new Intent(view.getContext(), AnotherActivity.class);
startActivity(intent);
}
});
Chiming in a bit late here, but couldn't resist.
You're question is half-flawed. Let me explain:
The first half of your question, on image replacement, is a valid question, and my opinion is that for a logo, a simple image; an alt attribute; and CSS for its positioning are sufficient.
The second half of your question, on the "SEO value" of the H1 for a logo is the wrong approach to deciding on which elements to use for different types of content.
A logo isn't a primary heading, or even a heading at all, and using the H1 element to markup the logo on each page of your site will do (slightly) more harm than good for your rankings. Semantically, headings (H1 - H6) are appropriate for, well, just that: headings and subheadings for content.
In HTML5, more than one heading is allowed per page, but a logo isn't deserving of one of them. Your logo, which might be a fuzzy green widget and some text is in an image off to the side of the header for a reason - it's sort of a "stamp", not a hierarchical element to structure your content. The first (whether you use more depends on your heading hierarchy) H1 of each page of your site should headline its subject matter. The main primary heading of your index page might be 'The Best Source For Fuzzy Green Widgets in NYC'. The primary heading on another page might be 'Shipping Details for Our Fuzzy Widgets'. On another page, it may be 'About Bert's Fuzzy Widgets Inc.'. You get the idea.
Side note: As incredible as it sounds, don't look at the source of Google-owned web properties for examples of correct markup. This is a whole post unto itself.
To get the most "SEO value" out HTML and its elements, take a look at the HTML5 specs, and make make markup decisions based on (HTML) semantics and value to users before search engines, and you'll have better success with your SEO.
I´ve made a different solution, by eliminating the Control characters, which was my original problem.
It is better than putting in a list all the "special but good" chars
char[] arr = str.Where(c => !char.IsControl(c)).ToArray();
str = new string(arr);
it´s simpler, so I think it´s better !
Uninstall any antivirus (Avast, in my case), reboot the system and try install the Intel HAXM again. It works for me.
There are two easy methods:
\
before double quotes.''
instead of "
For example:
System.out.println("\"Hello\"");
System.out.println("''Hello''");
I've been stuck with the same issue, and the preceding answer did not help me (albeit well written).
The solution is here : check your /etc/redis/redis.conf
, and make sure to change the default
bind 127.0.0.1
to
bind 0.0.0.0
Then restart your service (service redis-server restart
)
You can then now check that redis is listening on non-local interface with
redis-cli -h 192.168.x.x ping
(replace 192.168.x.x with your IP adress)
Important note : as several users stated, it is not safe to set this on a server which is exposed to the Internet. You should be certain that you redis is protected with any means that fits your needs.
I have use mkcert to create infinites *.dev.net subdomains & localhost with valid HTTPS/SSL certs (Windows 10 XAMPP & Linux Debian 10 Apache2)
I create the certs on Windows with mkcert v1.4.0 (execute CMD as Administrator):
mkcert -install
mkcert localhost "*.dev.net"
This create in Windows 10 this files (I will install it first in Windows 10 XAMPP)
localhost+1.pem
localhost+1-key.pem
Overwrite the XAMPP default certs:
copy "localhost+1.pem" C:\xampp\apache\conf\ssl.crt\server.crt
copy "localhost+1-key.pem" C:\xampp\apache\conf\ssl.key\server.key
Now, in Apache2 for Debian 10, activate SSL & vhost_alias
a2enmod vhosts_alias
a2enmod ssl
a2ensite default-ssl
systemctl restart apache2
For vhost_alias add this Apache2 config:
nano /etc/apache2/sites-available/999-vhosts_alias.conf
With this content:
<VirtualHost *:80>
UseCanonicalName Off
ServerAlias *.dev.net
VirtualDocumentRoot "/var/www/html/%0/"
</VirtualHost>
Add the site:
a2ensite 999-vhosts_alias
Copy the certs to /root/mkcert by SSH and let overwrite the Debian ones:
systemctl stop apache2
mv /etc/ssl/certs/ssl-cert-snakeoil.pem /etc/ssl/certs/ssl-cert-snakeoil.pem.bak
mv /etc/ssl/private/ssl-cert-snakeoil.key /etc/ssl/private/ssl-cert-snakeoil.key.bak
cp "localhost+1.pem" /etc/ssl/certs/ssl-cert-snakeoil.pem
cp "localhost+1-key.pem" /etc/ssl/private/ssl-cert-snakeoil.key
chown root:ssl-cert /etc/ssl/private/ssl-cert-snakeoil.key
chmod 640 /etc/ssl/private/ssl-cert-snakeoil.key
systemctl start apache2
Edit the SSL config
nano /etc/apache2/sites-enabled/default-ssl.conf
At the start edit the file with this content:
<IfModule mod_ssl.c>
<VirtualHost *:443>
UseCanonicalName Off
ServerAlias *.dev.net
ServerAdmin webmaster@localhost
# DocumentRoot /var/www/html/
VirtualDocumentRoot /var/www/html/%0/
...
Last restart:
systemctl restart apache2
NOTE: don´t forget to create the folders for your subdomains in /var/www/html/
/var/www/html/subdomain1.dev.net
/var/www/html/subdomain2.dev.net
/var/www/html/subdomain3.dev.net
I would apply this rule to all input fields of type text, so it doesn't need to be duplicated later:
input[type=text]::-ms-clear { display: none; }
One can even get less specific by using just:
::-ms-clear { display: none; }
I have used the later even before adding this answer, but thought that most people would prefer to be more specific than that. Both solutions work fine.
By default the @Transactional
attribute works only when calling an annotated method on a reference obtained from applicationContext.
public class Bean {
public void doStuff() {
doTransactionStuff();
}
@Transactional
public void doTransactionStuff() {
}
}
This will open a transaction:
Bean bean = (Bean)appContext.getBean("bean");
bean.doTransactionStuff();
This will not:
Bean bean = (Bean)appContext.getBean("bean");
bean.doStuff();
Spring Reference: Using @Transactional
Note: In proxy mode (which is the default), only 'external' method calls coming in through the proxy will be intercepted. This means that 'self-invocation', i.e. a method within the target object calling some other method of the target object, won't lead to an actual transaction at runtime even if the invoked method is marked with
@Transactional
!Consider the use of AspectJ mode (see below) if you expect self-invocations to be wrapped with transactions as well. In this case, there won't be a proxy in the first place; instead, the target class will be 'weaved' (i.e. its byte code will be modified) in order to turn
@Transactional
into runtime behavior on any kind of method.
suppose your array :
arr=["1","2","3","4"]
Method to convert array to string:
Array_name.join(",")
Example:
arr.join(",")
Result:
"'1','2','3','4'"
Well the above answers have give a good explanations to half of the question. For the other half.
Why don't just hide the scroll bar itself. This way it will look more appealing as most of the people ( including me ) hate the scroll bar. You can use this code
::-webkit-scrollbar {
width: 0px; /* Remove scrollbar space */
background: transparent; /* Optional: just make scrollbar invisible */
}
I'm running Tomcat 7 in Eclipse with Java 7 and using the jdbc driver for MSSQL sqljdbc4.jar.
When running the code outside of tomcat, from a standalone java app, this worked just fine:
connection = DriverManager.getConnection(conString, user, pw);
However, when I tried to run the same code inside of Tomcat 7, I found that I could only get it work by first registering the driver, changing the above to this:
DriverManager.registerDriver(new com.microsoft.sqlserver.jdbc.SQLServerDriver());
connection = DriverManager.getConnection(conString, user, pw);
When I got an error saying "archive for required library could not be read," I solved it by removing the JARS in question from the Build Path of the project, and then using "Add External Jars" to add them back in again (navigating to the same folder that they were in). Using the "Add Jars" button wouldn't work, and the error would still be there. But using "Add External Jars" worked.
What I tried is to source the location where my files are.
e.g. E:\git_projects\My_project\__init__.py is my location.
I went to File -> Setting -> Project:My_project -> Project Structure and added the content root to about mention place E:\git_projects\My_project
it worked for me.
To read a big file into array you can read line by line or chunk by chunk.
line by line refer to my answer here
var fs = require('fs'),
es = require('event-stream'),
var lines = [];
var s = fs.createReadStream('filepath')
.pipe(es.split())
.pipe(es.mapSync(function(line) {
//pause the readstream
s.pause();
lines.push(line);
s.resume();
})
.on('error', function(err) {
console.log('Error:', err);
})
.on('end', function() {
console.log('Finish reading.');
console.log(lines);
})
);
chunk by chunk refer to this article
var offset = 0;
var chunkSize = 2048;
var chunkBuffer = new Buffer(chunkSize);
var fp = fs.openSync('filepath', 'r');
var bytesRead = 0;
while(bytesRead = fs.readSync(fp, chunkBuffer, 0, chunkSize, offset)) {
offset += bytesRead;
var str = chunkBuffer.slice(0, bytesRead).toString();
var arr = str.split('\n');
if(bytesRead = chunkSize) {
// the last item of the arr may be not a full line, leave it to the next chunk
offset -= arr.pop().length;
}
lines.push(arr);
}
console.log(lines);
Two things:
First, JRE is not the same as the JDK. If you do have the JDK, you need to configure eclipse to point to that in your settings.
Second, in your screenshot above, your compiler compliance level is set to 1.7. This will treat all your code as if it's using Java 1.7. Change this to 1.8 to fix your error.
You will need to have Eclipse Luna in order to get support for Java 8, but you can add it to Kepler SR2 if you want. I'd try with Luna and the above suggestions before you go any further. See this reference.
Once you get Luna, your JAVA_HOME variable should be enough to get Eclipse to recognize JDK 8. If you want to specify an additional JDK, you can add a new Java System Library by going to:
Project -> Properties -> Java Build Path -> Libraries -> Add Library -> Java System Library
and navigating to a valid location for the JDK 8.
You can download your platform's JDK 8 here
$('#navigation ul li').css({'display' : 'inline-block'});
It seems a typo there ...syntax mistake :))
Code Example : Reading data from DataGridView and storing it in an array
int[,] n = new int[3, 19];
for (int i = 0; i < (StartDataView.Rows.Count - 1); i++)
{
for (int j = 0; j < StartDataView.Columns.Count; j++)
{
if(this.StartDataView.Rows[i].Cells[j].Value.ToString() != string.Empty)
{
try
{
n[i, j] = int.Parse(this.StartDataView.Rows[i].Cells[j].Value.ToString());
}
catch (Exception Ee)
{ //get exception of "null"
MessageBox.Show(Ee.ToString());
}
}
}
}
The beforeunload
event fires whenever the user leaves your page for any reason.
For example, it will be fired if the user submits a form, clicks a link, closes the window (or tab), or goes to a new page using the address bar, search box, or a bookmark.
You could exclude form submissions and hyperlinks (except from other frames) with the following code:
var inFormOrLink;
$('a').on('click', function() { inFormOrLink = true; });
$('form').on('submit', function() { inFormOrLink = true; });
$(window).on("beforeunload", function() {
return inFormOrLink ? "Do you really want to close?" : null;
})
For jQuery versions older than 1.7, try this:
var inFormOrLink;
$('a').live('click', function() { inFormOrLink = true; });
$('form').bind('submit', function() { inFormOrLink = true; });
$(window).bind("beforeunload", function() {
return inFormOrLink ? "Do you really want to close?" : null;
})
The live
method doesn't work with the submit
event, so if you add a new form, you'll need to bind the handler to it as well.
Note that if a different event handler cancels the submit or navigation, you will lose the confirmation prompt if the window is actually closed later. You could fix that by recording the time in the submit
and click
events, and checking if the beforeunload
happens more than a couple of seconds later.
I had the same problem while I was testing a project and it turned that running Fiddler was the cause for this error..!!
If you are using Fiddler to intercept the http request, shut it down ...
This is one of the many causes for such error.
To fix Fiddler you may need to Reset Fiddler Https Certificates.
How to sum array of object using Javascript
const traveler = [
{ description: 'Senior', Amount: 50},
{ description: 'Senior', Amount: 50},
{ description: 'Adult', Amount: 75},
{ description: 'Child', Amount: 35},
{ description: 'Infant', Amount: 25 }
];
const traveler = [_x000D_
{ description: 'Senior', Amount: 50},_x000D_
{ description: 'Senior', Amount: 50},_x000D_
{ description: 'Adult', Amount: 75},_x000D_
{ description: 'Child', Amount: 35},_x000D_
{ description: 'Infant', Amount: 25 },_x000D_
];_x000D_
function sum(arrayData, key){_x000D_
return arrayData.reduce((a,b) => {_x000D_
return {Amount : a.Amount + b.Amount}_x000D_
})_x000D_
}_x000D_
console.log(sum(traveler))
_x000D_
Use COALESCE
to avoid that outcome.
SELECT COALESCE(SUM(column),0)
FROM table
WHERE ...
To see it in action, please see this sql fiddle: http://www.sqlfiddle.com/#!2/d1542/3/0
More Information:
Given three tables (one with all numbers, one with all nulls, and one with a mixture):
MySQL 5.5.32 Schema Setup:
CREATE TABLE foo
(
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
val INT
);
INSERT INTO foo (val) VALUES
(null),(1),(null),(2),(null),(3),(null),(4),(null),(5),(null),(6),(null);
CREATE TABLE bar
(
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
val INT
);
INSERT INTO bar (val) VALUES
(1),(2),(3),(4),(5),(6);
CREATE TABLE baz
(
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
val INT
);
INSERT INTO baz (val) VALUES
(null),(null),(null),(null),(null),(null);
Query 1:
SELECT 'foo' as table_name,
'mixed null/non-null' as description,
21 as expected_sum,
COALESCE(SUM(val), 0) as actual_sum
FROM foo
UNION ALL
SELECT 'bar' as table_name,
'all non-null' as description,
21 as expected_sum,
COALESCE(SUM(val), 0) as actual_sum
FROM bar
UNION ALL
SELECT 'baz' as table_name,
'all null' as description,
0 as expected_sum,
COALESCE(SUM(val), 0) as actual_sum
FROM baz
| TABLE_NAME | DESCRIPTION | EXPECTED_SUM | ACTUAL_SUM |
|------------|---------------------|--------------|------------|
| foo | mixed null/non-null | 21 | 21 |
| bar | all non-null | 21 | 21 |
| baz | all null | 0 | 0 |
Converting an int to a byte in Python 3:
n = 5
bytes( [n] )
>>> b'\x05'
;) guess that'll be better than messing around with strings
source: http://docs.python.org/3/library/stdtypes.html#binaryseq
One more thing - if You edited the shell script in some Windows text editor, which produces the \r\n
line-endings, cygwin's bash wouldn't accept those \r
. Just run dos2unix testit.sh
before executing the script:
C:\cygwin\bin\dos2unix testit.sh
C:\cygwin\bin\bash testit.sh
I had a same problem. To solve this problem just open your all files(recent working files) in Which you made the changes and check did you forget to delete some which should be deleted.
In my case the problem was with the Unreferenced code which I was using in one of my file and that code is present in that file which should not be present in that file because I was using an interface which I have deleted from my project but I forget to deleted from one of my file).
I had similar issue. I was not able to use value="something"
to display and edit.
I had to use the below command inside my <input>
along withe ng model being declared.
[(ngModel)]=userDataToPass.pinCode
Where I have the list of data in the object userDataToPass
and the item that I need to display and edit is pinCode
.
For the same , I referred to this YouTube video
Check every each value by a for loop once you checked the size of the array.
function equalArray(a, b) {
if (a.length === b.length) {
for (var i = 0; i < a.length; i++) {
if (a[i] !== b[i]) {
return false;
}
}
return true;
} else {
return false;
}
}
SWIFT 4:
1. Create an @IBAction with segue inside controller you want to unwind to:
@IBAction func unwindToVC(segue: UIStoryboardSegue) {
}
2. In the storyboard, from the controller you want to segue (unwind) from ctrl+drag from the controller sign to exit sign and choose method you created earlier:
3. Now you can notice that in document outline you have new line with title "Unwind segue....". Now you should click on this line and open attribute inspector to set identifier (in my case unwindSegueIdentifier).
4. You're almost done! Now you need to open view controller you wish to unwind from and create some method that will perform segue. For example you can add button, connect it with code with @IBAction, after that inside this IBAction add perfromSegue(withIdentifier:sender:) method:
@IBAction func unwindToSomeVCWithSegue(_ sender: UIButton) {
performSegue(withIdentifier: "unwindSegueIdentifier", sender: nil)
}
So that is all you have to do!
You can also simply create ONLY a UIView in Interface builder and drag & drop the ImageView and UILabel (to make it look like your desired header) and then use that.
Once your UIView looks like the way you want it too, you can programmatically initialize it from the XIB and add to your UITableView. In other words, you dont have to design the ENTIRE table in IB. Just the headerView (this way the header view can be reused in other tables as well)
For example I have a custom UIView for one of my table headers. The view is managed by a xib file called "CustomHeaderView" and it is loaded into the table header using the following code in my UITableViewController subclass:
-(UIView *) customHeaderView {
if (!customHeaderView) {
[[NSBundle mainBundle] loadNibNamed:@"CustomHeaderView" owner:self options:nil];
}
return customHeaderView;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Set the CustomerHeaderView as the tables header view
self.tableView.tableHeaderView = self.customHeaderView;
}
OK, guys, here's my little test too. I had a similar problem, so I decided to test out 3 situations:
All the results were as expected.
Instead of browsing tutorials, I found it easier to try it out, so I did. My conclusion: whenever you include an external JS file in your HTML page, the contents of the external JS gets "copy/pasted" into your HTML page before the page is rendered. Or into your PHP page if you will. Please correct me if I'm wrong here. Thanx.
My example files follow:
EXTERNAL JS:
var global = 0;
function f1()
{
alert('fired: f1');
global = 1;
alert('global changed to 1');
}
function f2()
{
alert('fired f2');
alert('value of global: '+global);
}
HTML 1:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<script type="text/javascript" src="external.js"></script>
<title>External JS Globals - index.php</title>
</head>
<body>
<button type="button" id="button1" onclick="f1();"> fire f1 </button>
<br />
<button type="button" id="button2" onclick="f2();"> fire f2 </button>
<br />
</body>
</html>
HTML 2
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<script type="text/javascript" src="external.js"></script>
<title>External JS Globals - index2.php</title>
</head>
<body>
<button type="button" id="button1" onclick="f1();"> fire f1 </button>
<br />
<button type="button" id="button2" onclick="f2();"> fire f2 </button>
<br />
</body>
</html>
Set seekbar max and min value
seekbar have method that setmax(int position) and setProgress(int position)
thanks
A Jmeter Test Plan must have listener to showcase the result of performance test execution.
Listeners capture the response coming back from Server while Jmeter runs and showcase in the form of – tree, tables, graphs and log files.
It also allows you to save the result in a file for future reference. There are many types of listeners Jmeter provides. Some of them are: Summary Report, Aggregate Report, Aggregate Graph, View Results Tree, View Results in Table etc.
Here is the detailed understanding of each parameter in Summary report.
By referring to the figure:
Label: It is the name/URL for the specific HTTP(s) Request. If you have selected “Include group name in label?” option then the name of the Thread Group is applied as the prefix to each label.
Samples: This indicates the number of virtual users per request.
Average: It is the average time taken by all the samples to execute specific label. In our case, the average time for Label 1 is 942 milliseconds & total average time is 584 milliseconds.
Min: The shortest time taken by a sample for specific label. If we look at Min value for Label 1 then, out of 20 samples shortest response time one of the sample had was 584 milliseconds.
Max: The longest time taken by a sample for specific label. If we look at Max value for Label 1 then, out of 20 samples longest response time one of the sample had was 2867 milliseconds.
Std. Dev.: This shows the set of exceptional cases which were deviating from the average value of sample response time. The lesser this value more consistent the data. Standard deviation should be less than or equal to half of the average time for a label.
Error%: Percentage of Failed requests per Label.
Throughput: Throughput is the number of request that are processed per time unit(seconds, minutes, hours) by the server. This time is calculated from the start of first sample to the end of the last sample. Larger throughput is better.
KB/Sec: This indicates the amount of data downloaded from server during the performance test execution. In short, it is the Throughput measured in Kilobytes per second.
For more information: http://www.testingjournals.com/understand-summary-report-jmeter/
This object provides a sensible implementation of equals(), returning true if equals() is true on each of the contained objects.
If you're using Swift 2, now you can only use print() to write something to the output.
Apple has combined both println() and print() functions into one.
Updated to iOS 9
By default, the function terminates the line it prints by adding a line break.
print("Hello Swift")
Terminator
To print a value without a line break after it, pass an empty string as the terminator
print("Hello Swift", terminator: "")
Separator
You now can use separator to concatenate multiple items
print("Hello", "Swift", 2, separator:" ")
Both
Or you could combine using in this way
print("Hello", "Swift", 2, separator:" ", terminator:".")
This also works for me:-
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "CREATE_DATE_TIME", nullable = false, updatable = false, insertable = false, columnDefinition = "TIMESTAMP DEFAULT CURRENT_TIMESTAMP")
public Date getCreateDateTime() {
return createDateTime;
}
public void setCreateDateTime(Date createDateTime) {
this.createDateTime = createDateTime;
}
In addition to this, due to some recent website hacks we had to secure our sites more. In doing so, we discovered that file_get_contents failed to work, where curl still would work.
Not 100%, but I believe that this php.ini setting may have been blocking the file_get_contents request.
; Disable allow_url_fopen for security reasons
allow_url_fopen = 0
Either way, our code now works with curl.
Something that hasn't been covered in the other answers = if you're using strongly typed C++11 enums, you cannot use ++
or + int
on them. In that case, a bit of a messier solution is required:
enum class myenumtype {
MYENUM_FIRST,
MYENUM_OTHER,
MYENUM_LAST
}
for(myenumtype myenum = myenumtype::MYENUM_FIRST;
myenum != myenumtype::MYENUM_LAST;
myenum = static_cast<myenumtype>(static_cast<int>(myenum) + 1)) {
do_whatever(myenum)
}
The general idea of abstract classes and interfaces is to be extended/implemented by other classes (cannot be constructed alone) that use these general "settings" (some kind of a template), making it simple to set a specific-general behaviour for all the objects that later extend it.
An abstract class has regular methods set AND abstract methods. Extended classes can include unset methods after being extended by an abstract class. When setting abstract methods - they are defined by the classes that are extending it later.
Interfaces have the same properties as an abstract class, but includes only abstract methods, which could be implemented in an other class/es (and can be more than one interface to implement), this creates a more permanent-solid definishion of methods/static variables. Unlike the abstract class, you cannot add custom "regular" methods.
If you are using RC5 then import this:
import { CommonModule } from '@angular/common';
import { BrowserModule } from '@angular/platform-browser';
and be sure to import CommonModule
from the module that is providing your component.
@NgModule({
imports: [CommonModule],
declarations: [MyComponent]
...
})
class MyComponentModule {}
Although it's not really clear to me what you're trying to achieve, I spotted an obvious error in your code:
Field.get()
expects the object which contains the field as argument, not some (possible) value of that field. So you should have field.get(object)
.
Since you appear to be looking for the field value, you can obtain that as:
Object objectValue = field.get(object);
No need to instantiate the field type and create some empty/default value; or maybe there's something I missed.
Schedule provides various ajax behavior events to respond user actions.
there is more in here https://www.primefaces.org/docs/guide/primefaces_user_guide_5_0.pdf
The onclick
attribute on your anchor tag is going to call a client-side function. (This is what you would use if you wanted to call a javascript function when the link is clicked.)
What you want is a server-side control, like the LinkButton
:
<asp:LinkButton ID="lnkTutorial" runat="server" Text="Tutorial" OnClick="displayTutorial_Click"/>
This has an OnClick
attribute that will call the method in your code behind.
Looking further into your code, it looks like you're just trying to open a different tutorial based on access level of the user. You don't need an event handler for this at all. A far better approach would be to just set the end point of your LinkButton
control in the code behind.
protected void Page_Load(object sender, EventArgs e)
{
userinfo = (UserInfo)Session["UserInfo"];
if (userinfo.user == "Admin")
{
lnkTutorial.PostBackUrl = "help/AdminTutorial.html";
}
else
{
lnkTutorial.PostBackUrl = "help/UserTutorial.html";
}
}
Really, it would be best to check that you actually have a user first.
protected void Page_Load(object sender, EventArgs e)
{
if (Session["UserInfo"] != null && ((UserInfo)Session["UserInfo"]).user == "Admin")
{
lnkTutorial.PostBackUrl = "help/AdminTutorial.html";
}
else
{
lnkTutorial.PostBackUrl = "help/UserTutorial.html";
}
}
If this is happening to you with Android 6 and compile target >= 23, don't forget that we are now using runtime permissions. So giving permissions in the manifest is not enough anymore.
you have have strange characters in your heading # % -- or ,
SELECT RTRIM(' Author ') AS Name;
Output will be without any trailing spaces.
Name —————— ‘ Author’
At the risk of sounding obvious, always check the spelling of your forward class files. Sometimes XCode (at least XCode 4.3.2) will turn a declaration green that's actually camel cased incorrectly. Like in this example:
"_OBJC_CLASS_$_RadioKit", referenced from:
objc-class-ref in RadioPlayerViewController.o
If RadioKit was a class file and you make it a property of another file, in the interface declaration, you might see that
Radiokit *rk;
has "Radiokit" in green when the actual decalaration should be:
RadioKit *rk;
This error will also throw this type of error. Another example (in my case), is when you have _iPhone and _iphone extensions on your class names for universal apps. Once I changed the appropriate file from _iphone to the correct _iPhone, the errors went away.
Use putty. Put install directory path in environment values (PATH), and restart your PC if required.
Open cmd (command prompt) and type
C:/> pscp "C:\Users/gsjha/Desktop/example.txt" user@host:/home/
It'll be copied to the system.
This post is right from SAP on Sep 20, 2012.
In short, they are still working on a release of Crystal Reports that will support VS2012 (including support for Windows 8) It will come in the form of a service pack release that updates the version currently supporting VS2010. At that time they will drop 2010/2012 from the name and simply call it Crystal Reports Developer.
If you want to download that version you can find it here.
Further, service packs etc. when released can be found here.
I would also add that I am currently using Visual Studio 2012. As long as you don't edit existing reports they continue to compile and work fine. Even on Windows 8. When I need to modify a report I can still open the project with VS2010, do my work, save my changes, and then switch back to 2012. It's a little bit of a pain but the ability for VS2010 and VS2012 to co-exist is nice in this regard. I'm also using TFS2012 and so far it hasn't had a problem with me modifying files in 2010 on a "2012" solution.
How about this:
def yes(prompt = 'Please enter Yes/No: '):
while True:
try:
i = raw_input(prompt)
except KeyboardInterrupt:
return False
if i.lower() in ('yes','y'): return True
elif i.lower() in ('no','n'): return False
For who are looking for Java Server solution
Here is RestEasy
@GET
@Path("/preference-language")
@Consumes({"application/json", "application/xml"})
@Produces({"application/json", "application/xml"})
public Response getUserLanguagePreference(@Context HttpHeaders headers) {
return Response.status(200)
.entity(headers.getAcceptableLanguages().get(0))
.build();
}
Swift 5
//MARK:- if you are in UITabBarController
self.selectedIndex = 1
or
tabBarController?.selectedIndex = 1
x.transpose[6][3..8]
or x[3..8].map {|r| r [6]}
would give what you want.
Example:
a = [ [1, 2, 3, 4, 5],
[6, 7, 8, 9, 10],
[11, 12, 13, 14, 15],
[21, 22, 23, 24, 25]
]
#a[1..2][2] -> [8,13]
puts a.transpose[2][1..2].inspect # [8,13]
puts a[1..2].map {|r| r[2]}.inspect # [8,13]
JSON.stringify
returns a String
. So, for example:
var data = [
{ id: 1, name: "bob" },
{ id: 2, name: "john" },
{ id: 3, name: "jake" },
];
JSON.stringify(data)
will return the equivalent of:
"[{\"id\":1,\"name\":\"bob\"},{\"id\":2,\"name\":\"john\"},{\"id\":3,\"name\":\"jake\"}]"
as a String
value.
So when you have
<% for(var i=0; i<JSON.stringify(data).length; i++) {%>
what that ends up looking like is:
<% for(var i=0; i<"[{\"id\":1,\"name\":\"bob\"},{\"id\":2,\"name\":\"john\"},{\"id\":3,\"name\":\"jake\"}]".length; i++) {%>
which is probably not what you want. What you probably do want is something like this:
<table>
<% for(var i=0; i < data.length; i++) { %>
<tr>
<td><%= data[i].id %></td>
<td><%= data[i].name %></td>
</tr>
<% } %>
</table>
This will output the following table (using the example data
from above):
<table>
<tr>
<td>1</td>
<td>bob</td>
</tr>
<tr>
<td>2</td>
<td>john</td>
</tr>
<tr>
<td>3</td>
<td>jake</td>
</tr>
</table>
The existing answers show a possible solution for single files or file types. However, you can define the charset standard in VS Code by following this path:
File > Preferences > Settings > Encoding > Choose your option
This will define a character set as default. Besides that, you can always change the encoding in the lower right corner of the editor (blue symbol line) for the current project.
I was getting this issue on WSL on Windows while connecting to AWS instance. My issue got resolved by witching to classic Command prompt. You can try switching to a different terminal interface and see if that helps.
So ... you need to change some things in your code
<form method="POST" id="form-pass">
Password: <input type="text" name="pwd" id="input-pwd">
<input type="submit" value="Submit">
</form>
<script>
var form = document.querySelector('#form-pass');
var pwd = document.querySelector('#input-pwd');
pwd.focus();
form.onsubmit = checkForm;
function checkForm() {
alert(pwd.value);
}
</script>
Try this way.
You can loop through all directories including hidden directrories (beginning with a dot) with:
for file in */ .*/ ; do echo "$file is a directory"; done
note: using the list */ .*/
works in zsh only if there exist at least one hidden directory in the folder. In bash it will show also .
and ..
Another possibility for bash to include hidden directories would be to use:
shopt -s dotglob;
for file in */ ; do echo "$file is a directory"; done
If you want to exclude symlinks:
for file in */ ; do
if [[ -d "$file" && ! -L "$file" ]]; then
echo "$file is a directory";
fi;
done
To output only the trailing directory name (A,B,C as questioned) in each solution use this within the loops:
file="${file%/}" # strip trailing slash
file="${file##*/}" # strip path and leading slash
echo "$file is the directoryname without slashes"
mkdir /tmp/A /tmp/B /tmp/C "/tmp/ dir with spaces"
for file in /tmp/*/ ; do file="${file%/}"; echo "${file##*/}"; done
**Filter by name, age ** also, you can use the map function
difference between map and filter
1. map - The map() method creates a new array with the results of calling a function for every array element. The map method allows items in an array to be manipulated to the user’s preference, returning the conclusion of the chosen manipulation in an entirely new array. For example, consider the following array:
2. filter - The filter() method creates an array filled with all array elements that pass a test implemented by the provided function. The filter method is well suited for particular instances where the user must identify certain items in an array that share a common characteristic. For example, consider the following array:
const users = [
{ name: "john", age: 23 },
{ name: "john", age:43 },
{ name: "jim", age: 101 },
{ name: "bob", age: 67 }
];
const user = _.filter(users, {name: 'jim', age: 101});
console.log(user);
When the file is writing in binary(byte by byte),create FileStream and above solutions Not working,because file is ready and wrotted in every bytes,so in this Situation you need other workaround like this: Do this when file created or you want to start processing on file
long fileSize = 0;
currentFile = new FileInfo(path);
while (fileSize < currentFile.Length)//check size is stable or increased
{
fileSize = currentFile.Length;//get current size
System.Threading.Thread.Sleep(500);//wait a moment for processing copy
currentFile.Refresh();//refresh length value
}
//Now file is ready for any process!
If you don't want to use momentum.js or any other date formating, you can prepend a date format in milliseconds in the date value so that the sort will read according to it's millisecond. And hide the milliseconds date format.
Sample code:
var date = new Date();
var millisecond = Date.parse(date);
HTML
<td>'<span style="display: none;">' + millisecond + "</span>" + date + </td>
That's it.
This one is pretty fast :
select * from listofvalue l
inner join tbl on tbl.mycol like '%' || l.value || '%'
select * from table
where tester NOT LIKE '%username%';
I guess you want to do the "Iterating over Keys and Values"
As the doc here says, just add "|keys" in the variable you want and it will magically happen.
{% for key, user in users %}
<li>{{ key }}: {{ user.username|e }}</li>
{% endfor %}
It never hurts to search before asking :)
The "official" way to get the vs2015 is to go to https://my.visualstudio.com/ ; join the " Visual Studio Dev Essentials" and then search the relevant file to download https://my.visualstudio.com/Downloads?q=Visual%20Studio%202015%20with%20Update%203
with the help of @JsonView we can decide fields of model classes to serialize which satisfy the minimal criteria ( we have to define the criteria) like we can have one core class with 10 properties but only 5 properties can be serialize which are needful for client only
Define our Views by simply creating following class:
public class Views
{
static class Android{};
static class IOS{};
static class Web{};
}
Annotated model class with views:
public class Demo
{
public Demo()
{
}
@JsonView(Views.IOS.class)
private String iosField;
@JsonView(Views.Android.class)
private String androidField;
@JsonView(Views.Web.class)
private String webField;
// getters/setters
...
..
}
Now we have to write custom json converter by simply extending HttpMessageConverter class from spring as:
public class CustomJacksonConverter implements HttpMessageConverter<Object>
{
public CustomJacksonConverter()
{
super();
//this.delegate.getObjectMapper().setConfig(this.delegate.getObjectMapper().getSerializationConfig().withView(Views.ClientView.class));
this.delegate.getObjectMapper().configure(MapperFeature.DEFAULT_VIEW_INCLUSION, true);
this.delegate.getObjectMapper().setSerializationInclusion(Include.NON_NULL);
}
// a real message converter that will respond to methods and do the actual work
private MappingJackson2HttpMessageConverter delegate = new MappingJackson2HttpMessageConverter();
@Override
public boolean canRead(Class<?> clazz, MediaType mediaType) {
return delegate.canRead(clazz, mediaType);
}
@Override
public boolean canWrite(Class<?> clazz, MediaType mediaType) {
return delegate.canWrite(clazz, mediaType);
}
@Override
public List<MediaType> getSupportedMediaTypes() {
return delegate.getSupportedMediaTypes();
}
@Override
public Object read(Class<? extends Object> clazz,
HttpInputMessage inputMessage) throws IOException,
HttpMessageNotReadableException {
return delegate.read(clazz, inputMessage);
}
@Override
public void write(Object obj, MediaType contentType, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException
{
synchronized(this)
{
String userAgent = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getHeader("userAgent");
if ( userAgent != null )
{
switch (userAgent)
{
case "IOS" :
this.delegate.getObjectMapper().setConfig(this.delegate.getObjectMapper().getSerializationConfig().withView(Views.IOS.class));
break;
case "Android" :
this.delegate.getObjectMapper().setConfig(this.delegate.getObjectMapper().getSerializationConfig().withView(Views.Android.class));
break;
case "Web" :
this.delegate.getObjectMapper().setConfig(this.delegate.getObjectMapper().getSerializationConfig().withView( Views.Web.class));
break;
default:
this.delegate.getObjectMapper().setConfig(this.delegate.getObjectMapper().getSerializationConfig().withView( null ));
break;
}
}
else
{
// reset to default view
this.delegate.getObjectMapper().setConfig(this.delegate.getObjectMapper().getSerializationConfig().withView( null ));
}
delegate.write(obj, contentType, outputMessage);
}
}
}
Now there is need to tell spring to use this custom json convert by simply putting this in dispatcher-servlet.xml
<mvc:annotation-driven>
<mvc:message-converters register-defaults="true">
<bean id="jsonConverter" class="com.mactores.org.CustomJacksonConverter" >
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
That's how you will able to decide which fields to get serialize.
Create enviroment variable in your .bashrc
export RUNSERVER_PORT=8010
Create alias
alias runserver='django-admin runserver $RUNSERVER_PORT'
Im using zsh and virtualenvs wrapper. I put export in projects postactivate script and asign port for every project.
workon someproject
runserver
When you are releasing signed apk , please make sure you tick both v1 and v2 in signature versions
Try wrapping the spans in an anchor tag and apply the background image to that.
HTML:
<div class="header">
<a href="/">
<span class="header-title">My gray sea design</span><br />
<span class="header-title-two">A beautiful design</span>
</a>
</div>
CSS:
.header {
border-bottom:1px solid #eaeaea;
}
.header a {
display: block;
background-image: url("./images/embouchure.jpg");
background-repeat: no-repeat;
height:160px;
padding-left:280px;
padding-top:50px;
width:470px;
color: #eaeaea;
}
View On-Device Files with Device File Explorer
https://developer.android.com/studio/debug/device-file-explorer
public String withChars(String inputa) {
String input = inputa.toLowerCase();
StringBuilder sb = new StringBuilder();
final char delim = '_';
char value;
boolean capitalize = false;
for (int i=0; i<input.length(); ++i) {
value = input.charAt(i);
if (value == delim) {
capitalize = true;
}
else if (capitalize) {
sb.append(Character.toUpperCase(value));
capitalize = false;
}
else {
sb.append(value);
}
}
return sb.toString();
}
public String withRegex(String inputa) {
String input = inputa.toLowerCase();
String[] parts = input.split("_");
StringBuilder sb = new StringBuilder();
sb.append(parts[0]);
for (int i=1; i<parts.length; ++i) {
sb.append(parts[i].substring(0,1).toUpperCase());
sb.append(parts[i].substring(1));
}
return sb.toString();
}
Times: in milli seconds.
Iterations = 1000
WithChars: start = 1379685214671 end = 1379685214683 diff = 12
WithRegex: start = 1379685214683 end = 1379685214712 diff = 29
Iterations = 1000
WithChars: start = 1379685217033 end = 1379685217045 diff = 12
WithRegex: start = 1379685217045 end = 1379685217077 diff = 32
Iterations = 1000
WithChars: start = 1379685218643 end = 1379685218654 diff = 11
WithRegex: start = 1379685218655 end = 1379685218684 diff = 29
Iterations = 1000000
WithChars: start = 1379685232767 end = 1379685232968 diff = 201
WithRegex: start = 1379685232968 end = 1379685233649 diff = 681
Iterations = 1000000
WithChars: start = 1379685237220 end = 1379685237419 diff = 199
WithRegex: start = 1379685237419 end = 1379685238088 diff = 669
Iterations = 1000000
WithChars: start = 1379685239690 end = 1379685239889 diff = 199
WithRegex: start = 1379685239890 end = 1379685240585 diff = 695
Iterations = 1000000000
WithChars: start = 1379685267523 end = 1379685397604 diff = 130081
WithRegex: start = 1379685397605 end = 1379685850582 diff = 452977
Simply remove the dot for the relative import and do:
from p_02_paying_debt_off_in_a_year import compute_balance_after
Here is an example to fully programmatically:
I am using the following class vars:
Spinner varSpinner;
List<String> varSpinnerData;
float varScaleX;
float varScaleY;
A - Init and render the Spinner (varRoot is a pointer to my main Activity):
public void renderSpinner() {
List<String> myArraySpinner = new ArrayList<String>();
myArraySpinner.add("red");
myArraySpinner.add("green");
myArraySpinner.add("blue");
varSpinnerData = myArraySpinner;
Spinner mySpinner = new Spinner(varRoot);
varSpinner = mySpinner;
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(varRoot, android.R.layout.simple_spinner_item, myArraySpinner);
spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // The drop down vieww
mySpinner.setAdapter(spinnerArrayAdapter);
B - Resize and Add the Spinner to my View:
FrameLayout.LayoutParams myParamsLayout = new FrameLayout.LayoutParams(
FrameLayout.LayoutParams.MATCH_PARENT,
FrameLayout.LayoutParams.WRAP_CONTENT);
myParamsLayout.gravity = Gravity.NO_GRAVITY;
myParamsLayout.leftMargin = (int) (100 * varScaleX);
myParamsLayout.topMargin = (int) (350 * varScaleY);
myParamsLayout.width = (int) (300 * varScaleX);;
myParamsLayout.height = (int) (60 * varScaleY);;
varLayoutECommerce_Dialogue.addView(mySpinner, myParamsLayout);
C - Make the Click handler and use this to set the font.
mySpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int myPosition, long myID) {
Log.i("renderSpinner -> ", "onItemSelected: " + myPosition + "/" + myID);
((TextView) parentView.getChildAt(0)).setTextColor(Color.GREEN);
((TextView) parentView.getChildAt(0)).setTextSize(TypedValue.COMPLEX_UNIT_PX, (int) (varScaleY * 22.0f) );
((TextView) parentView.getChildAt(0)).setPadding(1,1,1,1);
}
@Override
public void onNothingSelected(AdapterView<?> parentView) {
// your code here
}
});
}
D - Update the Spinner with new data:
private void updateInitSpinners(){
String mySelected = varSpinner.getSelectedItem().toString();
Log.i("TPRenderECommerce_Dialogue -> ", "updateInitSpinners -> mySelected: " + mySelected);
varSpinnerData.clear();
varSpinnerData.add("Hello World");
varSpinnerData.add("Hello World 2");
((BaseAdapter) varSpinner.getAdapter()).notifyDataSetChanged();
varSpinner.invalidate();
varSpinner.setSelection(1);
}
}
What I have not been able to solve in the updateInitSpinners, is to do varSpinner.setSelection(0); and have the custom font settings activated automatically.
UPDATE:
This "ugly" solution solves the varSpinner.setSelection(0); issue, but I am not very happy with it:
private void updateInitSpinners(){
String mySelected = varSpinner.getSelectedItem().toString();
Log.i("TPRenderECommerce_Dialogue -> ", "updateInitSpinners -> mySelected: " + mySelected);
varSpinnerData.clear();
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(varRoot, android.R.layout.simple_spinner_item, varSpinnerData);
spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
varSpinner.setAdapter(spinnerArrayAdapter);
varSpinnerData.add("Hello World");
varSpinnerData.add("Hello World 2");
((BaseAdapter) varSpinner.getAdapter()).notifyDataSetChanged();
varSpinner.invalidate();
varSpinner.setSelection(0);
}
}
Hope this helps......
String Formatting:
a = 6.789809823
print('%.2f' %a)
OR
print ("{0:.2f}".format(a))
Round Function can be used:
print(round(a, 2))
Good thing about round() is that, we can store this result to another variable, and then use it for other purposes.
b = round(a, 2)
print(b)
Please notice that instead of script/runner
, you may have to use rails runner
on new rails environments.
Plotly can do some cool stuffs for you
Produces highly interactive graphs that can be easily embedded withing the HTML pages for your private server or website using its off line API.
Update: I am note sure about its 3D plotting capabilities, for 2D graphs is awesome Thanks
you can give :
select{
position:absolute;
top:50%;
transform: translateY(-50%);
}
and to parent you have to give position:relative. it will work.
Assume Table1 and Table2 have three columns A, B and TimeStamp. I want to insert from Table1 into Table2.
This fails with the timestamp error:
Insert Into Table2
Select Table1.A, Table1.B, Table1.TimeStamp From Table1
This works:
Insert Into Table2
Select Table1.A, Table1.B, null From Table1
First of all, you do not have to develop any form yourself : phpMyAdmin, depending on its configuration (i.e. config.inc.php
) will display an identification form, asking for a login and password.
To get that form, you should not use :
$cfg['Servers'][$i]['auth_type'] = 'config';
But you should use :
$cfg['Servers'][$i]['auth_type'] = 'cookie';
(At least, that's what I have on a server which prompts for login/password, using a form)
For more informations, you can take a look at the documentation :
'config'
authentication ($auth_type = 'config'
) is the plain old way: username and password are stored in config.inc.php.'cookie'
authentication mode ($auth_type = 'cookie'
) as introduced in 2.2.3 allows you to log in as any valid MySQL user with the help of cookies.
Username and password are stored in cookies during the session and password is deleted when it ends.
To send CDATA in a request object use the SoapObject.setInnerText("...");
method.
If you want to look in all tables in all Databases server-wide and get output you can make use of the undocumented sp_MSforeachdb procedure:
sp_MSforeachdb 'SELECT "?" AS DB, * FROM [?].sys.tables WHERE name like ''%Table_Names%'''
I've managed to achieve it with minimal effort (just as simple as with ASP.NET Core).
For that I use OWIN Startup.cs
file and Microsoft.Owin.Security.Jwt
library.
In order for the app to hit Startup.cs
we need to amend Web.config
:
<configuration>
<appSettings>
<add key="owin:AutomaticAppStartup" value="true" />
...
Here's how Startup.cs
should look:
using MyApp.Helpers;
using Microsoft.IdentityModel.Tokens;
using Microsoft.Owin;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.Jwt;
using Owin;
[assembly: OwinStartup(typeof(MyApp.App_Start.Startup))]
namespace MyApp.App_Start
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
app.UseJwtBearerAuthentication(
new JwtBearerAuthenticationOptions
{
AuthenticationMode = AuthenticationMode.Active,
TokenValidationParameters = new TokenValidationParameters()
{
ValidAudience = ConfigHelper.GetAudience(),
ValidIssuer = ConfigHelper.GetIssuer(),
IssuerSigningKey = ConfigHelper.GetSymmetricSecurityKey(),
ValidateLifetime = true,
ValidateIssuerSigningKey = true
}
});
}
}
}
Many of you guys use ASP.NET Core nowadays, so as you can see it doesn't differ a lot from what we have there.
It really got me perplexed first, I was trying to implement custom providers, etc. But I didn't expect it to be so simple. OWIN
just rocks!
Just one thing to mention - after I enabled OWIN Startup NSWag
library stopped working for me (e.g. some of you might want to auto-generate typescript HTTP proxies for Angular app).
The solution was also very simple - I replaced NSWag
with Swashbuckle
and didn't have any further issues.
Ok, now sharing ConfigHelper
code:
public class ConfigHelper
{
public static string GetIssuer()
{
string result = System.Configuration.ConfigurationManager.AppSettings["Issuer"];
return result;
}
public static string GetAudience()
{
string result = System.Configuration.ConfigurationManager.AppSettings["Audience"];
return result;
}
public static SigningCredentials GetSigningCredentials()
{
var result = new SigningCredentials(GetSymmetricSecurityKey(), SecurityAlgorithms.HmacSha256);
return result;
}
public static string GetSecurityKey()
{
string result = System.Configuration.ConfigurationManager.AppSettings["SecurityKey"];
return result;
}
public static byte[] GetSymmetricSecurityKeyAsBytes()
{
var issuerSigningKey = GetSecurityKey();
byte[] data = Encoding.UTF8.GetBytes(issuerSigningKey);
return data;
}
public static SymmetricSecurityKey GetSymmetricSecurityKey()
{
byte[] data = GetSymmetricSecurityKeyAsBytes();
var result = new SymmetricSecurityKey(data);
return result;
}
public static string GetCorsOrigins()
{
string result = System.Configuration.ConfigurationManager.AppSettings["CorsOrigins"];
return result;
}
}
Another important aspect - I sent JWT Token via Authorization header, so typescript code looks for me as follows:
(the code below is generated by NSWag)
@Injectable()
export class TeamsServiceProxy {
private http: HttpClient;
private baseUrl: string;
protected jsonParseReviver: ((key: string, value: any) => any) | undefined = undefined;
constructor(@Inject(HttpClient) http: HttpClient, @Optional() @Inject(API_BASE_URL) baseUrl?: string) {
this.http = http;
this.baseUrl = baseUrl ? baseUrl : "https://localhost:44384";
}
add(input: TeamDto | null): Observable<boolean> {
let url_ = this.baseUrl + "/api/Teams/Add";
url_ = url_.replace(/[?&]$/, "");
const content_ = JSON.stringify(input);
let options_ : any = {
body: content_,
observe: "response",
responseType: "blob",
headers: new HttpHeaders({
"Content-Type": "application/json",
"Accept": "application/json",
"Authorization": "Bearer " + localStorage.getItem('token')
})
};
See headers part - "Authorization": "Bearer " + localStorage.getItem('token')
You can't do that, unless you take the child out of the parent and place it via positioning.
The only way I know and it actually works, is to use a translucid image (.png with transparency) for the parent's background. The only disavantage is that you can't control the opacity via CSS, other than that it works!
First navigate to below location and open it in a text editor
<TOMCAT_HOME>/conf/tomcat-users.xml
For tomcat 7, Add the following xml code somewhere between <tomcat-users>
I find the following solution.
<role rolename="manager-gui"/>
<user username="username" password="password" roles="manager-gui"/>
Now restart the tomcat server.
I hope you find this helpful.
HTML :
<html>
<head>
<link rel = "stylesheet" href = "test.css">
<body>
</body>
<script src = "test.js"></script>
</head>
</html>
JAVASCRIPT :
var tableString = "<table>",
body = document.getElementsByTagName('body')[0],
div = document.createElement('div');
for (row = 1; row < 101; row += 1) {
tableString += "<tr>";
for (col = 1; col < 11; col += 1) {
tableString += "<td>" + "row [" + row + "]" + "col [" + col + "]" + "</td>";
}
tableString += "</tr>";
}
tableString += "</table>";
div.innerHTML = tableString;
body.appendChild(div);
Another answer based on extensions (boy do I miss this in Java):
extension NSData {
func toUtf8() -> String? {
return String(data: self, encoding: NSUTF8StringEncoding)
}
}
Then you can use it:
let data : NSData = getDataFromEpicServer()
let string : String? = data.toUtf8()
Note that the string is optional, the initial NSData
may be unconvertible to Utf8.
Git 2.23 introduces git switch
and git restore
to split the responsibilities of git checkout
Creating a new branch from an existing branch as of git 2.23:
git switch -c my-new-branch
Switched to a new branch 'my-new-branch'
Take a look at this Github blog post explaining the changes in greater detail:
Git 2.23 brings a new pair of experimental commands to the suite of existing ones: git switch and git restore. These two are meant to eventually provide a better interface for the well-known git checkout. The new commands intend to each have a clear separation, neatly divvying up what the many responsibilities of git checkout
This can be caused by SELinux. If you don't want to disable SELinux completely, you need to set the db directory fcontext to httpd_sys_rw_content_t.
semanage fcontext -a -t httpd_sys_rw_content_t "/var/www/railsapp/db(/.*)?"
restorecon -v /var/www/railsapp/db
It's called an initialization list. An initializer list is how you pass arguments to your member variables' constructors and for passing arguments to the parent class's constructor.
If you use =
to assign in the constructor body, first the default constructor is called, then the assignment operator is called. This is a bit wasteful, and sometimes there's no equivalent assignment operator.
Place it in extension and call it like below. It's easy to use throughout the application.
self.getFormattedDate(strDate: "20-March-2019", currentFomat: "dd-MMM-yyyy", expectedFromat: "yyyy-MM-dd")
Implementation
func getFormattedDate(strDate: String , currentFomat:String, expectedFromat: String) -> String{
let dateFormatterGet = DateFormatter()
dateFormatterGet.dateFormat = currentFomat
let date : Date = dateFormatterGet.date(from: strDate) ?? Date()
dateFormatterGet.dateFormat = expectedFromat
return dateFormatterGet.string(from: date)
}
There is a much easier way to run PHP, no configuration needed:
Ctrl+Alt+N
F1
and then select/type Run Code
, Run Code
in editor context menuRun Code
button in editor title menuRun Code
button in context menu of file explorerBesides, you could select part of the PHP code and run the code snippet. Very convenient!
Looking at this official google link: Youtube Live encoder settings, bitrates and resolutions they have this table:
240p 360p 480p 720p 1080p
Resolution 426 x 240 640 x 360 854x480 1280x720 1920x1080
Video Bitrates
Maximum 700 Kbps 1000 Kbps 2000 Kbps 4000 Kbps 6000 Kbps
Recommended 400 Kbps 750 Kbps 1000 Kbps 2500 Kbps 4500 Kbps
Minimum 300 Kbps 400 Kbps 500 Kbps 1500 Kbps 3000 Kbps
It would appear as though this is the case, although the numbers dont sync up to the google table above:
// the bitrates, video width and file names for this clip
bitrates: [
{ url: "bbb-800.mp4", width: 480, bitrate: 800 }, //360p video
{ url: "bbb-1200.mp4", width: 720, bitrate: 1200 }, //480p video
{ url: "bbb-1600.mp4", width: 1080, bitrate: 1600 } //720p video
],
Actually, to query the team_name
, just add it in brackets to the last line. Apart from that, it seems to work on Python 2.7.3 on command line.
from urllib2 import urlopen
import json
url = 'http://openligadb-json.heroku.com/api/teams_by_league_saison?league_saison=2012&league_shortcut=bl1'
response = urlopen(url)
json_obj = json.load(response)
for i in json_obj['team']:
print i['team_name']
I know that the question is too old, anyway:
select a, b from mytable group by a, b
will give your all the combinations.
here the problem is model binding if you specify a class then the model binding can understand it during the post if it an integer or string then you have to specify the [FromBody] to bind it properly.
make the following changes in FormMethod
using (@Html.BeginForm("myMethod", "Home", FormMethod.Post, new { id = @item.JobId })){
}
and inside your home controller for binding the string you should specify [FromBody]
using System.Web.Http;
[HttpPost]
public FileStreamResult myMethod([FromBody]string id)
{
// Set a local variable with the incoming data
string str = id;
}
FromBody is available in System.Web.Http. make sure you have the reference to that class and added it in the cs file.
As explained here, in the context of main
both return
and exit
do the same thing
Q: Why do we need to return
or exit
?
A: To indicate execution status.
In your example even if you didnt have return or exit statements the code would run fine (Assuming everything else is syntactically,etc-ally correct. Also, if (and it should be) main
returns int
you need that return 0
at the end).
But, after execution you don't have a way to find out if your code worked as expected.
You can use the return code of the program (In *nix environments , using $?
) which gives you the code (as set by exit
or return
) . Since you set these codes yourself you understand at which point the code reached before terminating.
You can write return 123
where 123
indicates success in the post execution checks.
Usually, in *nix environments 0
is taken as success and non-zero codes as failures.
Reading quickly through the source it seems that you're not far off. The following link should help (I did something similar but for FTP). For a file send from server to client, you start off with a file instance and an array of bytes. You then read the File into the byte array and write the byte array to the OutputStream which corresponds with the InputStream on the client's side.
http://www.rgagnon.com/javadetails/java-0542.html
Edit: Here's a working ultra-minimalistic file sender and receiver. Make sure you understand what the code is doing on both sides.
package filesendtest;
import java.io.*;
import java.net.*;
class TCPServer {
private final static String fileToSend = "C:\\test1.pdf";
public static void main(String args[]) {
while (true) {
ServerSocket welcomeSocket = null;
Socket connectionSocket = null;
BufferedOutputStream outToClient = null;
try {
welcomeSocket = new ServerSocket(3248);
connectionSocket = welcomeSocket.accept();
outToClient = new BufferedOutputStream(connectionSocket.getOutputStream());
} catch (IOException ex) {
// Do exception handling
}
if (outToClient != null) {
File myFile = new File( fileToSend );
byte[] mybytearray = new byte[(int) myFile.length()];
FileInputStream fis = null;
try {
fis = new FileInputStream(myFile);
} catch (FileNotFoundException ex) {
// Do exception handling
}
BufferedInputStream bis = new BufferedInputStream(fis);
try {
bis.read(mybytearray, 0, mybytearray.length);
outToClient.write(mybytearray, 0, mybytearray.length);
outToClient.flush();
outToClient.close();
connectionSocket.close();
// File sent, exit the main method
return;
} catch (IOException ex) {
// Do exception handling
}
}
}
}
}
package filesendtest;
import java.io.*;
import java.io.ByteArrayOutputStream;
import java.net.*;
class TCPClient {
private final static String serverIP = "127.0.0.1";
private final static int serverPort = 3248;
private final static String fileOutput = "C:\\testout.pdf";
public static void main(String args[]) {
byte[] aByte = new byte[1];
int bytesRead;
Socket clientSocket = null;
InputStream is = null;
try {
clientSocket = new Socket( serverIP , serverPort );
is = clientSocket.getInputStream();
} catch (IOException ex) {
// Do exception handling
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
if (is != null) {
FileOutputStream fos = null;
BufferedOutputStream bos = null;
try {
fos = new FileOutputStream( fileOutput );
bos = new BufferedOutputStream(fos);
bytesRead = is.read(aByte, 0, aByte.length);
do {
baos.write(aByte);
bytesRead = is.read(aByte);
} while (bytesRead != -1);
bos.write(baos.toByteArray());
bos.flush();
bos.close();
clientSocket.close();
} catch (IOException ex) {
// Do exception handling
}
}
}
}
Related
Byte array of unknown length in java
Edit: The following could be used to fingerprint small files before and after transfer (use SHA if you feel it's necessary):
public static String md5String(File file) {
try {
InputStream fin = new FileInputStream(file);
java.security.MessageDigest md5er = MessageDigest.getInstance("MD5");
byte[] buffer = new byte[1024];
int read;
do {
read = fin.read(buffer);
if (read > 0) {
md5er.update(buffer, 0, read);
}
} while (read != -1);
fin.close();
byte[] digest = md5er.digest();
if (digest == null) {
return null;
}
String strDigest = "0x";
for (int i = 0; i < digest.length; i++) {
strDigest += Integer.toString((digest[i] & 0xff)
+ 0x100, 16).substring(1).toUpperCase();
}
return strDigest;
} catch (Exception e) {
return null;
}
}
I understand much better the output of:
git diff <remote-tracking branch> <local branch>
that shows me what is going to be dropped and what is going to be added if I push the local branch. Of course it is the same, just the inverse, but for me is more readable and I'm more confortable looking at what is going to happen.
Lots of good answers had been added. I still want to contribute, might be it will clarify slightly more.
When you pass an instance as an argument to the method it passes the copy
of the instance. Now, if the instance you pass is a value type
(resides in the stack
) you pass the copy of that value, so if you modify it, it won't be reflected in the caller. If the instance is a reference type you pass the copy of the reference(again resides in the stack
) to the object. So you got two references to the same object. Both of them can modify the object. But if within the method body, you instantiate new object your copy of the reference will no longer refer to the original object, it will refer to the new object you just created. So you will end up having 2 references and 2 objects.
When performing certain types of cross-domain AJAX requests, modern browsers that support CORS will insert an extra "preflight" request to determine whether they have permission to perform the action. From example query:
$http.get( ‘https://example.com/api/v1/users/’ +userId,
{params:{
apiKey:’34d1e55e4b02e56a67b0b66’
}
}
);
As a result of this fragment we can see that the address was sent two requests (OPTIONS and GET). The response from the server includes headers confirming the permissibility the query GET. If your server is not configured to process an OPTIONS request properly, client requests will fail. For example:
Access-Control-Allow-Credentials: true
Access-Control-Allow-Headers: accept, origin, x-requested-with, content-type
Access-Control-Allow-Methods: DELETE
Access-Control-Allow-Methods: OPTIONS
Access-Control-Allow-Methods: PUT
Access-Control-Allow-Methods: GET
Access-Control-Allow-Methods: POST
Access-Control-Allow-Orgin: *
Access-Control-Max-Age: 172800
Allow: PUT
Allow: OPTIONS
Allow: POST
Allow: DELETE
Allow: GET
You can change the default with an alter table set default charset
but that won't change the charset of the existing columns. To change that you need to use a alter table modify column
.
Changing the charset of a column only means that it will be able to store a wider range of characters. Your application talks to the db using the mysql client so you may need to change the client encoding as well.
Answer is to add a having clause:
SELECT [columns]
FROM table t1
WHERE value= (select max(value) from table)
AND date = (select MIN(date) from table t2 where t1.value = t2.value)
this should work and gets rid of the neccesity of having an extra sub select in the date clause.
If you don't care about row order (which I don't think you do), then you can use a Linux/FreeBSD/Mac OS X/Cygwin box and do:
$ cat yourfile | sort | uniq > yourfile_nodups
Then open the file again in Notepad++.
You are missing a semicolon at the end of your 'struct' definition.
Also,
*sotrudnik
needs to be
sotrudnik*
Adding "/usr/bin/git" >> Path to Git executable, didn't work for me. Then I deleted the contents of $JENKINS_HOME/fingerprints and restarted Jenkins. The problem goes away.
It's complicated.
First of all, in this code
const p = new Promise((resolve) => {
resolve(4);
});
the type of p
is inferred as Promise<{}>
. There is open issue about this on typescript github, so arguably this is a bug, because obviously (for a human), p
should be Promise<number>
.
Then, Promise<{}>
is compatible with Promise<number>
, because basically the only property a promise has is then
method, and then
is compatible in these two promise types in accordance with typescript rules for function types compatibility. That's why there is no error in whatever1
.
But the purpose of async
is to pretend that you are dealing with actual values, not promises, and then you get the error in whatever2
because {}
is obvioulsy not compatible with number
.
So the async
behavior is the same, but currently some workaround is necessary to make typescript compile it. You could simply provide explicit generic argument when creating a promise like this:
const whatever2 = async (): Promise<number> => {
return new Promise<number>((resolve) => {
resolve(4);
});
};
Power of extension
extension Double {
var asNumber:String {
if self >= 0 {
var formatter = NSNumberFormatter()
formatter.numberStyle = .NoStyle
formatter.percentSymbol = ""
formatter.maximumFractionDigits = 1
return "\(formatter.stringFromNumber(self)!)"
}
return ""
}
}
let velocity:Float = 12.32982342034
println("The velocity is \(velocity.toNumber)")
Output: The velocity is 12.3
On express 3 you can use directly res.json({foo:bar})
res.json({ msgId: msg.fileName })
See the documentation