qid
int64
1
74.7M
question
stringlengths
15
58.3k
date
stringlengths
10
10
metadata
list
response_j
stringlengths
4
30.2k
response_k
stringlengths
11
36.5k
24,545,942
I have a Java application that accepts the user input for the configuration file path.I want this input configuration file path to be passed to my spring applicationContext.xml so that I can create the bean of datasource with the dburl,dbusername and dbpasswd which will be used in further classes of my application. Is there a way to pass the runtime user parameters to the Spring application Context? If yes then how to retrieve it in the applicationContext.xml
2014/07/03
[ "https://Stackoverflow.com/questions/24545942", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3754763/" ]
I agree there so many messages, but I had this below file with my, while developing plugin and I look for the type of `Input parameter first` I got this file from <http://patrickverbeeten.com/Blog/2008/01/25/CRM-40-Plug-in-message-input-parameters> But I have tried to update this file somewhat for CRM 2011: Please download file from: <http://tempsend.com/4C08EE4EA9>
If I understand your question correct you can just do the following: ``` if (context.InputParameters.Contains("Target")) { // Do something with Target } else if (context.InputParameters.Contains(“Relationship”)) { // Do something with Relationship } ``` If you want to confirm that Target is of Entity (I think it always is in the plugin) then I would think you could just do the following: ``` if (context.InputParameters["Target"].GetType() == new Entity().GetType()) { } ```
9,942,871
I was reading **Struts2 in Action**, and it said that if an interceptor **B** fires after interceptor **A**, and **B** determines that control should not be allowed to go to Action (as there might be validation errors as done by **DefaultWorkFLowInterceptor**). It then returns "input"..and the page is rendered to the user. The control then comes back to interceptor **A**, but **A** can't modify the result now, as the page has already been sent to the client. But, since the interceptor **B** returns just a string, the interceptor **A** can simply return another string in its place, and the result changes. **DefaultWorkFLowInterceptor** returns just a string, it doesn't actually write anything to the response stream, so when control goes back to its preceding interceptors, why can't they change the input ?
2012/03/30
[ "https://Stackoverflow.com/questions/9942871", "https://Stackoverflow.com", "https://Stackoverflow.com/users/443259/" ]
Even if you change the result string, its too late since the result has already been rendered to the client (UI). Interceptor calling occurs in reverse order so that any post processing work can be done like cleaning up any resources or writing any critical information. If you are interested to change the result you can use `PreResultListener`.A PreResultListener can affect an action invocation between the interceptor/action phase and the result phase. Typical uses include switching to a different Result or somehow modifying the Result or Action objects before the Result executes. For details refer to the document * [preresultlistener](http://struts.apache.org/2.3.1/docs/preresultlistener.html)
I was under the impression that an interceptor calls another interceptor (and therefore, the string returned by an interceptor is received by its preceding one, which it can modify). Actually, an interceptor calls the invoke method of the **ActionInvocation** class which, in turn calls the next interceptor. This also means that the result string returned by an interceptor will be first received by **ActionInvocation**, which can actually render the response page to the client before passing control to the preceding interceptors.
32,973,937
I have an input file in XML format and it is well formed, with accents well written. The file is created with a PHP script that works fine. But when i read the XML File and write it in another XML using a Java program, it puts strange characters instead of the characters with accents. This is the method that reads the XML File: ``` public static String getArchivo(FileInputStream fileinputstream) { String s = null; try { byte abyte0[] = new byte[1024]; int i = fileinputstream.read(abyte0); if(i != -1) { s = new String(abyte0, 0, i); for(int j = fileinputstream.read(abyte0); j != -1; j = fileinputstream.read(abyte0)) { s = s + new String(abyte0, 0, j); } } } catch(IOException ioexception) { s = null; } return s; } ``` Due to the fact that the file is read byte per byte, How do i replace the "bad" bytes for the correct bytes for the accented characters? If reading files like these byte per byte is not a good idea, how can i do it better? The characters that i need are: á, é, í, ó, ú, Á, É, Í, Ó, Ú, ñ, Ñ and °. Thanks in advance
2015/10/06
[ "https://Stackoverflow.com/questions/32973937", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2988946/" ]
Probably you are reading the file with UTF-8 charset. Special chars are not part of the UTF-8 charset. Change from UTF-8 to UTF-16 Something like ``` InputStream in = ... InputSource is = new InputSource(new InputStreamReader(in, "utf-16")); ``` --- As Jordi correctly said there are no special chars outside of utf-8. So consider the first part as an information for other special chars. Looking deeper at your code I see that you read an int and you convert it to a String. Don't convert it. Read bytes and write bytes to be sure that data will not changed.
When you read the file use encoding utf-8 is best ``` BufferedReader rd = new BufferedReader(new InputStreamReader(is, "utf-8")); ``` In writing also use utf-8 ``` OutputStreamWriter writer = new OutputStreamWriter( new FileOutputStream(filePath, true), "utf-8"); ``` This worked for me. When read file in vi editor or other editor change default encoding into utf-8 > > locale charmap > LANG=en\_US.UTF-8 > > >
32,973,937
I have an input file in XML format and it is well formed, with accents well written. The file is created with a PHP script that works fine. But when i read the XML File and write it in another XML using a Java program, it puts strange characters instead of the characters with accents. This is the method that reads the XML File: ``` public static String getArchivo(FileInputStream fileinputstream) { String s = null; try { byte abyte0[] = new byte[1024]; int i = fileinputstream.read(abyte0); if(i != -1) { s = new String(abyte0, 0, i); for(int j = fileinputstream.read(abyte0); j != -1; j = fileinputstream.read(abyte0)) { s = s + new String(abyte0, 0, j); } } } catch(IOException ioexception) { s = null; } return s; } ``` Due to the fact that the file is read byte per byte, How do i replace the "bad" bytes for the correct bytes for the accented characters? If reading files like these byte per byte is not a good idea, how can i do it better? The characters that i need are: á, é, í, ó, ú, Á, É, Í, Ó, Ú, ñ, Ñ and °. Thanks in advance
2015/10/06
[ "https://Stackoverflow.com/questions/32973937", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2988946/" ]
Works for me using Chaserset ISO 8859-1. Syntax in kotlin: ``` val inputStream : InputStream = FileInputStream(filePath) val json = inputStream.bufferedReader(Charsets.ISO_8859_1).use { it.readText()} ```
When you read the file use encoding utf-8 is best ``` BufferedReader rd = new BufferedReader(new InputStreamReader(is, "utf-8")); ``` In writing also use utf-8 ``` OutputStreamWriter writer = new OutputStreamWriter( new FileOutputStream(filePath, true), "utf-8"); ``` This worked for me. When read file in vi editor or other editor change default encoding into utf-8 > > locale charmap > LANG=en\_US.UTF-8 > > >
53,645,150
trying to get last parameters for further processing, but not able to separate them.
2018/12/06
[ "https://Stackoverflow.com/questions/53645150", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7572710/" ]
it is because you are not initializaing cells array. Just inititalize it to proper size , then it should not be a problem. For example: ``` cells = new Node[5][5]; ```
Just try `ArrayList<ArrayList<Node>>` if you don't know the size of array. ``` private ArrayList<ArrayList<Node>> nodes = new ArrayList<>(); for(int i=0;i<rows;i++){ ArrayList<Node> n = new ArrayList<>(); for(int j=0 ; j<cols;j++){ Node node = new Node(i,j,rows,cols); //throws exception this line n.add(node ) } nodes.add(n); } ``` If you know the size then use `Node[][] nodes = new Node[10][10]`.
31,449,434
What is the best way to handle expired tokens in laravel 5. I mean I have a page and it has some links which perform ajax requests. They work fine when the page is loaded but when I wait for sometime then I get a TOKEN MISMATCH error. Now, I have to refresh the page to make it work again. BUT, I don't want to refresh the page. I want some way to refresh the token or some other work around to make it fix. I hope you got my point.
2015/07/16
[ "https://Stackoverflow.com/questions/31449434", "https://Stackoverflow.com", "https://Stackoverflow.com/users/364300/" ]
**Update 2022;** the `csrf_token()` method will **never** create a *new* token, and it simply loads *existing* CSRF-token from current-session (if any, and returns it). But this *tricks* you into thinking it works, because Laravel increases the life-time of the *existing* CSRF-token, and that each time a request to a CSRF-protected route is made. For an implemention that **really creates new** CSRF-token, see: > > stackoverflow.com/[Get new CSRF token with Ajax?](https://stackoverflow.com/a/57252273/8740349) > > > Original Answer (From 2015) --------------------------- A work around for it, is to actually get the new token every certain time, otherwise you are defeating the purpose of the csrf token: ``` <html> <head> <meta name="csrf_token" content="{{ csrf_token() }}"> </head> <body> <script type="text/javascript"> var csrfToken = $('[name="csrf_token"]').attr('content'); setInterval(refreshToken, 3600000); // 1 hour function refreshToken(){ $.get('refresh-csrf').done(function(data){ csrfToken = data; // the new token }); } setInterval(refreshToken, 3600000); // 1 hour </script> </body> </html> ``` In laravel routes ``` Route::get('refresh-csrf', function(){ return csrf_token(); }); ``` I apologize in case of any syntax errors, haven't used jquery for long time, but i guess you get the idea
I have a simple solution that: * Doesn't require you to extend the session lifetime. * Works with multiple tabs open. * Also works if the session did time out because the device was turned off. in /routes/web.php: ``` $router->get('csrf-token', function() { return request()->session()->token(); }); ``` This simply returns the current csrf token. * In case the token is invalid by the time this route gets called (for example when the device was turned off for a long time), it will return a new token, which was created by starting the session. * In case there still is a valid token, it will be returned. Since calling this route will extend the session, the token lifetime is extended as well. Because this only returns a new token when necessary, there are no problems when having multiple tabs open as described by @Adam. You just need to make sure to call the above route every X minutes (where X is your session lifetime - 5 minutes), and update any `_token` inputs. I do this as follows (i use momentjs and axios here): ``` handleNewCsrfToken(); // Use visbility API to make sure the token gets updated in time, even when the device went to sleep. document.addEventListener('visibilitychange', function() { if (document.visibilityState === 'visible') { setTimeoutToRefreshCsrfToken(); } else if (document.visibilityState === 'hidden') { clearTimeout(refreshCsrfTokenTimeout); } }); function handleNewCsrfToken() { updateCsrfTokenTimeoutTarget(); setTimeoutToRefreshCsrfToken(); } function updateCsrfTokenTimeoutTarget() { csrfTokenTimeoutTarget = moment().add(2, 'hour').subtract(5, 'minute'); } function setTimeoutToRefreshCsrfToken() { refreshCsrfTokenTimeout = setTimeout(refreshCsrfToken, csrfTokenTimeoutTarget.diff()); } function refreshCsrfToken() { axios.get('/csrf-token').then(function(response) { document.getElementsByName('_token').forEach(function(element) { element.value = response.data; handleNewCsrfToken(); }); }); } ```
31,449,434
What is the best way to handle expired tokens in laravel 5. I mean I have a page and it has some links which perform ajax requests. They work fine when the page is loaded but when I wait for sometime then I get a TOKEN MISMATCH error. Now, I have to refresh the page to make it work again. BUT, I don't want to refresh the page. I want some way to refresh the token or some other work around to make it fix. I hope you got my point.
2015/07/16
[ "https://Stackoverflow.com/questions/31449434", "https://Stackoverflow.com", "https://Stackoverflow.com/users/364300/" ]
I have a simple solution that: * Doesn't require you to extend the session lifetime. * Works with multiple tabs open. * Also works if the session did time out because the device was turned off. in /routes/web.php: ``` $router->get('csrf-token', function() { return request()->session()->token(); }); ``` This simply returns the current csrf token. * In case the token is invalid by the time this route gets called (for example when the device was turned off for a long time), it will return a new token, which was created by starting the session. * In case there still is a valid token, it will be returned. Since calling this route will extend the session, the token lifetime is extended as well. Because this only returns a new token when necessary, there are no problems when having multiple tabs open as described by @Adam. You just need to make sure to call the above route every X minutes (where X is your session lifetime - 5 minutes), and update any `_token` inputs. I do this as follows (i use momentjs and axios here): ``` handleNewCsrfToken(); // Use visbility API to make sure the token gets updated in time, even when the device went to sleep. document.addEventListener('visibilitychange', function() { if (document.visibilityState === 'visible') { setTimeoutToRefreshCsrfToken(); } else if (document.visibilityState === 'hidden') { clearTimeout(refreshCsrfTokenTimeout); } }); function handleNewCsrfToken() { updateCsrfTokenTimeoutTarget(); setTimeoutToRefreshCsrfToken(); } function updateCsrfTokenTimeoutTarget() { csrfTokenTimeoutTarget = moment().add(2, 'hour').subtract(5, 'minute'); } function setTimeoutToRefreshCsrfToken() { refreshCsrfTokenTimeout = setTimeout(refreshCsrfToken, csrfTokenTimeoutTarget.diff()); } function refreshCsrfToken() { axios.get('/csrf-token').then(function(response) { document.getElementsByName('_token').forEach(function(element) { element.value = response.data; handleNewCsrfToken(); }); }); } ```
I think the best option is to take the lifetime configuration of the config/session.php file, then the lifetime value multiplied by 60 \* 1000 in the javascript code. Use helper function config() provided by laravel, it might look like this: ``` <script type="text/javascript"> var timeout = ({{config('session.lifetime')}} * 60) * 1000; setTimeout(function() { //reload on current page window.location = ''; }, timeout); </script> ```
31,449,434
What is the best way to handle expired tokens in laravel 5. I mean I have a page and it has some links which perform ajax requests. They work fine when the page is loaded but when I wait for sometime then I get a TOKEN MISMATCH error. Now, I have to refresh the page to make it work again. BUT, I don't want to refresh the page. I want some way to refresh the token or some other work around to make it fix. I hope you got my point.
2015/07/16
[ "https://Stackoverflow.com/questions/31449434", "https://Stackoverflow.com", "https://Stackoverflow.com/users/364300/" ]
Increase the `lifetime` of your sessions. You can do so by editing the `config/session.php` file in your laravel configuration. ``` /* |-------------------------------------------------------------------------- | Session Lifetime |-------------------------------------------------------------------------- | | Here you may specify the number of minutes that you wish the session | to be allowed to remain idle before it expires. If you want them | to immediately expire on the browser closing, set that option. | */ 'lifetime' => 120, ```
Circum-navigating the token is generally accepted as a terrible approach but there are problems with using js timers mentioned above too. js seetTimeout/setInterval is unreliable when the browser tab is either not it focus, minimised or in the case of many users, thier laptop/device is sleeping/closed etc. A better route might be to use a js timer to recalculate the 'time to die' from a datestamp set in a cookie (or meta tag for fussy GDPR no-cookie users). this datestamp will be the realworld (timezoned) time the session will die and is updated every page refresh. This way, it doesn't matter what the browser/device was doing/not doing whilst you were away AND it'll still be acurate for those with 'keep me signed in' etc. The next problem is what to do instead of auto resfreshing the token - present the user with a 're-login in' form (modal/popup) that ajaxes the new token to the page as mentioned above.
31,449,434
What is the best way to handle expired tokens in laravel 5. I mean I have a page and it has some links which perform ajax requests. They work fine when the page is loaded but when I wait for sometime then I get a TOKEN MISMATCH error. Now, I have to refresh the page to make it work again. BUT, I don't want to refresh the page. I want some way to refresh the token or some other work around to make it fix. I hope you got my point.
2015/07/16
[ "https://Stackoverflow.com/questions/31449434", "https://Stackoverflow.com", "https://Stackoverflow.com/users/364300/" ]
a short and fast way.... for handling ajax requests,when token expire : add this script to the end of master layout or your document ``` $(window).load(function(){ $.ajaxSetup({ statusCode: { 419: function(){ location.reload(); } } }); }); ``` and for handling http requests when token expires, create 419.blade.php in this path: \resources\views\errors and add this script to it: ``` <script type="text/javascript"> //reload on current page window.location = ''; </script> ```
I think the best option is to take the lifetime configuration of the config/session.php file, then the lifetime value multiplied by 60 \* 1000 in the javascript code. Use helper function config() provided by laravel, it might look like this: ``` <script type="text/javascript"> var timeout = ({{config('session.lifetime')}} * 60) * 1000; setTimeout(function() { //reload on current page window.location = ''; }, timeout); </script> ```
31,449,434
What is the best way to handle expired tokens in laravel 5. I mean I have a page and it has some links which perform ajax requests. They work fine when the page is loaded but when I wait for sometime then I get a TOKEN MISMATCH error. Now, I have to refresh the page to make it work again. BUT, I don't want to refresh the page. I want some way to refresh the token or some other work around to make it fix. I hope you got my point.
2015/07/16
[ "https://Stackoverflow.com/questions/31449434", "https://Stackoverflow.com", "https://Stackoverflow.com/users/364300/" ]
try this in your main layout file ``` @guest <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" /> <meta http-equiv="Pragma" content="no-cache" /> <meta http-equiv="Expires" content="0" /> <meta http-equiv="refresh" content="{{config('session.lifetime') * 60}}"> @endguest ```
You may try [Caffeine for Laravel package](https://github.com/GeneaLabs/laravel-caffeine) it set an interval then it refresh the token like suggested in some answers also it will be added automatically in every form having csrf token
31,449,434
What is the best way to handle expired tokens in laravel 5. I mean I have a page and it has some links which perform ajax requests. They work fine when the page is loaded but when I wait for sometime then I get a TOKEN MISMATCH error. Now, I have to refresh the page to make it work again. BUT, I don't want to refresh the page. I want some way to refresh the token or some other work around to make it fix. I hope you got my point.
2015/07/16
[ "https://Stackoverflow.com/questions/31449434", "https://Stackoverflow.com", "https://Stackoverflow.com/users/364300/" ]
**Update 2022;** the `csrf_token()` method will **never** create a *new* token, and it simply loads *existing* CSRF-token from current-session (if any, and returns it). But this *tricks* you into thinking it works, because Laravel increases the life-time of the *existing* CSRF-token, and that each time a request to a CSRF-protected route is made. For an implemention that **really creates new** CSRF-token, see: > > stackoverflow.com/[Get new CSRF token with Ajax?](https://stackoverflow.com/a/57252273/8740349) > > > Original Answer (From 2015) --------------------------- A work around for it, is to actually get the new token every certain time, otherwise you are defeating the purpose of the csrf token: ``` <html> <head> <meta name="csrf_token" content="{{ csrf_token() }}"> </head> <body> <script type="text/javascript"> var csrfToken = $('[name="csrf_token"]').attr('content'); setInterval(refreshToken, 3600000); // 1 hour function refreshToken(){ $.get('refresh-csrf').done(function(data){ csrfToken = data; // the new token }); } setInterval(refreshToken, 3600000); // 1 hour </script> </body> </html> ``` In laravel routes ``` Route::get('refresh-csrf', function(){ return csrf_token(); }); ``` I apologize in case of any syntax errors, haven't used jquery for long time, but i guess you get the idea
You may try [Caffeine for Laravel package](https://github.com/GeneaLabs/laravel-caffeine) it set an interval then it refresh the token like suggested in some answers also it will be added automatically in every form having csrf token
31,449,434
What is the best way to handle expired tokens in laravel 5. I mean I have a page and it has some links which perform ajax requests. They work fine when the page is loaded but when I wait for sometime then I get a TOKEN MISMATCH error. Now, I have to refresh the page to make it work again. BUT, I don't want to refresh the page. I want some way to refresh the token or some other work around to make it fix. I hope you got my point.
2015/07/16
[ "https://Stackoverflow.com/questions/31449434", "https://Stackoverflow.com", "https://Stackoverflow.com/users/364300/" ]
I think the answer by @UX Labs is misleading. And then the comment from @jfadich seems completely incorrect. For Laravel 5.4 in May 2017, I solved the problem this way: Here Is an Answer That Works ---------------------------- In `web.php`: ``` Route::post('keep-token-alive', function() { return 'Token must have been valid, and the session expiration has been extended.'; //https://stackoverflow.com/q/31449434/470749 }); ``` In javascript in your view: ``` $(document).ready(function () { setInterval(keepTokenAlive, 1000 * 60 * 15); // every 15 mins function keepTokenAlive() { $.ajax({ url: '/keep-token-alive', //https://stackoverflow.com/q/31449434/470749 method: 'post', headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') } }).then(function (result) { console.log(new Date() + ' ' + result + ' ' + $('meta[name="csrf-token"]').attr('content')); }); } }); ``` Note that you must *not* list `'keep-token-alive'` in the exclusions within `VerifyCsrfToken.php`. As @ITDesigns.eu implied in a comment, it's important for this route to verify that there is a valid token *currently* and that it just needs to have its expiration extended. Why this approach solves my problem ----------------------------------- My Laravel site allows users to watch a video (an hour long), and it uses ajax to post their progress every minute. But many users load the page and then don't start the video until many hours later. I don't know why they leave their browser tab open so long before watching, but they do. And then I'd get a ton of TokenMismatch exceptions in my logs (and would miss out on the data of their progress). In `session.php`, I changed `'lifetime'` from 120 to 360 minutes, but that still wasn't enough. And I didn't want to make it longer than 6 hours. So I needed to enable this one page to frequently extend the session via ajax. How you can test it and get a sense for how the tokens work: ------------------------------------------------------------ In `web.php`: ``` Route::post('refresh-csrf', function() {//Note: as I mentioned in my answer, I think this approach from @UX Labs does not make sense, but I first wanted to design a test view that used buttons to ping different URLs to understand how tokens work. The "return csrf_token();" does not even seem to get used. return csrf_token(); }); Route::post('test-csrf', function() { return 'Token must have been valid.'; }); ``` In javascript in your view: ``` <button id="tryPost">Try posting to db</button> <button id="getNewToken">Get new token</button> (function () { var $ = require("jquery"); $(document).ready(function () { $('body').prepend('<div>' + new Date() + ' Current token is: ' + $('meta[name="csrf-token"]').attr('content') + '</div>'); $('#getNewToken').click(function () { $.ajax({ url: '/refresh-csrf', method: 'post', headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') } }).then(function (d) { $('meta[name="csrf-token"]').attr('content', d); $('body').prepend('<div>' + new Date() + ' Refreshed token is: ' + $('meta[name="csrf-token"]').attr('content') + '</div>'); }); }); $('#tryPost').click(function () { $.ajax({ url: '/test-csrf', method: 'post', headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') } }).then(function (d) { $('body').prepend('<div>' + new Date() + ' Result of test: ' + d + '</div>'); }); }); }); })(); ``` In `session.php`, temporarily change `'lifetime'` to something very short for testing purposes. Then play around. This is how I learned how the Laravel token works and how we really just need to successfully POST to a CSRF-protected route frequently so that the token continues to be valid.
Best way to handle this Exception is with `App\Exceptions\Handler.php`. ```php public function render($request, Exception $e) { if ($e instanceof \Illuminate\Session\TokenMismatchException) { return Redirect::back()->withErrors(['session' => 'Désolé, votre session semble avoir expiré. Veuillez réessayer.']); } return parent::render($request, $e); } ``` and where ever you wanna show this message (in all your pages that contains `csrf_token`), add this piece: ``` <div> @if(count($errors)>0) @foreach($errors->all() as $error) <ul> <li>{{$error}}</li> </ul> @endforeach @endif </div> ```
31,449,434
What is the best way to handle expired tokens in laravel 5. I mean I have a page and it has some links which perform ajax requests. They work fine when the page is loaded but when I wait for sometime then I get a TOKEN MISMATCH error. Now, I have to refresh the page to make it work again. BUT, I don't want to refresh the page. I want some way to refresh the token or some other work around to make it fix. I hope you got my point.
2015/07/16
[ "https://Stackoverflow.com/questions/31449434", "https://Stackoverflow.com", "https://Stackoverflow.com/users/364300/" ]
Best way to handle this Exception is with `App\Exceptions\Handler.php`. ```php public function render($request, Exception $e) { if ($e instanceof \Illuminate\Session\TokenMismatchException) { return Redirect::back()->withErrors(['session' => 'Désolé, votre session semble avoir expiré. Veuillez réessayer.']); } return parent::render($request, $e); } ``` and where ever you wanna show this message (in all your pages that contains `csrf_token`), add this piece: ``` <div> @if(count($errors)>0) @foreach($errors->all() as $error) <ul> <li>{{$error}}</li> </ul> @endforeach @endif </div> ```
You may try [Caffeine for Laravel package](https://github.com/GeneaLabs/laravel-caffeine) it set an interval then it refresh the token like suggested in some answers also it will be added automatically in every form having csrf token
31,449,434
What is the best way to handle expired tokens in laravel 5. I mean I have a page and it has some links which perform ajax requests. They work fine when the page is loaded but when I wait for sometime then I get a TOKEN MISMATCH error. Now, I have to refresh the page to make it work again. BUT, I don't want to refresh the page. I want some way to refresh the token or some other work around to make it fix. I hope you got my point.
2015/07/16
[ "https://Stackoverflow.com/questions/31449434", "https://Stackoverflow.com", "https://Stackoverflow.com/users/364300/" ]
**Update 2022;** the `csrf_token()` method will **never** create a *new* token, and it simply loads *existing* CSRF-token from current-session (if any, and returns it). But this *tricks* you into thinking it works, because Laravel increases the life-time of the *existing* CSRF-token, and that each time a request to a CSRF-protected route is made. For an implemention that **really creates new** CSRF-token, see: > > stackoverflow.com/[Get new CSRF token with Ajax?](https://stackoverflow.com/a/57252273/8740349) > > > Original Answer (From 2015) --------------------------- A work around for it, is to actually get the new token every certain time, otherwise you are defeating the purpose of the csrf token: ``` <html> <head> <meta name="csrf_token" content="{{ csrf_token() }}"> </head> <body> <script type="text/javascript"> var csrfToken = $('[name="csrf_token"]').attr('content'); setInterval(refreshToken, 3600000); // 1 hour function refreshToken(){ $.get('refresh-csrf').done(function(data){ csrfToken = data; // the new token }); } setInterval(refreshToken, 3600000); // 1 hour </script> </body> </html> ``` In laravel routes ``` Route::get('refresh-csrf', function(){ return csrf_token(); }); ``` I apologize in case of any syntax errors, haven't used jquery for long time, but i guess you get the idea
I think the answer by @UX Labs is misleading. And then the comment from @jfadich seems completely incorrect. For Laravel 5.4 in May 2017, I solved the problem this way: Here Is an Answer That Works ---------------------------- In `web.php`: ``` Route::post('keep-token-alive', function() { return 'Token must have been valid, and the session expiration has been extended.'; //https://stackoverflow.com/q/31449434/470749 }); ``` In javascript in your view: ``` $(document).ready(function () { setInterval(keepTokenAlive, 1000 * 60 * 15); // every 15 mins function keepTokenAlive() { $.ajax({ url: '/keep-token-alive', //https://stackoverflow.com/q/31449434/470749 method: 'post', headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') } }).then(function (result) { console.log(new Date() + ' ' + result + ' ' + $('meta[name="csrf-token"]').attr('content')); }); } }); ``` Note that you must *not* list `'keep-token-alive'` in the exclusions within `VerifyCsrfToken.php`. As @ITDesigns.eu implied in a comment, it's important for this route to verify that there is a valid token *currently* and that it just needs to have its expiration extended. Why this approach solves my problem ----------------------------------- My Laravel site allows users to watch a video (an hour long), and it uses ajax to post their progress every minute. But many users load the page and then don't start the video until many hours later. I don't know why they leave their browser tab open so long before watching, but they do. And then I'd get a ton of TokenMismatch exceptions in my logs (and would miss out on the data of their progress). In `session.php`, I changed `'lifetime'` from 120 to 360 minutes, but that still wasn't enough. And I didn't want to make it longer than 6 hours. So I needed to enable this one page to frequently extend the session via ajax. How you can test it and get a sense for how the tokens work: ------------------------------------------------------------ In `web.php`: ``` Route::post('refresh-csrf', function() {//Note: as I mentioned in my answer, I think this approach from @UX Labs does not make sense, but I first wanted to design a test view that used buttons to ping different URLs to understand how tokens work. The "return csrf_token();" does not even seem to get used. return csrf_token(); }); Route::post('test-csrf', function() { return 'Token must have been valid.'; }); ``` In javascript in your view: ``` <button id="tryPost">Try posting to db</button> <button id="getNewToken">Get new token</button> (function () { var $ = require("jquery"); $(document).ready(function () { $('body').prepend('<div>' + new Date() + ' Current token is: ' + $('meta[name="csrf-token"]').attr('content') + '</div>'); $('#getNewToken').click(function () { $.ajax({ url: '/refresh-csrf', method: 'post', headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') } }).then(function (d) { $('meta[name="csrf-token"]').attr('content', d); $('body').prepend('<div>' + new Date() + ' Refreshed token is: ' + $('meta[name="csrf-token"]').attr('content') + '</div>'); }); }); $('#tryPost').click(function () { $.ajax({ url: '/test-csrf', method: 'post', headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') } }).then(function (d) { $('body').prepend('<div>' + new Date() + ' Result of test: ' + d + '</div>'); }); }); }); })(); ``` In `session.php`, temporarily change `'lifetime'` to something very short for testing purposes. Then play around. This is how I learned how the Laravel token works and how we really just need to successfully POST to a CSRF-protected route frequently so that the token continues to be valid.
31,449,434
What is the best way to handle expired tokens in laravel 5. I mean I have a page and it has some links which perform ajax requests. They work fine when the page is loaded but when I wait for sometime then I get a TOKEN MISMATCH error. Now, I have to refresh the page to make it work again. BUT, I don't want to refresh the page. I want some way to refresh the token or some other work around to make it fix. I hope you got my point.
2015/07/16
[ "https://Stackoverflow.com/questions/31449434", "https://Stackoverflow.com", "https://Stackoverflow.com/users/364300/" ]
try this in your main layout file ``` @guest <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" /> <meta http-equiv="Pragma" content="no-cache" /> <meta http-equiv="Expires" content="0" /> <meta http-equiv="refresh" content="{{config('session.lifetime') * 60}}"> @endguest ```
Circum-navigating the token is generally accepted as a terrible approach but there are problems with using js timers mentioned above too. js seetTimeout/setInterval is unreliable when the browser tab is either not it focus, minimised or in the case of many users, thier laptop/device is sleeping/closed etc. A better route might be to use a js timer to recalculate the 'time to die' from a datestamp set in a cookie (or meta tag for fussy GDPR no-cookie users). this datestamp will be the realworld (timezoned) time the session will die and is updated every page refresh. This way, it doesn't matter what the browser/device was doing/not doing whilst you were away AND it'll still be acurate for those with 'keep me signed in' etc. The next problem is what to do instead of auto resfreshing the token - present the user with a 're-login in' form (modal/popup) that ajaxes the new token to the page as mentioned above.
50,250,474
**Problem:** I'm looking for a way to create complex snippets. At our company we have larger functions which almost seem boilerplate-ish, and I feel can be made much easier. **Desired solution:** I want to create something, similar to how snippets work, but suitable for more complex generation of code. For instance, see the following code, which is typical for what we generate: ``` private readonly DependencyOne dependencyOne; private readonly DependencyTwo dependencyTwo; public ClassName(DependencyOne dependencyOne, DependencyTwo dependencyTwo) { this.dependencyOne = dependencyOne; this.dependencyTwo = dependencyTwo; } ``` **Basically I only want type the two classnames**, and from that generate the constructor and the two associated fields. If possible I want to add these fields at the correct position in the code, pretty much like how IntelliSense's Quick Fix automatically finds the correct position in your code to place the fields. The reason why I can't just generate it above the constructor, is because there are some methods which will be generated which aren't constructors and therefore don't reside on the top of the code. How do I achieve this desired solution?
2018/05/09
[ "https://Stackoverflow.com/questions/50250474", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9763789/" ]
Still you have selected the answer I would like to answer on your last desire that you want this to work in a proper way that WordPress do. Please check **wp\_footer** is called before **body** tag closed or not. Action Hook **wp\_enqueue\_scripts** will called in **wp\_footer** function. Please try once and let me know the result.
You can get css file from below code: ``` <?php add_action( 'wp_enqueue_scripts', 'theme_enqueue_styles' ); function theme_enqueue_styles() { wp_enqueue_style( 'parent-style', get_template_directory_uri() . '/style.css' ); wp_enqueue_style( 'child-style', get_stylesheet_directory_uri() . '/style.css', array('parent-style') ); } ?> ``` Or in Header section before wp\_head() add below code ``` <link href="<?php echo get_bloginfo('stylesheet_directory');?>/css/bootstrap_grid.css" rel="stylesheet" /> <link href="<?php echo get_bloginfo('stylesheet_directory');?>/css/main.css" rel="stylesheet" /> ```
50,250,474
**Problem:** I'm looking for a way to create complex snippets. At our company we have larger functions which almost seem boilerplate-ish, and I feel can be made much easier. **Desired solution:** I want to create something, similar to how snippets work, but suitable for more complex generation of code. For instance, see the following code, which is typical for what we generate: ``` private readonly DependencyOne dependencyOne; private readonly DependencyTwo dependencyTwo; public ClassName(DependencyOne dependencyOne, DependencyTwo dependencyTwo) { this.dependencyOne = dependencyOne; this.dependencyTwo = dependencyTwo; } ``` **Basically I only want type the two classnames**, and from that generate the constructor and the two associated fields. If possible I want to add these fields at the correct position in the code, pretty much like how IntelliSense's Quick Fix automatically finds the correct position in your code to place the fields. The reason why I can't just generate it above the constructor, is because there are some methods which will be generated which aren't constructors and therefore don't reside on the top of the code. How do I achieve this desired solution?
2018/05/09
[ "https://Stackoverflow.com/questions/50250474", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9763789/" ]
You can get css file from below code: ``` <?php add_action( 'wp_enqueue_scripts', 'theme_enqueue_styles' ); function theme_enqueue_styles() { wp_enqueue_style( 'parent-style', get_template_directory_uri() . '/style.css' ); wp_enqueue_style( 'child-style', get_stylesheet_directory_uri() . '/style.css', array('parent-style') ); } ?> ``` Or in Header section before wp\_head() add below code ``` <link href="<?php echo get_bloginfo('stylesheet_directory');?>/css/bootstrap_grid.css" rel="stylesheet" /> <link href="<?php echo get_bloginfo('stylesheet_directory');?>/css/main.css" rel="stylesheet" /> ```
Wrap with add\_action and this might work `<?php add_action( 'wp_enqueue_scripts', 'theme_enqueue_styles' ); function theme_enqueue_styles() { wp_register_style('css-ui',get_template_directory_uri().'/assets/css/style.css' ); wp_enqueue_style('css-ui' ); }`
50,250,474
**Problem:** I'm looking for a way to create complex snippets. At our company we have larger functions which almost seem boilerplate-ish, and I feel can be made much easier. **Desired solution:** I want to create something, similar to how snippets work, but suitable for more complex generation of code. For instance, see the following code, which is typical for what we generate: ``` private readonly DependencyOne dependencyOne; private readonly DependencyTwo dependencyTwo; public ClassName(DependencyOne dependencyOne, DependencyTwo dependencyTwo) { this.dependencyOne = dependencyOne; this.dependencyTwo = dependencyTwo; } ``` **Basically I only want type the two classnames**, and from that generate the constructor and the two associated fields. If possible I want to add these fields at the correct position in the code, pretty much like how IntelliSense's Quick Fix automatically finds the correct position in your code to place the fields. The reason why I can't just generate it above the constructor, is because there are some methods which will be generated which aren't constructors and therefore don't reside on the top of the code. How do I achieve this desired solution?
2018/05/09
[ "https://Stackoverflow.com/questions/50250474", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9763789/" ]
Still you have selected the answer I would like to answer on your last desire that you want this to work in a proper way that WordPress do. Please check **wp\_footer** is called before **body** tag closed or not. Action Hook **wp\_enqueue\_scripts** will called in **wp\_footer** function. Please try once and let me know the result.
Wrap with add\_action and this might work `<?php add_action( 'wp_enqueue_scripts', 'theme_enqueue_styles' ); function theme_enqueue_styles() { wp_register_style('css-ui',get_template_directory_uri().'/assets/css/style.css' ); wp_enqueue_style('css-ui' ); }`
17,591,618
I have a string like below that comes as a response. I want this string to format so every parameter come one after another. Like if i get this string ``` string str1 = @"testmode=0<br>MessageReceived=Your order dispached and will be delived<br>Messagecount1 <br>could not access file: Error=Not enough credit send."; ``` i want to format it so that it look like ``` testmode=0 message received=Your order dispached and will be delivered message count=1 could not access file: error=not enough credit send. ```
2013/07/11
[ "https://Stackoverflow.com/questions/17591618", "https://Stackoverflow.com", "https://Stackoverflow.com/users/357261/" ]
try something like ``` string formatted = str1.Replace("<br>",Environment.NewLine); ``` This will just replace the `<br>` tags with a newline.
Not the best one, but what about: ``` MessageBox.Show(string.Join(Environment.NewLine, str1.Split(new string[]{"<br>", ":"}, StringSplitOptions.None))); ```
17,591,618
I have a string like below that comes as a response. I want this string to format so every parameter come one after another. Like if i get this string ``` string str1 = @"testmode=0<br>MessageReceived=Your order dispached and will be delived<br>Messagecount1 <br>could not access file: Error=Not enough credit send."; ``` i want to format it so that it look like ``` testmode=0 message received=Your order dispached and will be delivered message count=1 could not access file: error=not enough credit send. ```
2013/07/11
[ "https://Stackoverflow.com/questions/17591618", "https://Stackoverflow.com", "https://Stackoverflow.com/users/357261/" ]
try something like ``` string formatted = str1.Replace("<br>",Environment.NewLine); ``` This will just replace the `<br>` tags with a newline.
try ``` MessageBox.Show(str1.Replace(@"<br>", Environment.NewLine)); ``` I'm not sure regarding the line break after `could not access file:` How do you know you have to break line there?
17,591,618
I have a string like below that comes as a response. I want this string to format so every parameter come one after another. Like if i get this string ``` string str1 = @"testmode=0<br>MessageReceived=Your order dispached and will be delived<br>Messagecount1 <br>could not access file: Error=Not enough credit send."; ``` i want to format it so that it look like ``` testmode=0 message received=Your order dispached and will be delivered message count=1 could not access file: error=not enough credit send. ```
2013/07/11
[ "https://Stackoverflow.com/questions/17591618", "https://Stackoverflow.com", "https://Stackoverflow.com/users/357261/" ]
try something like ``` string formatted = str1.Replace("<br>",Environment.NewLine); ``` This will just replace the `<br>` tags with a newline.
Maybe try this using Replace to change br into newline. Put after your code this line: ``` str1.Replace("<br>", "\n"); ```
17,591,618
I have a string like below that comes as a response. I want this string to format so every parameter come one after another. Like if i get this string ``` string str1 = @"testmode=0<br>MessageReceived=Your order dispached and will be delived<br>Messagecount1 <br>could not access file: Error=Not enough credit send."; ``` i want to format it so that it look like ``` testmode=0 message received=Your order dispached and will be delivered message count=1 could not access file: error=not enough credit send. ```
2013/07/11
[ "https://Stackoverflow.com/questions/17591618", "https://Stackoverflow.com", "https://Stackoverflow.com/users/357261/" ]
try ``` MessageBox.Show(str1.Replace(@"<br>", Environment.NewLine)); ``` I'm not sure regarding the line break after `could not access file:` How do you know you have to break line there?
Not the best one, but what about: ``` MessageBox.Show(string.Join(Environment.NewLine, str1.Split(new string[]{"<br>", ":"}, StringSplitOptions.None))); ```
17,591,618
I have a string like below that comes as a response. I want this string to format so every parameter come one after another. Like if i get this string ``` string str1 = @"testmode=0<br>MessageReceived=Your order dispached and will be delived<br>Messagecount1 <br>could not access file: Error=Not enough credit send."; ``` i want to format it so that it look like ``` testmode=0 message received=Your order dispached and will be delivered message count=1 could not access file: error=not enough credit send. ```
2013/07/11
[ "https://Stackoverflow.com/questions/17591618", "https://Stackoverflow.com", "https://Stackoverflow.com/users/357261/" ]
Maybe try this using Replace to change br into newline. Put after your code this line: ``` str1.Replace("<br>", "\n"); ```
Not the best one, but what about: ``` MessageBox.Show(string.Join(Environment.NewLine, str1.Split(new string[]{"<br>", ":"}, StringSplitOptions.None))); ```
18,064,716
So, I have a file like ``` <root> <transaction ts="1"> <abc><def></def></abc> </transaction> <transaction ts="2"> <abc><def></def></abc> </transaction> </root> ``` So, I have a condition which says if ts="2" then do something ... Now the problem is when it finds ts="1" it still scans through tags < abc>< def> and then reaches < transaction ts="2"> Is there a way when the condition doesn`t match the parsing breaks and look for the next transaction tag directly?
2013/08/05
[ "https://Stackoverflow.com/questions/18064716", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2601010/" ]
A SAX parser must scan thru all sub trees (like your "< abc>< def>< /def>< /abc>") to know where the next element starts. No way to get around it, which is also the reason why you cannot parallelize a XML Parser for a single XML document. The only two ways of tuning I can think of in your case: 1) If you have many XML documents to parse, you can run one Parser for each document in its own thread. This would at least parallelize the overall work and utilize all CPU's and Cores you have available. 2) If you just need to read up to a certain condition (like you mentioned < transaction ts="2">) you can skip parsing as soon as that condition is reached. If skipping the parser would help, the way to this is by throwing an Exception. Your implementation of `startElement` within the `ContentHandler` would look like this: ``` public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException { if(atts == null) return; if(localName.equals("transaction") && "2".equals(atts.getValue("ts"))) { // TODO: Whatever should happen when condition is reached throw new SAXException("Condition reached. Just skip rest of parsing"); } } ```
> > Is there a way when the condition doesn`t match the parsing breaks and > look for the next transaction tag directly? > > > No. You'll have to write the SAX parser to know when to skip looking at the tags in the bad transaction block. That said, you'll probably find switching to [STAX](http://docs.oracle.com/cd/E17802_01/webservices/webservices/docs/1.6/tutorial/doc/SJSXP3.html) to be easier to do stuff like this than SAX.
18,064,716
So, I have a file like ``` <root> <transaction ts="1"> <abc><def></def></abc> </transaction> <transaction ts="2"> <abc><def></def></abc> </transaction> </root> ``` So, I have a condition which says if ts="2" then do something ... Now the problem is when it finds ts="1" it still scans through tags < abc>< def> and then reaches < transaction ts="2"> Is there a way when the condition doesn`t match the parsing breaks and look for the next transaction tag directly?
2013/08/05
[ "https://Stackoverflow.com/questions/18064716", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2601010/" ]
A SAX parser must scan thru all sub trees (like your "< abc>< def>< /def>< /abc>") to know where the next element starts. No way to get around it, which is also the reason why you cannot parallelize a XML Parser for a single XML document. The only two ways of tuning I can think of in your case: 1) If you have many XML documents to parse, you can run one Parser for each document in its own thread. This would at least parallelize the overall work and utilize all CPU's and Cores you have available. 2) If you just need to read up to a certain condition (like you mentioned < transaction ts="2">) you can skip parsing as soon as that condition is reached. If skipping the parser would help, the way to this is by throwing an Exception. Your implementation of `startElement` within the `ContentHandler` would look like this: ``` public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException { if(atts == null) return; if(localName.equals("transaction") && "2".equals(atts.getValue("ts"))) { // TODO: Whatever should happen when condition is reached throw new SAXException("Condition reached. Just skip rest of parsing"); } } ```
The sax parser calls your callbacks always for each XML element. You can solve your question by setting a field `isIgnoreCurrentTransaction`, once you detect the condition to ignore. Then in your other sax callbacks you check for `isIgnoreCurrentTransaction` amd simply do nothing in that case.
18,064,716
So, I have a file like ``` <root> <transaction ts="1"> <abc><def></def></abc> </transaction> <transaction ts="2"> <abc><def></def></abc> </transaction> </root> ``` So, I have a condition which says if ts="2" then do something ... Now the problem is when it finds ts="1" it still scans through tags < abc>< def> and then reaches < transaction ts="2"> Is there a way when the condition doesn`t match the parsing breaks and look for the next transaction tag directly?
2013/08/05
[ "https://Stackoverflow.com/questions/18064716", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2601010/" ]
A SAX parser must scan thru all sub trees (like your "< abc>< def>< /def>< /abc>") to know where the next element starts. No way to get around it, which is also the reason why you cannot parallelize a XML Parser for a single XML document. The only two ways of tuning I can think of in your case: 1) If you have many XML documents to parse, you can run one Parser for each document in its own thread. This would at least parallelize the overall work and utilize all CPU's and Cores you have available. 2) If you just need to read up to a certain condition (like you mentioned < transaction ts="2">) you can skip parsing as soon as that condition is reached. If skipping the parser would help, the way to this is by throwing an Exception. Your implementation of `startElement` within the `ContentHandler` would look like this: ``` public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException { if(atts == null) return; if(localName.equals("transaction") && "2".equals(atts.getValue("ts"))) { // TODO: Whatever should happen when condition is reached throw new SAXException("Condition reached. Just skip rest of parsing"); } } ```
You can use a control flag in your SAX implementation which is raised when you detect your condition on a certain tag and lower the flag again once you exit the tag. You can use that flag to skip any processing when the parser runs through the children of the tag you are not interested in. Note however that your example XML is not valid. You need to use proper nesting of your tags before you can process it with a SAX implementation, as stated in the comments.
14,941,954
I have frames of a Video with 30FPS in my C# code and I want to broadcast it in local host so all other applications can use it. I though because it is a video and there is no concern if any packet lost and no need to connect/accept from clients, UDP is a good choose. But there are number of problems here. * If I use UDP Unicast speed is enough, about 25FPS (CPU Usage is 25% that mean 100% on one thread in my 4 core CPU which is not ideal. But at least it send enough set of data). But unicast cant deliver data to all clients. * If I use broadcast speed is very low. About 10FPS with same CPU usage. What can I do?! Data are in same computer so there is no need to remote access from LAN or etc. I just want a way to transfer about 30MBytes of data per second between different applications of same machine. (640x480 is fixed size of Image x 30fps x 3byte per pixel is about 27000KByte per second) 1. Is UDP Multicast has better performance?! 2. Is TCP can give me better performance even if I accept each client and send to them independently?! 3. Is there any better way than Socket?! Memory sharing or something?! 4. Why UDP broadcast is that much slow?! Only about 10MBytes per second?! 5. Is there a fast way to compress frames with high performance (to encode 30fps in a sec and decode on other part)? Client apps are in C++ so this must be a cross platform way. I just want to know other developers experiences and ideas here so please write what you think. Edit: More info about data: Data are in Bitmap RGB24 format and they are streaming from a device to my application with 30FPS. I want to broadcast this data to other applications and they need to have this images in RGB24 format again. There is no header or any thing, only bitmap data with fixed size. All operations must perform on the fly. No matter of using a lossy compression algorithm or any thing.
2013/02/18
[ "https://Stackoverflow.com/questions/14941954", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1913051/" ]
I experiment Multicast in an industrial environment, it's a good choice **over a not staturated reliable network**. In **local host**, *shared memory* may be a good choice because you may build a **circular queue of frames** and flip from one to the next only with a single mutex to protect a pointer assignment (writter side). With one writter, several reader, no problem arise. On Windows with C++ **and** C#, shared memory is called File Mapping, but you may use system paging file (RAM and/or disk). See these links to more information * <http://msdn.microsoft.com/en-us/library/system.io.memorymappedfiles.aspx> * <http://msdn.microsoft.com/en-us/library/dd997372.aspx> * Mixing C++ and C# : [How to implement shared memory in .NET?](https://stackoverflow.com/questions/439787/how-to-implement-shared-memory-in-net) * [Fully managed shared memory .NET implementations?](https://stackoverflow.com/questions/4580722/fully-managed-shared-memory-net-implementations) The shared memory space isn't protected nor private but it'd named. Usually, the writer process creates it, and the readers opens it by its name. Antivirus softwares takes a look at this kind of I/O in a same fashion as they do for all others but don't block the communication. Here is a sample to begin with File Mapping: ``` char shmName[MAX_PATH+1]; sprintf( shmName, "shmVideo_%s", name ); shmName[MAX_PATH] = '\0'; _hMap = CreateFileMapping( INVALID_HANDLE_VALUE, 0, PAGE_READWRITE, 0, size, shmName ); if( _hMap == 0 ) { throw OSException( __FILE__, __LINE__ ); } _owner = ( GetLastError() != ERROR_ALREADY_EXISTS ); _mutex = Mutex::getMutex( name ); Synchronize sync( *_mutex ); _data = (char *)MapViewOfFile( _hMap, FILE_MAP_ALL_ACCESS, 0, 0, 0 ); if( _data == 0 ) { throw OSException( __FILE__, __LINE__ ); } ```
Use live555 <http://www.live555.com/> for streaming in combination with your favorite compressor - ffmpeg.
71,153,291
I would like to retrieve all products of chosen parent category.Product model have hasmany relation to product\_category\_mapping table. If product have subcategory result like, ``` "MAinCatergory":[ { id="", name:"Drinks", "ChildCategory":[ { "id":1, "name":"Juce", "Products":[{ name:"apple juce", price:10, .... }] } ] } ] ``` } If product under main category only return array like, ``` "MAinCatergory":[ { id="", name:"Drinks", "Products":[{ name:"apple juce", price:10, .... }] } } ] ``` } category table fields - id,name,parent\_id product table fields - id,name,price,.., product-category-mapping table fields - id,category\_id,product\_id category model ``` public function children() { return $this->hasMany('App\Models\Category', 'parent_id'); } public function parent() { return $this->belongsTo('App\Models\Category', 'parent_id'); } public function product_category() { return $this->hasMany('App\Models\ProductCategoryMapping', 'category_id'); } ``` product model ``` public function product_category() { return $this->hasMany('App\Models\ProductCategoryMapping','product_id'); } ``` product-category\_mapping ``` public function product() { return $this->belongsTo(Product::class,'product_id','id'); } public function category() { return $this->belongsTo(Category::class,'category_id','id'); } ```
2022/02/17
[ "https://Stackoverflow.com/questions/71153291", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6085744/" ]
Something like this might suffice. ``` App\Models\Category::with('children', 'product_category.product')->get() ``` Suggestion, try implement pivot many to many relation instead this product\_category\_mapping, then model relation would change a bit. For pivot relation, you need to modify the Category model ``` public function products() { return $this->belongsToMany('App\Models\Product', 'product-category-mapping'); } ``` and in product Model ``` public function categories() { return $this->belongsToMany('App\Models\Category','product-category-mapping'); } ``` **Note:This is not the complete integration, but to give you an idea, for full logic see <https://laravel.com/docs/9.x/eloquent-relationships#many-to-many>**
in your product model add like this: ``` public function product_categorys(){ return $this->hasMany('App\Models\ProductCategoryMapping','product_id'); } ``` and in controller you can get inside your function like this `Product::with('product_categorys')->get();`
2,376,305
I am trying to evaluate the following Fourier transform $$F(x,n) = \int\_{-\infty}^{\infty}\frac{\mathrm{e}^{\mathrm{i}tx}} {(\,t - \mathrm{i}\,)^{n/2}}\,\mathrm{d}t\,,\quad \forall\ x \in \mathbb{R}^{+}\,,\ n\in \mathbb{N}. $$ For even $n$, we can use the contour integral on the complex plane $t$ where [the contour](https://upload.wikimedia.org/wikipedia/commons/9/93/ContourDiagram.png) consists of the interval $\left[-a, a\right]$ on the real axis and a hemisphere on the upper half plane centered at the origin with a radius of $a$ for $a > 0$. We obtain the result using Cauchy's differentiation formula. For odd natural number $n$, there is a branch cut for $\displaystyle(t - \mathrm{i})^{\frac n 2}$. Now if we make a slit from $t = \mathrm{i}$ and integrate $\displaystyle\frac{e^{\mathrm{i}tx}}{\left(\,t -\mathrm{i}\,\right)^{\frac n 2}}$ starting from $t = \mathrm{i}$ we will have a divergent integral for $n \geq 3$. What could be done ?
2017/07/30
[ "https://math.stackexchange.com/questions/2376305", "https://math.stackexchange.com", "https://math.stackexchange.com/users/64809/" ]
$\newcommand{\bbx}[1]{\,\bbox[15px,border:1px groove navy]{\displaystyle{#1}}\,} \newcommand{\braces}[1]{\left\lbrace\,{#1}\,\right\rbrace} \newcommand{\bracks}[1]{\left\lbrack\,{#1}\,\right\rbrack} \newcommand{\dd}{\mathrm{d}} \newcommand{\ds}[1]{\displaystyle{#1}} \newcommand{\expo}[1]{\,\mathrm{e}^{#1}\,} \newcommand{\ic}{\mathrm{i}} \newcommand{\mc}[1]{\mathcal{#1}} \newcommand{\mrm}[1]{\mathrm{#1}} \newcommand{\pars}[1]{\left(\,{#1}\,\right)} \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}} \newcommand{\root}[2][]{\,\sqrt[#1]{\,{#2}\,}\,} \newcommand{\totald}[3][]{\frac{\mathrm{d}^{#1} #2}{\mathrm{d} #3^{#1}}} \newcommand{\verts}[1]{\left\vert\,{#1}\,\right\vert}$ > > $\ds{\mrm{F}\pars{x,n} \equiv > \int\_{-\infty}^{\infty}{\expo{\ic tx} \over \pars{t - \ic}^{n/2}}\,\dd t\,,\quad > \forall\ x \in \mathbb{R}\setminus\braces{0}\,,\ n\in \mathbb{N}\_{\color{#f00}{\ \geq\ 1}}}$. > > > --- \begin{equation}\bbox[15px,#ffe,border:1px dotted navy]{\ds{% \begin{array}{l} \mbox{I'll consider a 'more general' case: Namely;} \ds{\,\,\, x \in \mathbb{R}\setminus\braces{0}\,,\ n \in \mathbb{R}^{+}}. \\[5mm] \mbox{Lets consider,} \\\ds{\quad \left.\vphantom{\Large A}\mc{F}\pars{x,\alpha} \right\vert\_{~\substack{x\ \in\ \mathbb{R}\setminus{0}\\[0.5mm] \alpha\ \in\ \mathbb{R}^{\large+}}} \equiv \int\_{-\infty}^{\infty}{\expo{\ic tx} \over \pars{t - \ic}^{\alpha/2}}\,\dd t} \quad\mbox{where}\ z^{\alpha/2}\ \mbox{is its}\ Principal\ Branch. \end{array}}}\label{1}\tag{1} \end{equation} --- \begin{align} \mc{F}\pars{x,\alpha} & = \expo{-x}\int\_{-\infty - \ic}^{\infty - \ic} {\expo{\ic xt} \over t^{\alpha/2}}\,\dd t \,\,\,\stackrel{\substack{t\ =\ -\ic s\\ s\ =\ \phantom{-}\ic t\\[0.5mm] \mbox{}}}{=}\,\,\, \expo{-x}\int\_{\ic\pars{-\infty - \ic}}^{\ic\pars{\infty - \ic}} {\expo{xs} \over \pars{-\ic s}^{\alpha/2}}\,\pars{-\ic}\,\dd s \\[5mm] & = -\bracks{x > 0}\ic\expo{\alpha\pi\ic/4}\expo{-x}\int\_{1 - \infty\ic}^{1 + \infty\ic} {\expo{xs} \over s^{\alpha/2}}\,\dd s\label{2}\tag{2} \end{align} The remaining integral is evaluated along a *key-hole contour* which 'takes care' of the $\ds{z^{\alpha/2}\mbox{-Branch-Cut}}$: \begin{align} \left.\int\_{1 - \infty\ic}^{1 + \infty\ic}{\expo{xs} \over s^{\alpha/2}}\,\dd s \,\right\vert\_{\ x\ >\ 0} & \,\,\,\stackrel{\mrm{as}\ \epsilon\ \to\ 0^{\large +}}{\sim}\,\,\, -\int\_{-\infty}^{-\epsilon}\pars{-s}^{-\alpha/2}\expo{-\alpha\pi\ic/2}\expo{xs} \,\dd s \\[2mm] & \phantom{\,\,\,\stackrel{\mrm{as}\ \epsilon\ \to\ 0^{\large +}}{\sim}\,\,\,} -\int\_{\pi}^{-\pi}\epsilon^{-\alpha/2} \expo{-\ic\alpha\theta/2}\epsilon\expo{\ic\theta}\ic\,\dd\theta \\[2mm] & \phantom{\,\,\,\stackrel{\mrm{as}\ \epsilon\ \to\ 0^{\large +}}{\sim}\,\,\,} -\int\_{-\epsilon}^{-\infty}\pars{-s} ^{-\alpha/2}\expo{\alpha\pi\ic/2}\expo{xs}\,\dd s \\[5mm] & = -\expo{-\alpha\pi\ic/2}\int\_{\epsilon}^{\infty}s^{-\alpha/2}\expo{-xs}\,\dd s + {2\sin\pars{\alpha\pi/2}\,\epsilon^{1 - \alpha/2} \over 1 - \alpha/2}\,\ic \\[2mm] & + \expo{\alpha\pi\ic/2}\int\_{\epsilon}^{\infty}s^{-\alpha/2}\expo{-xs}\,\dd s \\[5mm] & = 2\ic\sin\pars{\alpha\pi \over 2} \int\_{\epsilon}^{\infty}s^{-\alpha/2}\expo{-xs}\,\dd s + {2\sin\pars{\alpha\pi/2}\epsilon^{1 - \alpha/2} \over 1 - \alpha/2}\,\ic \end{align} > > Note that I'll can consider the case where $\ds{2 \not\mid \alpha}$ such that the case $\ds{2 \mid \alpha}$ is a 'limiting one'. > > > Therefore, \begin{align} \left.\int\_{1 - \infty\ic}^{1 + \infty\ic}{\expo{xs} \over s^{\alpha/2}}\,\dd s \,\right\vert\_{\ x\ >\ 0} & \,\,\,\stackrel{\mrm{as}\ \epsilon\ \to\ 0^{\large +}}{\sim}\,\,\, 2\ic\sin\pars{\alpha\pi \over 2}\bracks{% {1 \over x^{1 - \alpha/2}}\int\_{x\epsilon}^{\infty}s^{-\alpha/2}\expo{-s}\,\dd s + {\epsilon^{1 - \alpha/2} \over 1 - \alpha/2}} \\[5mm] & = 2\ic\sin\pars{\alpha\pi \over 2}\bracks{% x^{\alpha/2 - 1}\Gamma\pars{1 - {\alpha \over 2},x\epsilon} + {\epsilon^{1 - \alpha/2} \over 1 - \alpha/2}}\label{3}\tag{3} \end{align} > > $\ds{\Gamma\pars{1 - {\alpha \over 2},x\epsilon}}$ is the > [Incomplete Gamma Function](http://dlmf.nist.gov/8.2.E2). > > > In the present case $\large\left(\right.$ [see $\ds{\mathbf{\color{#000}{8.7.3}}}$ in DLMF](http://dlmf.nist.gov/8.7.E3) ${\large\left.\right)}$: $\ds{\pars{~1 - {\alpha \over 2} \not= 0,-1,-2,\ldots\ \mbox{or/and}\ \alpha \not= 2,4,6,\ldots~}}$ \begin{align} &x^{\alpha/2 - 1}\,\Gamma\pars{1 - {\alpha \over 2},x\epsilon} \,\,\,\stackrel{\mrm{as}\ \epsilon\ \to\ 0^{+}}{\sim}\,\,\, x^{\alpha/2 - 1}\,\Gamma\pars{1 - {\alpha \over 2}}- {\epsilon^{1 - \alpha/2}\expo{-x\epsilon} \over 1 - \alpha/2}\label{3.a}\tag{3.a} \\[5mm] & \bbx{\mbox{Note that the cases}\ \alpha = 2,4,6,\ldots\ \mbox{are 'limiting cases' of the final result.}} \end{align} \eqref{3} becomes, in the $\ds{\epsilon \to 0^{+}}$ limit, \begin{align} \left.\int\_{1 - \infty\ic}^{1 + \infty\ic}{\expo{xs} \over s^{\alpha/2}}\,\dd s \,\right\vert\_{\ x\ >\ 0} & = 2\ic\sin\pars{\alpha\pi \over 2}\,x^{\alpha/2 - 1} \,\Gamma\pars{1 - {\alpha \over 2}} \\[5mm] & = 2\ic\sin\pars{\alpha\pi \over 2}\,x^{\alpha/2 - 1} \,{\pi \over \Gamma\pars{\alpha/2}\sin\pars{\alpha\pi/2}} = {2\pi\ic \over \Gamma\pars{\alpha/2}}\,x^{\alpha/2 - 1}\label{4}\tag{4} \end{align} --- Finally, with \eqref{2} and \eqref{4}: $$\bbox[15px,#ffe,border:1px dotted navy]{\ds{ \left.\vphantom{\Large A}\int\_{-\infty}^{\infty} {\expo{\ic tx} \over \pars{t - \ic}^{\alpha/2}}\,\dd t \,\right\vert\_{\ \substack{x\ \in\ \mathbb{R}\setminus\braces{0}\\[0.5mm] \alpha\ \in\ \mathbb{R}^{+}}} = \bracks{x > 0}2\pi\,{\expo{\alpha\pi\ic/4} \over \Gamma\pars{\alpha/2}}\,\, x^{\alpha/2 - 1}\expo{-x}}} $$
It stays related to $\Gamma(s)$ and its properties. For $x > 0$ and $n > 0$ $$F(x) =\int\_{-\infty}^\infty \frac{e^{itx}}{(t-i)^{n/2}} dt=e^{-x}\int\_{-\infty-i}^{\infty-i} \frac{e^{itx}}{t^{n/2}} dt=e^{-x}x^{n/2-1}\int\_{-\infty-ix}^{\infty-ix} \frac{e^{i\tau}}{\tau^{n/2}} d\tau$$ $$ =F(1) e^{1-x}x^{n/2-1}$$ For $x < 0$ I'm not sure.
2,376,305
I am trying to evaluate the following Fourier transform $$F(x,n) = \int\_{-\infty}^{\infty}\frac{\mathrm{e}^{\mathrm{i}tx}} {(\,t - \mathrm{i}\,)^{n/2}}\,\mathrm{d}t\,,\quad \forall\ x \in \mathbb{R}^{+}\,,\ n\in \mathbb{N}. $$ For even $n$, we can use the contour integral on the complex plane $t$ where [the contour](https://upload.wikimedia.org/wikipedia/commons/9/93/ContourDiagram.png) consists of the interval $\left[-a, a\right]$ on the real axis and a hemisphere on the upper half plane centered at the origin with a radius of $a$ for $a > 0$. We obtain the result using Cauchy's differentiation formula. For odd natural number $n$, there is a branch cut for $\displaystyle(t - \mathrm{i})^{\frac n 2}$. Now if we make a slit from $t = \mathrm{i}$ and integrate $\displaystyle\frac{e^{\mathrm{i}tx}}{\left(\,t -\mathrm{i}\,\right)^{\frac n 2}}$ starting from $t = \mathrm{i}$ we will have a divergent integral for $n \geq 3$. What could be done ?
2017/07/30
[ "https://math.stackexchange.com/questions/2376305", "https://math.stackexchange.com", "https://math.stackexchange.com/users/64809/" ]
We extend the original integral on $\frac n2$ by a complex number $\Re z>0$. $$F(x,z) := \int\_{-\infty}^{\infty}\frac{\mathrm{e}^{\mathrm{i}tx}} {\left(t - \mathrm{i}\right)^z}\,\mathrm{d}t\,,\quad \forall\ x \in \mathbb{R}^{+}\,,\ \Re z\in(0,\infty).$$ We have to make the extension to make use of the contour integral because of the subtlety of the convergence condition of the contour integral in different region is different. The convergence set for $z$ is the intersection of all the convergence sets of $z$ on all the different legs. We use analytical continuation to make the connection. > > Lemma 1: Let $g(z,t)$ be defined for $(z,t)\in\Omega\times[0,1]$. $g(z,t)$ is holomorphic in $z$ for every fixed $t$ and continuous on $\Omega\times[0,1]$. $G(z):=\int\_0^1 g(z,t)\,\mathrm dt$ is holomorphic in $\Omega$. > > > Proof: We show this via Morera's theorem applied to an arbitrary closed simple smooth contour on any arbitrarily given disk $B$ of finite radius in $\Re z\in(0,\infty)$. A continuous function on a compact set is uniformly continuous. So $g(z,t)$ being continuous on the compact set $B\times[0,1]$ is uniformly continuous on $B\times[0,1]$. We can use Riemann sum for the integral to finish the proof. > > Lemma 2: $F(x,z)$ is holomorphic in $\Re z\in(0,\infty)$ for every $x \in \mathbb{R}^{+}$. > > > Proof: We show this via Morera's theorem applied to an arbitrary closed simple smooth contour $C$ on any arbitrarily given disk $B$ of finite radius in $\Re z\in(0,\infty)$. By Lemma 1, $F(x,z,R):=\int\_{-R}^R f(t,x,z)\,\mathrm dt$, where $f(t,x,z):=\frac{\mathrm{e}^{\mathrm{i}tx}} {\left(t - \mathrm{i}\right)^z}$, is holomorphic in $\Re z\in(0,\infty)$. We will show below that for any fixed $x\in\mathbb R^+$, $F(x,z,R)$ uniformly approaches $F(x,z)$ with respect to $B$ as $R\rightarrow\infty$. Then $$0=\lim\_{R\rightarrow\infty}\oint\_C F(x,z,R)\,\mathrm dz = \oint\_C \lim\_{R\rightarrow\infty}F(x,z,R)\,\mathrm dz=\oint\_C F(x,z)\,\mathrm dz$$ by Morera's theorem, the conclusion of the Lemma follows. To that end, let $$\overline F\_+(x,z,R):=\int\_R^\infty\frac{\mathrm{e}^{\mathrm{i}tx}} {\left(t - \mathrm{i}\right)^z}\,\mathrm dt = \frac1{\mathrm ix}\bigg(-\frac{\mathrm{e}^{\mathrm{i}Rx}} {\left(R - \mathrm{i}\right)^z}+z\int\_R^\infty\frac{\mathrm{e}^{\mathrm{i}tx}} {\left(t - \mathrm{i}\right)^{1+z}}\,\mathrm dt\bigg)$$ and $$\overline F\_-(x,z,R):=\int\_R^\infty\frac{\mathrm{e}^{-\mathrm{i}tx}} {\left(-(t+\mathrm{i})\right)^z}\,\mathrm dt = \frac1{\mathrm ix}\bigg(\frac{\mathrm{e}^{-\mathrm{i}Rx}} {\left(-(R - \mathrm{i})\right)^z}+z\int\_R^\infty\frac{\mathrm{e}^{-\mathrm{i}tx}} {\left(-(t - \mathrm{i})\right)^{1+z}}\,\mathrm dt\bigg)$$ Note: The integration by parts is needed because we need to make use of the oscillatory behavior of the harmonic function without which the integral diverges for $\Re z\in (0,1]$. For $z=u+\mathrm iv$, $u,v \in\mathbb R$, $|(t-i)^z|=(t^2+1)^ue^{-\alpha v}$, where $\alpha=\arg(t-i)$ so $|\alpha|<\pi$. As $z$ is in a finite radius disk, $|u|,|v|\in [a,b]$ for some constant real numbers $0<a<b$. $|(t-i)^z|>t^ae^{-\pi b}>0$, $|z|<\sqrt{a^2+b^2}$. $$|\overline F\_+(x,z,R)|<\frac 1x \bigg(\frac1{R^ae^{-\pi b}}+\sqrt{a^2+b^2}\int\_R^\infty \frac1{t^{1+a}e^{-\pi b}}\,\mathrm dt\bigg)=e^{\pi b}\bigg(1+\frac{\sqrt{a^2+b^2}}a\bigg)\frac1{xR^a}.$$ $|\overline F\_+(x,z,R)|\rightarrow 0$ as $R\rightarrow\infty$ uniformly with respect to $z\in B$. The same goes for $|\overline F\_-(x,z,R)|$. So $F(x,z,R)\rightarrow F(x,z)$ as $R\rightarrow\infty$ uniformly with respect to $z\in B$ for fixed $x\in\mathbb R^+$. QED --- Now we proceed to evaluate the original integral. Make the branch cut of $u^z$ in the variable $u$ along the imaginary axis. We construct a contour extending the real axis segment around the upper semicircle, with a slit cut along the imaginary axis with a keyhole around $i$. $$I\_1(R)+I\_2(R)+I\_3(r,R)+I\_4(r)+I\_5(r,R)+I\_6(R)=0,$$ where \begin{align} I\_1(R) &= \int\_{-R}^R\frac{\mathrm{e}^{\mathrm{i}tx}} {\left(\,t - \mathrm{i}\,\right)^z}\,\mathrm{d}t \\ I\_2(R) &= \int\_0^{\frac\pi2}\frac{\mathrm{e}^{\mathrm{i}xRe^{\mathrm i\theta}}} {\left(\,Re^{\mathrm i\theta} - \mathrm{i}\,\right)^z}iRe^{\mathrm i\theta}\,\mathrm{d}\theta \\ I\_6(R) &= \int\_{\frac\pi2}^\pi\frac{\mathrm{e}^{\mathrm{i}xRe^{\mathrm i\theta}}} {\left(\,Re^{\mathrm i\theta} - \mathrm{i}\,\right)^z}iRe^{\mathrm i\theta}\,\mathrm{d}\theta \\ I\_4(r,R) &= e^{-x}\int\_{\frac\pi2}^{-\frac32\pi}\frac{\mathrm{e}^{\mathrm{i}xre^{\mathrm i\theta}}} {\left(re^{\mathrm i\theta}\right)^z}ire^{\mathrm i\theta}\,\mathrm{d}\theta = ie^{-x}\int\_{\frac\pi2}^{-\frac32\pi}e^{ixre^{i\theta}}(re^{i\theta})^{1-z}\,\mathrm d\theta \\ I\_3(r,R) &= e^{-x}\int\_R^r\frac{\mathrm{e}^{\mathrm{i}xte^{\mathrm i\frac\pi 2}}} {\big(te^{\mathrm i\frac\pi 2}\big)^z}e^{\mathrm i\frac\pi 2}\,\mathrm dt = -ie^{-x-i\frac\pi 2z}\int\_r^R\frac{e^{-xt}}{t^z}\,\mathrm dt \\ I\_5(r,R) &= e^{-x}\int\_r^R\frac{\mathrm{e}^{\mathrm{i}xte^{-\mathrm i\frac32\pi}}} {\big(te^{-\mathrm i\frac32\pi}\big)^z}e^{-\mathrm i\frac32\pi}\,\mathrm dt = ie^{-x+i\frac32\pi z}\int\_r^R\frac{e^{-xt}}{t^z}\,\mathrm dt \end{align} Let $z=u+iv$ for real $u$ and $v$. $|(Re^{i\theta}-i)^z|=\rho^ue^{-\alpha v}$, where $\rho:=|Re^{i\theta}-i|,\,\alpha:=\arg(Re^{i\theta}-i)$. We take the branch cut where $\alpha\in\big(-\frac32\pi,\frac12\pi\big]$ When $u>0$, $\rho>R-1$, $|(Re^{i\theta}-i)^z|>(R-1)^ue^{-\alpha v}$, since $\alpha$ is bounded from both sides, $I\_2(R), I\_6(R)\rightarrow 0$ as $R\rightarrow\infty$. When $u\in(0,1)$, $|(re^{i\theta})^{1-z}|=r^{1-u}e^{-\theta v}$, then $I\_4(r)\rightarrow 0$ as $r\rightarrow 0^+$. $I\_3(r,R)$ and $I\_5(r,R)$ converge as $r\rightarrow 0,\, R\rightarrow\infty$ iff $u\in(0,1)$. For $u\in(0,1)$, \begin{align} I\_3(0,\infty)+I\_5(0,\infty) &= -2e^{-x+i\frac\pi2z}\sin(\pi z)\int\_0^\infty \frac{e^{-xt}}{t^z}\,\mathrm dt \\ &= -2e^{-x+i\frac\pi2z}\sin(\pi z)x^{z-1}\int\_0^\infty \frac{e^{-t}}{t^z}\,\mathrm dt \\ &= -2e^{-x+i\frac\pi2z}x^{z-1}\sin(\pi z)\Gamma(1-z) \\ &= -2e^{-x+i\frac\pi2z}x^{z-1}\frac\pi{\Gamma(z)}. \end{align} The equating of the last integral expression with the gamma function is valid only for $u\in(0,1)$. Taking the intersection which is $u\in(0,1)$ of all the convergence sets of $z$ on all the legs, $$F(x,z) = I\_1(\infty) = e^{-x+i\frac\pi2z}x^{z-1}\frac{2\pi}{\Gamma(z)}. \tag1$$ The right hand side of equation (1) is entire with respect to $z$. By Lemma 2, $F(x,z)=I\_1(\infty)$ can be analytically continued from $\Re z\in(0,1)$ to $\Re z\in(0,\infty)$. Therefore Equation $(1)$ can be extended to the open upper plane of the complex plane $\Re z\in(0,\infty)$ for positive $x\in\mathbb R^+.$
It stays related to $\Gamma(s)$ and its properties. For $x > 0$ and $n > 0$ $$F(x) =\int\_{-\infty}^\infty \frac{e^{itx}}{(t-i)^{n/2}} dt=e^{-x}\int\_{-\infty-i}^{\infty-i} \frac{e^{itx}}{t^{n/2}} dt=e^{-x}x^{n/2-1}\int\_{-\infty-ix}^{\infty-ix} \frac{e^{i\tau}}{\tau^{n/2}} d\tau$$ $$ =F(1) e^{1-x}x^{n/2-1}$$ For $x < 0$ I'm not sure.
23,720
I want my raspberryPi to shut down during the night and wake up in the morning. I.e., at 10pm raspberry should shutdown or at least turn of the WiFi and the HDD. At 10am every day my raspberry should wake up or at least turn on the WiFi and the HDD. **How can I do this?** Edit: How can I set a timer to turn of the WiFi and HDD and turn it on again at a certain time?
2014/10/06
[ "https://raspberrypi.stackexchange.com/questions/23720", "https://raspberrypi.stackexchange.com", "https://raspberrypi.stackexchange.com/users/17915/" ]
While - as joan already put it - it's not possible to shut the RPi completely down and/or start it up by its own hardware, your "at least" demand of turning off WiFi and the HDD could be accomplished with only minor hardware hacking. Joans solution however provides higher savings with respect to electrical energy since the RPi also got no real power-off circuit thus consuming power if `halt`-ed. Find a solution the use the GPIO-Pins to turn of a connected USB device (such as the WiFi dongle) [here](https://raspberrypi.stackexchange.com/questions/2181/turning-on-and-off-a-3g-or-any-usb-port/3342#3342). Be sure to spin down the HDD before turning of its power using tools like `hd-idle`. Be also aware that some users claim reduced life-time of HDDs if spun down to often.
You could use power outlet timer, plug the Pi into that and set it to power up every morning. I think the shutdown command has a schedule flag.
23,720
I want my raspberryPi to shut down during the night and wake up in the morning. I.e., at 10pm raspberry should shutdown or at least turn of the WiFi and the HDD. At 10am every day my raspberry should wake up or at least turn on the WiFi and the HDD. **How can I do this?** Edit: How can I set a timer to turn of the WiFi and HDD and turn it on again at a certain time?
2014/10/06
[ "https://raspberrypi.stackexchange.com/questions/23720", "https://raspberrypi.stackexchange.com", "https://raspberrypi.stackexchange.com/users/17915/" ]
Why do you want to shut down the Pi? The Pi itself uses so little power (<5W) that it is not worthwhile unless you are running on batteries. The B+ uses even less. EDIT 2016-06-18 The following comment is no longer correct. `halt` `shutdown` and `poweroff` all perform a orderly shutdown of the OS. Having said that `halt`ing the Pi puts into a very low power state, but can only be restarted with external events. It is simple to "restart" the `B` or `B+` from the `halt` state using a simple externally driven circuit. This could be a timer or even a light dependent sensor. see <https://raspberrypi.stackexchange.com/a/19754/8697> If your motivation is to limit access you can use `cron` to close down the relevant services and/or power down external devices. You would leave the Pi running to restart the next morning using a `cron` task.
I don't know if this is still relevant to anyone, but this is how I solved it: In our Company we have tons of Displays that just Display Information, and I was looking, just like the person that asked this question, to reduce the energy my Raspberry Pi's use at night (since no one really needs them at night). I modified /etc/crontab to kill all tasks (specifically all chromium tasks, as we run the info on an html site) at 8pm. After that my PI used 0.5% of their ram. I also disabled the task bar and made the background black. The PI uses just a little more energy than if he was actually turned off (which you could only do with additional hardware). And it's an easy solution. (For turning the PC back on, I modified crontab to reboot at 7am and added the website in autostart (/etc/xdg/lxsession/LXDE-pi/autostart)). As a result, all of our PI's use little to no energy overnight. I hope I was able to help someone that was facing the some problem that we had. I also want to add that in normal circumstances you dont have to worry about turning your PI off, as it uses little to no energy anyways (especially when you're just displaying something).
23,720
I want my raspberryPi to shut down during the night and wake up in the morning. I.e., at 10pm raspberry should shutdown or at least turn of the WiFi and the HDD. At 10am every day my raspberry should wake up or at least turn on the WiFi and the HDD. **How can I do this?** Edit: How can I set a timer to turn of the WiFi and HDD and turn it on again at a certain time?
2014/10/06
[ "https://raspberrypi.stackexchange.com/questions/23720", "https://raspberrypi.stackexchange.com", "https://raspberrypi.stackexchange.com/users/17915/" ]
You could check out the Witty Pi from [UUGear](http://www.uugear.com/store/) as a simple extension to the Raspi. Will do proper startup and shutdown of system, includes real-time clock.
Why do you want to shut down the Pi? The Pi itself uses so little power (<5W) that it is not worthwhile unless you are running on batteries. The B+ uses even less. EDIT 2016-06-18 The following comment is no longer correct. `halt` `shutdown` and `poweroff` all perform a orderly shutdown of the OS. Having said that `halt`ing the Pi puts into a very low power state, but can only be restarted with external events. It is simple to "restart" the `B` or `B+` from the `halt` state using a simple externally driven circuit. This could be a timer or even a light dependent sensor. see <https://raspberrypi.stackexchange.com/a/19754/8697> If your motivation is to limit access you can use `cron` to close down the relevant services and/or power down external devices. You would leave the Pi running to restart the next morning using a `cron` task.
23,720
I want my raspberryPi to shut down during the night and wake up in the morning. I.e., at 10pm raspberry should shutdown or at least turn of the WiFi and the HDD. At 10am every day my raspberry should wake up or at least turn on the WiFi and the HDD. **How can I do this?** Edit: How can I set a timer to turn of the WiFi and HDD and turn it on again at a certain time?
2014/10/06
[ "https://raspberrypi.stackexchange.com/questions/23720", "https://raspberrypi.stackexchange.com", "https://raspberrypi.stackexchange.com/users/17915/" ]
You could check out the Witty Pi from [UUGear](http://www.uugear.com/store/) as a simple extension to the Raspi. Will do proper startup and shutdown of system, includes real-time clock.
I know this is "sorta" cheating, but I found an old laptop for under $20, and I use it to power my Pi. It also runs Linux and has WOL for it's ethernet, so I can simply login to the pi and shut it down, then log in to the laptop and shut it down. Then all i have to do is run etherwake AA:BB:CC... (the hardware address of the laptop's ethernet) and it will also then boot the Pi. Some laptops still send power out of the USB even if not on if it's plugged into the wall so you'll need to do a little research.
23,720
I want my raspberryPi to shut down during the night and wake up in the morning. I.e., at 10pm raspberry should shutdown or at least turn of the WiFi and the HDD. At 10am every day my raspberry should wake up or at least turn on the WiFi and the HDD. **How can I do this?** Edit: How can I set a timer to turn of the WiFi and HDD and turn it on again at a certain time?
2014/10/06
[ "https://raspberrypi.stackexchange.com/questions/23720", "https://raspberrypi.stackexchange.com", "https://raspberrypi.stackexchange.com/users/17915/" ]
Why do you want to shut down the Pi? The Pi itself uses so little power (<5W) that it is not worthwhile unless you are running on batteries. The B+ uses even less. EDIT 2016-06-18 The following comment is no longer correct. `halt` `shutdown` and `poweroff` all perform a orderly shutdown of the OS. Having said that `halt`ing the Pi puts into a very low power state, but can only be restarted with external events. It is simple to "restart" the `B` or `B+` from the `halt` state using a simple externally driven circuit. This could be a timer or even a light dependent sensor. see <https://raspberrypi.stackexchange.com/a/19754/8697> If your motivation is to limit access you can use `cron` to close down the relevant services and/or power down external devices. You would leave the Pi running to restart the next morning using a `cron` task.
While - as joan already put it - it's not possible to shut the RPi completely down and/or start it up by its own hardware, your "at least" demand of turning off WiFi and the HDD could be accomplished with only minor hardware hacking. Joans solution however provides higher savings with respect to electrical energy since the RPi also got no real power-off circuit thus consuming power if `halt`-ed. Find a solution the use the GPIO-Pins to turn of a connected USB device (such as the WiFi dongle) [here](https://raspberrypi.stackexchange.com/questions/2181/turning-on-and-off-a-3g-or-any-usb-port/3342#3342). Be sure to spin down the HDD before turning of its power using tools like `hd-idle`. Be also aware that some users claim reduced life-time of HDDs if spun down to often.
23,720
I want my raspberryPi to shut down during the night and wake up in the morning. I.e., at 10pm raspberry should shutdown or at least turn of the WiFi and the HDD. At 10am every day my raspberry should wake up or at least turn on the WiFi and the HDD. **How can I do this?** Edit: How can I set a timer to turn of the WiFi and HDD and turn it on again at a certain time?
2014/10/06
[ "https://raspberrypi.stackexchange.com/questions/23720", "https://raspberrypi.stackexchange.com", "https://raspberrypi.stackexchange.com/users/17915/" ]
You could check out the Witty Pi from [UUGear](http://www.uugear.com/store/) as a simple extension to the Raspi. Will do proper startup and shutdown of system, includes real-time clock.
I don't know if this is still relevant to anyone, but this is how I solved it: In our Company we have tons of Displays that just Display Information, and I was looking, just like the person that asked this question, to reduce the energy my Raspberry Pi's use at night (since no one really needs them at night). I modified /etc/crontab to kill all tasks (specifically all chromium tasks, as we run the info on an html site) at 8pm. After that my PI used 0.5% of their ram. I also disabled the task bar and made the background black. The PI uses just a little more energy than if he was actually turned off (which you could only do with additional hardware). And it's an easy solution. (For turning the PC back on, I modified crontab to reboot at 7am and added the website in autostart (/etc/xdg/lxsession/LXDE-pi/autostart)). As a result, all of our PI's use little to no energy overnight. I hope I was able to help someone that was facing the some problem that we had. I also want to add that in normal circumstances you dont have to worry about turning your PI off, as it uses little to no energy anyways (especially when you're just displaying something).
23,720
I want my raspberryPi to shut down during the night and wake up in the morning. I.e., at 10pm raspberry should shutdown or at least turn of the WiFi and the HDD. At 10am every day my raspberry should wake up or at least turn on the WiFi and the HDD. **How can I do this?** Edit: How can I set a timer to turn of the WiFi and HDD and turn it on again at a certain time?
2014/10/06
[ "https://raspberrypi.stackexchange.com/questions/23720", "https://raspberrypi.stackexchange.com", "https://raspberrypi.stackexchange.com/users/17915/" ]
The Raspberry Pi doesn't have the hardware needed to shut-down/start-up like a regular desktop PC. The simplest, and possibly most reliable, solution would be to use a timer switch to switch the power to the Pi on and off. If doing so I'd add a cron job on the Pi to do a software shutdown several minutes before the timer shutdown. That would leave the SD card in a safe state.
I know this is "sorta" cheating, but I found an old laptop for under $20, and I use it to power my Pi. It also runs Linux and has WOL for it's ethernet, so I can simply login to the pi and shut it down, then log in to the laptop and shut it down. Then all i have to do is run etherwake AA:BB:CC... (the hardware address of the laptop's ethernet) and it will also then boot the Pi. Some laptops still send power out of the USB even if not on if it's plugged into the wall so you'll need to do a little research.
23,720
I want my raspberryPi to shut down during the night and wake up in the morning. I.e., at 10pm raspberry should shutdown or at least turn of the WiFi and the HDD. At 10am every day my raspberry should wake up or at least turn on the WiFi and the HDD. **How can I do this?** Edit: How can I set a timer to turn of the WiFi and HDD and turn it on again at a certain time?
2014/10/06
[ "https://raspberrypi.stackexchange.com/questions/23720", "https://raspberrypi.stackexchange.com", "https://raspberrypi.stackexchange.com/users/17915/" ]
The Raspberry Pi doesn't have the hardware needed to shut-down/start-up like a regular desktop PC. The simplest, and possibly most reliable, solution would be to use a timer switch to switch the power to the Pi on and off. If doing so I'd add a cron job on the Pi to do a software shutdown several minutes before the timer shutdown. That would leave the SD card in a safe state.
While - as joan already put it - it's not possible to shut the RPi completely down and/or start it up by its own hardware, your "at least" demand of turning off WiFi and the HDD could be accomplished with only minor hardware hacking. Joans solution however provides higher savings with respect to electrical energy since the RPi also got no real power-off circuit thus consuming power if `halt`-ed. Find a solution the use the GPIO-Pins to turn of a connected USB device (such as the WiFi dongle) [here](https://raspberrypi.stackexchange.com/questions/2181/turning-on-and-off-a-3g-or-any-usb-port/3342#3342). Be sure to spin down the HDD before turning of its power using tools like `hd-idle`. Be also aware that some users claim reduced life-time of HDDs if spun down to often.
23,720
I want my raspberryPi to shut down during the night and wake up in the morning. I.e., at 10pm raspberry should shutdown or at least turn of the WiFi and the HDD. At 10am every day my raspberry should wake up or at least turn on the WiFi and the HDD. **How can I do this?** Edit: How can I set a timer to turn of the WiFi and HDD and turn it on again at a certain time?
2014/10/06
[ "https://raspberrypi.stackexchange.com/questions/23720", "https://raspberrypi.stackexchange.com", "https://raspberrypi.stackexchange.com/users/17915/" ]
The Raspberry Pi doesn't have the hardware needed to shut-down/start-up like a regular desktop PC. The simplest, and possibly most reliable, solution would be to use a timer switch to switch the power to the Pi on and off. If doing so I'd add a cron job on the Pi to do a software shutdown several minutes before the timer shutdown. That would leave the SD card in a safe state.
You could use power outlet timer, plug the Pi into that and set it to power up every morning. I think the shutdown command has a schedule flag.
23,720
I want my raspberryPi to shut down during the night and wake up in the morning. I.e., at 10pm raspberry should shutdown or at least turn of the WiFi and the HDD. At 10am every day my raspberry should wake up or at least turn on the WiFi and the HDD. **How can I do this?** Edit: How can I set a timer to turn of the WiFi and HDD and turn it on again at a certain time?
2014/10/06
[ "https://raspberrypi.stackexchange.com/questions/23720", "https://raspberrypi.stackexchange.com", "https://raspberrypi.stackexchange.com/users/17915/" ]
I know this is "sorta" cheating, but I found an old laptop for under $20, and I use it to power my Pi. It also runs Linux and has WOL for it's ethernet, so I can simply login to the pi and shut it down, then log in to the laptop and shut it down. Then all i have to do is run etherwake AA:BB:CC... (the hardware address of the laptop's ethernet) and it will also then boot the Pi. Some laptops still send power out of the USB even if not on if it's plugged into the wall so you'll need to do a little research.
You could use power outlet timer, plug the Pi into that and set it to power up every morning. I think the shutdown command has a schedule flag.
61,666,498
This question is about code styling in Nestjs. This framework suggests file naming lowercase letters and across the dot. Example: file user.service.ts ``` export class UserService { } ``` another file ``` import { UserService } from './user.service' ``` In most cases every file contains one class. I find it convenient to export this class as default and then import the file with the same name file UserService.ts ``` export default class UserService { } ``` another file ``` import UserService from './UserService' ``` Because it is faster and easier. Could you argue to me why I should not do this? Also I don’t understand why the only entity in a file is not exported as default. Are you comfortable working with file names in Nest JS? UPD. One more question: If I have a class name consisting of several words. For example "UserRoleService". What should I name this file? > > userrole.service.ts > > > user-role.service.ts > > > user\_role.service.ts > > > user.role.service.ts > > > It looks weird and not readable. I think CamelCase would be preferable but here we come back where we started
2020/05/07
[ "https://Stackoverflow.com/questions/61666498", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11586849/" ]
This is a very opinionated question which deserves an opinionated answer. File Names ========== The file names are separated as they are for several reasons. 1) it's how Angular does it and Nest is inspired by Angular 2) it means that OSs that treat uppercase and lowercase file names as the same do not get confused (like MacOS) 3) it gives the dev an easy separation point in the file name to look at 4) some tooling in file editors can show different icons depending on the file name. `.ts` might not mean anything other than a typescript file, but `.service.ts` means a Service file written in typescript. (Material Icon Theme with VSCode gives different icons) Exports ======= The other issue you're bringing up is named vs default exports. There isn't much difference in these other than how the import works, but the big thing to recognize is that with a named export (`export class <ClassName>`) you **must** import that class in another file with the same name (though you are able to give it an alias using `as`). With `default exports` you can export anything as default once per file, but you can import it into another file with any name. So if you wanted you could have `export default MyClass` and then have `import SomethingNotRelatedToTheName from path/to/MyClass`. If you feel strongly about it, you can always rewrite and rename your filenames and exports, but don't expect Nest to change that for you, as it is an opinionated framework.
I came a cross this old question, and I think it worths providing this answer for next visitors. Like `@Jay McDoiel` mentioned, this is a very opinionated choice. Either way is correct. **However, I found out that NestJS library used hyphen-separated `user-role.service.ts` file naming as its convention.** Check out my the attached photo below [![enter image description here](https://i.stack.imgur.com/ePaJn.png)](https://i.stack.imgur.com/ePaJn.png)
14,403,498
I have a simple Hibernate query like: ``` from MyEntity where name = ? ``` Nothing fancy, but it's called many times in a fairly big transaction (lasts one second, may load dozens or hundreds of entities). Profiler shows that a lot of time is spent in: ``` org.hibernate.internal.SessionImpl.autoFlushIfRequired(SessionImpl.java:1185) org.hibernate.internal.SessionImpl.list(SessionImpl.java:1240) org.hibernate.internal.QueryImpl.list(QueryImpl.java:101) ``` In other words - flushing changes before running the actual query. Can I somehow prevent Hibernate from doing this flush at all? If not, what can I do to make it faster?
2013/01/18
[ "https://Stackoverflow.com/questions/14403498", "https://Stackoverflow.com", "https://Stackoverflow.com/users/277683/" ]
By default hibernate flushes before issuing a query during a session (FlushMode.AUTO), and chews up lots of CPU time doing it. It is particularly painful if you have a session where many queries and updates run alternately. If the query is likely to select back data that you have inserted/updated/deleted during the current session then you need these flushes. This *may* also be the case even if you haven't modified anything in the current transaction but are using a transaction-isolation level like read-uncommitted. Assuming you don't want uncommitted reads, etc., there are two ways around this that I know of: 1. Select everything you'll need during the session *before* you make any modifications (ie., re-order things so that all your queries are issued before any modifications are made). 2. If you know for sure that you are selecting data that has not been modified in this session then you can explicitly set the flush-mode to something which won't trigger the flush, like this: ``` Query query = session.getNamedQuery(SOME_QUERY_NAME); query.setFlushMode(FlushMode.COMMIT); ```
Hibernate changed its flush logic in version 3.3. Now it will always flush, even if set to `FlushMode.MANUAL`, if it detects you are querying a table for which there are dirty entities. Some workarounds I can think of: * Reorder operations to not query dirty tables and set `FlushMode.COMMIT` or lower. * Detach entities before modification and re-attach later so Hibernate doesn't know they were changed. * Provide a custom [`AutoFlushEventListener`](https://docs.jboss.org/hibernate/core/3.5/javadocs/org/hibernate/event/AutoFlushEventListener.html) with different behaviour. That will require some low-level fiddling and might break something else.
29,535,125
My project needs both accessors. * Access Value using Key (Simple) * Access Key using Value (Bit tricky) Value too will be unique in my project --- Please suggest the better container to use and how ? I would like to use either the STL or BOOST.
2015/04/09
[ "https://Stackoverflow.com/questions/29535125", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1312193/" ]
What you're looking for is called a [bidirectional map](https://en.wikipedia.org/wiki/Bidirectional_map). There isn't one in the STL, but you can take a look at [Boost.Bimap](http://www.boost.org/doc/libs/1_55_0/libs/bimap/doc/html/) for another implementation. If you want to implement it yourself, you can simply use two regular one-way maps. If you use pointers, there should be little memory overhead and decent performance.
If you want the either way access, ie *key->value and value->key*, chances are that your design doesn't need an associative container like a `map` Try a `vector` of [std::pair](http://en.cppreference.com/w/cpp/utility/pair). On a side note, if you need to store more than two values, you can use [std::tuple](http://en.cppreference.com/w/cpp/utility/tuple). HTH!!
29,535,125
My project needs both accessors. * Access Value using Key (Simple) * Access Key using Value (Bit tricky) Value too will be unique in my project --- Please suggest the better container to use and how ? I would like to use either the STL or BOOST.
2015/04/09
[ "https://Stackoverflow.com/questions/29535125", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1312193/" ]
That's what I used in my project two days ago. ``` #include <boost/bimap.hpp> class ClientManager { typedef boost::bimap< boost::bimaps::set_of<int>, boost::bimaps::set_of<int> > ConnectedUsers; // User Id, Instance Id ConnectedUsers m_connectedUsers; public: int getUserId(int instanceId); int getInstanceId(int userId); }; int ClientManager::getInstanceId(int userId) { auto it = m_connectedUsers.left.find(userId); return it->second; } int ClientManager::getUserId(int instanceId) { auto it = m_connectedUsers.right.find(instanceId); return it->second; } ... // Insert m_connectedUsers.insert(ConnectedUsers::value_type(id, instanceId)); // Erase m_connectedUsers.left.erase(userId); ```
If you want the either way access, ie *key->value and value->key*, chances are that your design doesn't need an associative container like a `map` Try a `vector` of [std::pair](http://en.cppreference.com/w/cpp/utility/pair). On a side note, if you need to store more than two values, you can use [std::tuple](http://en.cppreference.com/w/cpp/utility/tuple). HTH!!
44,519,722
Please, I was using **log4j** input of logstash, it was allowing me to **skip log parsing** (grok ...). ``` `input { log4j { mode => "server" host => "0.0.0.0" port => 8090 } }` ``` Elastic now, in version [5.4.1](https://www.elastic.co/guide/en/logstash/current/plugins-inputs-log4j.html), is tagging this input as ***deprecated***, and the alternative now is **filebeats**, which listen on log files directly. The problem is that you need to parse your log files again via **grok filter**...is there any possible way to use beats for log4j without parsing log lines again, exactly like the old log4j socketAppender ? Thank you
2017/06/13
[ "https://Stackoverflow.com/questions/44519722", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5164226/" ]
The log4j [socket appender](https://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/net/SocketAppender.html) does not use a layout. It sends the data in a structured format such that grok is not required. To achieve a similar result you could configure log4j to write the data to log files in a structured format. This is commonly done with the [JSON layout](https://logging.apache.org/log4j/2.x/manual/layouts.html#JSONLayout). So configure your app's log4j settings to write JSON events to a file. Then once you have your logs in a structured format you can configure Filebeat to read the logs, decode the JSON data, and forward the events to Logstash or Elasticsearch. ``` filebeat.prospectors: - type: log paths: - /var/log/myapp/output*.json json.keys_under_root: true json.add_error_key: true json.message_key: message ```
You can use `logstash-logback-encoder`, it provides a `LogstashSocketAppender`, which implement SocketAppender, and using RSysLog to send log in json format to elasticsearch.
64,299,118
I'm trying to make a generic stack and queue class that uses the generic node class. It has `empty()`, `pop()`, `peek()`, `push()`, and a `search()` method. I know there is a built-in `Stack` class and stack `search` method but we have to make it by using the `Node` class. I am unsure of how to make the `search` method. The `search` method is supposed to return the distance from the top of the stack of the occurrence that is nearest the top of the stack. The topmost item is considered to be at distance 1; the next item is at distance 2; etc. My classes are below: ``` import java.io.*; import java.util.*; public class MyStack<E> implements StackInterface<E> { private Node<E> head; private int nodeCount; public static void main(String args[]) { } public E peek() { return this.head.getData(); } public E pop() { E item; item = head.getData(); head = head.getNext(); nodeCount--; return item; } public boolean empty() { if (head==null) { return true; } else { return false; } } public void push(E data) { Node<E> head = new Node<E>(data); nodeCount++; } public int search(Object o) { // todo } } public class Node<E> { E data; Node<E> next; // getters and setters public Node(E data) { this.data = data; this.next = null; } public E getData() { return data; } public void setData(E data) { this.data = data; } public Node<E> getNext() { return next; } public void setNext(Node<E> next) { this.next = next; } } public class MyQueue<E> implements QueueInterface<E> { private Node<E> head; private int nodeCount; Node<E> rear; public MyQueue() { this.head = this.rear = null; } public void add(E item){ Node<E> temp = new Node<E>(item); if (this.rear == null) { this.head = this.rear = temp; return; } this.rear.next = temp; this.rear = temp; } public E peek(){ return this.head.getData(); } public E remove(){ E element = head.getData(); Node<E> temp = this.head; this.head = this.head.getNext(); nodeCount--; return element; } } ``` After working on it based off of the first comment I have this: ``` public int search(Object o){ int count=0; Node<E> current = new Node<E> (head.getData()); while(current.getData() != o){ current.getNext(); count++; } return count; } ``` It doesn't have any errors but I cannot tell if it is actually working correctly. Does this seem correct?
2020/10/10
[ "https://Stackoverflow.com/questions/64299118", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14270806/" ]
`str.split(" ")` does the exact same thing in both cases. It creates an anonymous list of the split strings. In the second case you have the minor overhead of assigning it to a variable and then fetching the value of the variable. Its wasted time if you don't need to keep the object for other reasons. But this is a trivial amount of time compared to other object referencing taking place in the same loop. Alternative 2 also leaves the data in memory which is another small performance issue. The real reason Alternative 1 is better than 2, IMHO, is that it doesn't leave the hint that `splittedStr` is going to be needed later.
Look my friend, if you want to actually reduce the amount of time in the code in general,loop on a tuple instead of list but assigning the result in a variable then using the variable is not the best approach is you just reserved a memory location just to store the value but sometimes you can do that just for the sake of having a clean code like if you have more than one operation in one line like ``` min(str.split(mylist)[3:10]) ``` In this case, it is better to have a variable called min\_value for example just to make things cleaner. returning back to the performance issue, you could actually notice the difference in performance if you loop through a list or a tuple like This is looping through a tuple ``` for i in (1,2,3): print(i) ``` & This is looping through a list ``` for i in [1,2,3]: print(i) ``` you will find that using tuple will be faster !
7,517,887
I have been using DDD for a while know so I am comfortable with the idea of aggregates. At first I did have troubles wrapping my head around not using/persisting references to other root aggregates but I think I'm on board... so: * Storing a root aggregate as a one document.... check * Using denormalized references containing properties that do not change or rarely change.... check For the times that I DO want to have a full reference to another root aggregate, I understand it is recommended that I persist a reference to its ID and can use the RavenDB client API's *Includes* to retrieve all the entities efficiently. That handles the data part, what I haven't seen is the best way to handle this in my entity class: 1. Have both *Product* and *ProductId* properties in my class using **[JsonIgnore]** on the *Product* to ensure it doesn't get persisted with the document. * The full object graph could then be glued back together in the repository (using API's *Includes* for efficiency) or I could inject a service into the entity that would fetch *Product* lazily (possible N+1 hit) 2. Glue it back together in a ViewModel. I don't like this idea as I could end up with an unexpected NULL reference in the domain if not used correctly. 3. Some other obvious way that I'm not seeing? Thoughts?
2011/09/22
[ "https://Stackoverflow.com/questions/7517887", "https://Stackoverflow.com", "https://Stackoverflow.com/users/285874/" ]
In DDD there are at least two valid points of view. Some ppl link root aggregates only by ID or another valid key and second is using platform specific references to other objects. Both has it's own pros and cons. With NoSql solutions like RavenDb, it's probably better to use first approach, because second is just technically wrong.
You are going explicitly against the recommended design here, why *do* you want a Product property refering to another aggregate? What does it gives you?
1,151,461
I'm looking to take a whole system backup and store it on S3. Something that could be good enough to restore my entire system. But I've been told that using dd/rsync to capture the root directory will save a lot of extraneous files that I wouldn't need to restore the system. In the event that I had to reply on this backup, I would need to restore: * The home directory * All installed programs * All customizations throughout the system, such as edits to the Openbox configuration file, etc The command I see recommended [here](https://www.ostechnix.com/backup-entire-linux-system-using-rsync/) is: ``` sudo rsync -aAXv / --exclude={"/dev/*","/proc/*","/sys/*","/tmp/*","/run/*","/mnt/*","/media/*","/lost+found"} /mnt ``` Is it possible to go lighter than that?
2019/06/16
[ "https://askubuntu.com/questions/1151461", "https://askubuntu.com", "https://askubuntu.com/users/510490/" ]
You might look at a combination of `Backups` (Déjà Dup) for your /home, and `Timeshift` for the system stuff. Otherwise, use `Macrium Reflect` to clone your entire disk/partition. The closest thing to a Windows-like restore point is by using `Timeshift`. I use it to save snapshots to an external USB hard drive. Although it can, it's normally not used for backing up your /home directory, just system-level changes. Use `Backups` (Déjà Dup) for backing up /home files. ``` Timeshift is a system restore utility which takes snapshots of the system at regular intervals. These snapshots can be restored at a later date to undo system changes. Creates incremental snapshots using rsync or BTRFS snapshots using BTRFS tools. ``` More information at <https://github.com/teejee2008/timeshift> For pre-19.04 users, add the PPA: ``` sudo add-apt-repository -y ppa:teejee2008/ppa ``` And install with: ``` sudo apt update sudo apt install timeshift ```
From: [Bash script to backkup/clone Ubuntu to another partition](https://askubuntu.com/questions/1028604/bash-script-to-backkup-clone-ubuntu-to-another-partition/1028605#1028605) ``` rsync -haxAX --stats --delete --info=progress2 --info=name0 --inplace \ /* "$TargetMnt" \ --exclude={/dev/*,/proc/*,/sys/*,/tmp/*,/run/*,/mnt/*,/media/*,/lost+found} ``` The script also updates `/boot/grub/grub.cfg` and `/etc/fstab` so you can boot your backup.
123,071
As a follow up to [my recent question](https://tex.stackexchange.com/questions/123002/problem-with-custom-vertical-alignment-and-or-length-of-lines-rules-in-tabular-e): Now I'd like to put some color on to that line/rule. In the MWE below, `\arrayrulecolor{blue}\mycline{1-1}` throws an error (`undefined control sequence` with respect to `\arrayrulecolor`). How can I make `\mycline` accept a color? ``` % \PassOptionsToPackage{table}{xcolor} \documentclass[a4paper]{article} % \usepackage{booktabs} % \usepackage{array} \newlength{\mycustomlength} \settowidth\mycustomlength{blaaaaaaaa} \makeatletter \def\mycline#1{\expandafter\my@cline\@cline#1\@nil} \def\my@cline#1\leaders#2\hfill{% #1\hfill\leaders#2\hskip\mycustomlength\hfill\kern\z@} \makeatother %%%%%%%%%%%%%%%%%%%%%%%% \usepackage[framemethod=TikZ, xcolor=RGB,table]{mdframed} % \usepackage[RGB]{xcolor} \definecolor{mycolor}{RGB}{0,111,222} \mdfsetup{skipabove=\topskip,skipbelow=\topskip, nobreak=true, innertopmargin=0.5\baselineskip, innerbottommargin=0.5\baselineskip, frametitleaboveskip=3pt, frametitlebelowskip=2pt, skipabove=\topskip,skipbelow=\topskip} \mdfdefinestyle{my_style}{% linecolor=mycolor,middlelinewidth=0.7pt, frametitlebackgroundcolor=mycolor} \usepackage{tabularx} \usepackage{multirow} %------------------------------------ \begin{document} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \begin{mdframed}[style=my_style,frametitle=\color{white}{OOO}] \begin{tabularx}{\textwidth}{@{}*{1}{|p{\mycustomlength}|}*{1}{X}@{}} \textbf{AAAAAA} & \\ \mycline{1-1} %%%\arrayrulecolor{blue}\mycline{1-1} % \cline{1-1} aaaaaaaaa & \textbf{aaaa} \\ aaaa & \textbf{aa} \\ \\ \textbf{BBBB} & \\ % \rule{\mycustomlength}{0.4pt} % & \\ % \\ % \cline{1-1} \mycline{1-1} bbb & bbbbbbbbb \textbf{b} \\ bbbbb & \textbf{B} \\ \end{tabularx} % \end{tabulary} \end{mdframed} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % \lipsum \end{document} ``` Cf. also: * [Clash among packages?](https://tex.stackexchange.com/questions/52973/clash-among-packages) and * [How to use table in mdframed?](https://tex.stackexchange.com/questions/50543/how-to-use-table-in-mdframed) Note that *in theory* `mdframed` should load `xcolor` which in turn should load `colortbl` *(cf. the resp. documentation files)*. But there seem multiple ways of calling these packages; and apart from *how* they are called/loaded the order in which they are called/loaded also matters...
2013/07/08
[ "https://tex.stackexchange.com/questions/123071", "https://tex.stackexchange.com", "https://tex.stackexchange.com/users/27721/" ]
Your MWE generates an unknown option error for mdfamed with the version I have, so I removed that and loaded `colortbl` which otherwise wasn't loaded. Since `colortbl` redefines `\cline` The patch in the previous answer didn't match and you need a modified one. ![enter image description here](https://i.stack.imgur.com/db4bN.png) ``` \documentclass[a4paper]{article} % \usepackage{booktabs} % \usepackage{array} \usepackage{colortbl} \newlength{\mycustomlength} \settowidth\mycustomlength{blaaaaaaaa} \makeatletter \def\mycline#1{\expandafter\my@cline\@cline#1\@nil} \def\my@cline#1\@multispan\@ne#2{% #1\@multispan\@ne {\CT@arc@\hfill\leaders\hrule\@height\arrayrulewidth\hskip\mycustomlength\hfill\kern\z@}}% \makeatother %%%%%%%%%%%%%%%%%%%%%%%% \usepackage[framemethod=TikZ, xcolor=RGB]{mdframed} % \usepackage[RGB]{xcolor} \definecolor{mycolor}{RGB}{0,111,222} \mdfsetup{skipabove=\topskip,skipbelow=\topskip, nobreak=true, innertopmargin=0.5\baselineskip, innerbottommargin=0.5\baselineskip, frametitleaboveskip=3pt, frametitlebelowskip=2pt, skipabove=\topskip,skipbelow=\topskip} \mdfdefinestyle{my_style}{% linecolor=mycolor,middlelinewidth=0.7pt, frametitlebackgroundcolor=mycolor} \usepackage{tabularx} \usepackage{multirow} %------------------------------------ \begin{document} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \begin{mdframed}[style=my_style,frametitle=\color{white}{OOO}] \arrayrulecolor{blue} \begin{tabularx}{\textwidth}{@{}*{1}{|p{\mycustomlength}|}*{1}{X}@{}} \textbf{AAAAAA} & \\ \mycline{1-1} %%%\arrayrulecolor{blue}\mycline{1-1} % \cline{1-1} aaaaaaaaa & \textbf{aaaa} \\ aaaa & \textbf{aa} \\ \\ \textbf{BBBB} & \\ % \rule{\mycustomlength}{0.4pt} % & \\ % \\ % \cline{1-1} \mycline{1-1} bbb & bbbbbbbbb \textbf{b} \\ bbbbb & \textbf{B} \\ \end{tabularx} % \end{tabulary} \end{mdframed} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % \lipsum \end{document} ```
To understand the error related to `mdframed` I want to provide a small answer. Options are separated by commas, so your input ``` \usepackage[framemethod=TikZ, xcolor=RGB,table]{mdframed} ``` is passing the options to `mdframed`: 1. `framemethod=TikZ` == known 2. `xcolor=RGB` == known 3. `table`== unknown If you want to pass a value to an option which contains a comma, you have to embrace it. So the correct syntax is: ``` \usepackage[framemethod=TikZ, xcolor={RGB,table}]{mdframed} ``` Now you are passing two options to `mdframed`. --- But why does it have no effect? I decided to implement the option `xcolor` in the following way: If the package `xcolor` is already loaded, ignore all options. The package TikZ loads `xcolor` and so the options of `xcolor` are ignored. To add options to `xcolor` you can do the following: 1. Load `xcolor` separately ``` \usepackage[table,RGB]{xcolor} \usepackage[framemethod=TikZ]{mdframed} ``` 2. Pass options to `xcolor` via `\PassOptionsToPackage` ``` \PassOptionsToPackage{table,RGB}{xcolor} \usepackage[framemethod=TikZ]{mdframed} ``` 3. Change the order of the options: ``` \usepackage[xcolor={RGB,table},framemethod=TikZ]{mdframed} ``` I recommend the first method.
12,951
They both mean medium, so they are probably the same. Are they?
2015/04/07
[ "https://chinese.stackexchange.com/questions/12951", "https://chinese.stackexchange.com", "https://chinese.stackexchange.com/users/8119/" ]
The difference between "载体" and "媒介" in Chinese is equivalent to the difference between "Carrier" and "Medium" in English. So, you pretty much can figure this out immediately after I told you that, if your English is well enough.
Usually they are the same thing. FYI,if 载体carrier is something, Media媒介 is everything. whole meaning on media: <http://www.businessdictionary.com/definition/media.html> carrier, mostly means practical channel like radio, newspaper, internet,etc. So in this point the meaning are the same, means of communication, as radio and television, newspapers, and magazines, that reach or influence people widely
12,951
They both mean medium, so they are probably the same. Are they?
2015/04/07
[ "https://chinese.stackexchange.com/questions/12951", "https://chinese.stackexchange.com", "https://chinese.stackexchange.com/users/8119/" ]
Very interesting! Both semantics and syntax mixed up in here. 載體 is a noun. It is the thing which moves a to b; definitely a new sounding word, yet I found one example from 1965! In biology, such as virology or genetic technology, 載體 is a "vector", so we have words like 病毒載體 viral vector, for which there is a Chinese wikipedia article. It is also used in transportation, and the example from 1965 refers to a rocket "carrier" for a satellite where a stage failed to separate. It is a term of art, and this already makes it very different from 媒介. But there are important differences in meaning as well. Here is an example where 媒介 works and 載體 doesn't: 沒有第三國為媒介,日本政府仍舊能夠以其他方法將上述態度通知俄國... Even without a third country as an intermediary, Japan can still still express its views to Russia by other means. Nothing is being carried, so 載體 doesn't work. Here 媒介 means to act as intermediary, not as a carrier. Here is another example: 人與神交往,就以血作為媒介 When men and gods interact, they do so through the medium of blood. This is talking about the use of sacrificial blood to communicate with gods. There is no "intermediary" here, but 'blood' is clearly an intermediate mechanism or means for the communication. "medium" fits here, but 載體 doesn't. Unlike 載體, 媒介 can also be a verb. Here is an example that took some time to find: 蜜峰因採蜜而媒介了花粉,動機還不是由於自私. Honey bees convey pollen through collecting honey (?) and their motive is by no means selfish. 載體 is impossible here. Perhaps we could translate this as "convey"? It can also be used for more abstract ideas: 資訊網最新的網路交易市場功能,更為國內廠商媒介了三萬多個商機 The information network's latest online exchange market functions has also introduced over 30,000 business opportunities for domestic manufacturers. Here "媒介" is really close to its original "matchmaker" sense. Anyway, an interesting contrast. Good question.
这可能有习惯用语的成分在里面,通常: * 声音以空气为媒介传递,而较少说声音以空气为载体。 * 通灵师(从事迷信活动并获得报酬的人)的肉体可以作为现世(the alive world)与彼岸(the dead world)联系的媒介,而较少说通灵师的肉体是某载体。 * 信息传输以电磁波或光波为载体,而较少说信息传输以电磁波为媒介。 * 磁带作为信息的载体,而较少说磁带作为信息的媒介。 * 蜜蜂充当了花粉授粉的媒介,而较少说蜜蜂充当了授粉的载体。 可以认为,载体是一种媒介物,因此媒介的范畴通常要宽泛一些,但考虑到一些习惯用法因此实际上并不绝对。
12,951
They both mean medium, so they are probably the same. Are they?
2015/04/07
[ "https://chinese.stackexchange.com/questions/12951", "https://chinese.stackexchange.com", "https://chinese.stackexchange.com/users/8119/" ]
The difference between "载体" and "媒介" in Chinese is equivalent to the difference between "Carrier" and "Medium" in English. So, you pretty much can figure this out immediately after I told you that, if your English is well enough.
just like English, Chinese language's words and expressions are used in circumstances and may link to different aspects as the context changes. 载体 is more related to carrier, bearing something on it, holder of something, while 媒介 is more related to medium, pipe, conducting something, or the intermediate interface between things. 载体: [used more in circumstances related to material or things or physical constructs. more as a carrier] 媒介: [used more in circumstances related to human, social, media, and interpersonal relationships. more as an interface]
12,951
They both mean medium, so they are probably the same. Are they?
2015/04/07
[ "https://chinese.stackexchange.com/questions/12951", "https://chinese.stackexchange.com", "https://chinese.stackexchange.com/users/8119/" ]
The difference between "载体" and "媒介" in Chinese is equivalent to the difference between "Carrier" and "Medium" in English. So, you pretty much can figure this out immediately after I told you that, if your English is well enough.
这可能有习惯用语的成分在里面,通常: * 声音以空气为媒介传递,而较少说声音以空气为载体。 * 通灵师(从事迷信活动并获得报酬的人)的肉体可以作为现世(the alive world)与彼岸(the dead world)联系的媒介,而较少说通灵师的肉体是某载体。 * 信息传输以电磁波或光波为载体,而较少说信息传输以电磁波为媒介。 * 磁带作为信息的载体,而较少说磁带作为信息的媒介。 * 蜜蜂充当了花粉授粉的媒介,而较少说蜜蜂充当了授粉的载体。 可以认为,载体是一种媒介物,因此媒介的范畴通常要宽泛一些,但考虑到一些习惯用法因此实际上并不绝对。
12,951
They both mean medium, so they are probably the same. Are they?
2015/04/07
[ "https://chinese.stackexchange.com/questions/12951", "https://chinese.stackexchange.com", "https://chinese.stackexchange.com/users/8119/" ]
The difference between "载体" and "媒介" in Chinese is equivalent to the difference between "Carrier" and "Medium" in English. So, you pretty much can figure this out immediately after I told you that, if your English is well enough.
I think 媒介 refers to the environment. Say A and B are both in the air/space/water/etc, here the air/space/water/etc is 媒介. If A gives B something through C, then C is 载体.
12,951
They both mean medium, so they are probably the same. Are they?
2015/04/07
[ "https://chinese.stackexchange.com/questions/12951", "https://chinese.stackexchange.com", "https://chinese.stackexchange.com/users/8119/" ]
Usually they are the same thing. FYI,if 载体carrier is something, Media媒介 is everything. whole meaning on media: <http://www.businessdictionary.com/definition/media.html> carrier, mostly means practical channel like radio, newspaper, internet,etc. So in this point the meaning are the same, means of communication, as radio and television, newspapers, and magazines, that reach or influence people widely
这可能有习惯用语的成分在里面,通常: * 声音以空气为媒介传递,而较少说声音以空气为载体。 * 通灵师(从事迷信活动并获得报酬的人)的肉体可以作为现世(the alive world)与彼岸(the dead world)联系的媒介,而较少说通灵师的肉体是某载体。 * 信息传输以电磁波或光波为载体,而较少说信息传输以电磁波为媒介。 * 磁带作为信息的载体,而较少说磁带作为信息的媒介。 * 蜜蜂充当了花粉授粉的媒介,而较少说蜜蜂充当了授粉的载体。 可以认为,载体是一种媒介物,因此媒介的范畴通常要宽泛一些,但考虑到一些习惯用法因此实际上并不绝对。
12,951
They both mean medium, so they are probably the same. Are they?
2015/04/07
[ "https://chinese.stackexchange.com/questions/12951", "https://chinese.stackexchange.com", "https://chinese.stackexchange.com/users/8119/" ]
The difference between "载体" and "媒介" in Chinese is equivalent to the difference between "Carrier" and "Medium" in English. So, you pretty much can figure this out immediately after I told you that, if your English is well enough.
Very interesting! Both semantics and syntax mixed up in here. 載體 is a noun. It is the thing which moves a to b; definitely a new sounding word, yet I found one example from 1965! In biology, such as virology or genetic technology, 載體 is a "vector", so we have words like 病毒載體 viral vector, for which there is a Chinese wikipedia article. It is also used in transportation, and the example from 1965 refers to a rocket "carrier" for a satellite where a stage failed to separate. It is a term of art, and this already makes it very different from 媒介. But there are important differences in meaning as well. Here is an example where 媒介 works and 載體 doesn't: 沒有第三國為媒介,日本政府仍舊能夠以其他方法將上述態度通知俄國... Even without a third country as an intermediary, Japan can still still express its views to Russia by other means. Nothing is being carried, so 載體 doesn't work. Here 媒介 means to act as intermediary, not as a carrier. Here is another example: 人與神交往,就以血作為媒介 When men and gods interact, they do so through the medium of blood. This is talking about the use of sacrificial blood to communicate with gods. There is no "intermediary" here, but 'blood' is clearly an intermediate mechanism or means for the communication. "medium" fits here, but 載體 doesn't. Unlike 載體, 媒介 can also be a verb. Here is an example that took some time to find: 蜜峰因採蜜而媒介了花粉,動機還不是由於自私. Honey bees convey pollen through collecting honey (?) and their motive is by no means selfish. 載體 is impossible here. Perhaps we could translate this as "convey"? It can also be used for more abstract ideas: 資訊網最新的網路交易市場功能,更為國內廠商媒介了三萬多個商機 The information network's latest online exchange market functions has also introduced over 30,000 business opportunities for domestic manufacturers. Here "媒介" is really close to its original "matchmaker" sense. Anyway, an interesting contrast. Good question.
12,951
They both mean medium, so they are probably the same. Are they?
2015/04/07
[ "https://chinese.stackexchange.com/questions/12951", "https://chinese.stackexchange.com", "https://chinese.stackexchange.com/users/8119/" ]
just like English, Chinese language's words and expressions are used in circumstances and may link to different aspects as the context changes. 载体 is more related to carrier, bearing something on it, holder of something, while 媒介 is more related to medium, pipe, conducting something, or the intermediate interface between things. 载体: [used more in circumstances related to material or things or physical constructs. more as a carrier] 媒介: [used more in circumstances related to human, social, media, and interpersonal relationships. more as an interface]
这可能有习惯用语的成分在里面,通常: * 声音以空气为媒介传递,而较少说声音以空气为载体。 * 通灵师(从事迷信活动并获得报酬的人)的肉体可以作为现世(the alive world)与彼岸(the dead world)联系的媒介,而较少说通灵师的肉体是某载体。 * 信息传输以电磁波或光波为载体,而较少说信息传输以电磁波为媒介。 * 磁带作为信息的载体,而较少说磁带作为信息的媒介。 * 蜜蜂充当了花粉授粉的媒介,而较少说蜜蜂充当了授粉的载体。 可以认为,载体是一种媒介物,因此媒介的范畴通常要宽泛一些,但考虑到一些习惯用法因此实际上并不绝对。
12,951
They both mean medium, so they are probably the same. Are they?
2015/04/07
[ "https://chinese.stackexchange.com/questions/12951", "https://chinese.stackexchange.com", "https://chinese.stackexchange.com/users/8119/" ]
I think 媒介 refers to the environment. Say A and B are both in the air/space/water/etc, here the air/space/water/etc is 媒介. If A gives B something through C, then C is 载体.
这可能有习惯用语的成分在里面,通常: * 声音以空气为媒介传递,而较少说声音以空气为载体。 * 通灵师(从事迷信活动并获得报酬的人)的肉体可以作为现世(the alive world)与彼岸(the dead world)联系的媒介,而较少说通灵师的肉体是某载体。 * 信息传输以电磁波或光波为载体,而较少说信息传输以电磁波为媒介。 * 磁带作为信息的载体,而较少说磁带作为信息的媒介。 * 蜜蜂充当了花粉授粉的媒介,而较少说蜜蜂充当了授粉的载体。 可以认为,载体是一种媒介物,因此媒介的范畴通常要宽泛一些,但考虑到一些习惯用法因此实际上并不绝对。
12,951
They both mean medium, so they are probably the same. Are they?
2015/04/07
[ "https://chinese.stackexchange.com/questions/12951", "https://chinese.stackexchange.com", "https://chinese.stackexchange.com/users/8119/" ]
They have different meanings but in practical they are used interchangeable especially about mass media. 載體, from its sense, it is holder and container. 媒介, it is an agent that allows two or more parties interact.
这可能有习惯用语的成分在里面,通常: * 声音以空气为媒介传递,而较少说声音以空气为载体。 * 通灵师(从事迷信活动并获得报酬的人)的肉体可以作为现世(the alive world)与彼岸(the dead world)联系的媒介,而较少说通灵师的肉体是某载体。 * 信息传输以电磁波或光波为载体,而较少说信息传输以电磁波为媒介。 * 磁带作为信息的载体,而较少说磁带作为信息的媒介。 * 蜜蜂充当了花粉授粉的媒介,而较少说蜜蜂充当了授粉的载体。 可以认为,载体是一种媒介物,因此媒介的范畴通常要宽泛一些,但考虑到一些习惯用法因此实际上并不绝对。
32,138,637
When writing code like this, why is the y axis inverted, meaning positive values make an object go down while negative values make it go up? ``` animation.update(); if(up){ dy -=1.1; } else{ dy +=1.1; } if(dy>14)dy = 14; if(dy<-14)dy = -14; y += dy*2; dy = 0; } public void draw(Canvas canvas) { canvas.drawBitmap(animation.getImage(),x,y,null); } ```
2015/08/21
[ "https://Stackoverflow.com/questions/32138637", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5162815/" ]
Please note that the origin `(0,0)` in Android screen is situated at **top-left** corner of the screen. Thus, when you add values to `y axis` the object go towards bottom and when subtract values the object goes upwards. In Android devices: ``` Origin | V *------------------------------- | ----> X axis | | | | | | | | V Y-axis | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | ------------------------------- ``` **Possible History:** As screen space calculations started when television sets were used as screens. The raster gun of a TV is also starting at the **top left** corner, so this was accepted as the origin. For further reference you can refer [here](https://stackoverflow.com/questions/11483345/how-do-android-screen-coordinates-work) **Transformations**: However, you can use the transformation of coordinates in android using `Canvas.setMatrix()`. You can flip your `Canvas` with using ``` canvas.translate(0,canvas.getHeight()); canvas.scale(1, -1) ``` to shift it to the correct location. You can refer [here](http://developer.android.com/reference/android/graphics/Canvas.html#translate%28float,%20float%29) for transformation.
This is the common way, in which computer displays are addressed. It stems probably from that video memory is mapped to screen row-by-row from the top left corner, which in turn most likely comes from the fact that this way electron beam swept the screen in old CRT displays. You can change the coordinate system to be more "mathematical" by using `Canvas.setMatrix()` with appropriate transforma matrix. In order to create a "mirroring" transform matrix, use -1 as a parameter to the scale operation (i.e. `matrix.setScale(0, -1)`)
67,990,201
I have one ugly text file that looks like this: ``` 2020-06-13 ---------------------------------------- |Order |Warehouse|Stock|Price|Vendor| |--------------------------------------| |31434 |WA12 |200 |160 |AS12 | |31435 |WA11 |26 |12 |AS11 | |31436 |WA13 |202 |161 |AS16 | ---------------------------------------- 2020-06-14 ---------------------------------------- |Order |Warehouse|Stock|Price|Vendor| |--------------------------------------| |31437 |WA12 |200 |160 |AS12 | |31438 |WA11 |26 |12 |AS11 | |31439 |WA13 |202 |161 |AS16 | ---------------------------------------- ``` I try to parse it using the read\_csv function like so: ``` df = pd.read_csv(file, sep='|', error_bad_lines=False) ``` But my dataframe comes out with a lot of notable problems: First problem, the first dashed lines (before the headers) and I also assume the last dashed lines (the footer) get inserted into the *Material* column and every other field in that row (Warehouse, Stock, Price, Vendor) is set to NaN * Is there a way to skip these dashed lines: `----------------------------------------` ? * Second problem, is the separator | which shows up before and after the headers. Before *Order* and after *Vendor* |*Order* |Warehouse|Stock|Price|*Vendor*| This make pandas return two NaN headers with empty values inside of them * Third problem is how to ignore this line |--------------------------------------| as well? Sorry if this question sounds confusing. I'm confused as well if this is the proper way to do it by changing the parameters the read\_csv function takes or do I need to normalize/sanitize/clean the file before sending it to the read\_csv function by doing some pure python? Thank you
2021/06/15
[ "https://Stackoverflow.com/questions/67990201", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16235371/" ]
This data is really tricky as you said, So, we have to pay logic another way around: raw\_data as provided: ---------------------- ``` $ cat weired_data ---------------------------------------- |Order |Warehouse|Stock|Price|Vendor| |--------------------------------------| |31434 |WA12 |200 |160 |AS12 | |31435 |WA11 |26 |12 |AS11 | |31436 |WA13 |202 |161 |AS16 | ---------------------------------------- 2020-06-14 ---------------------------------------- |Order |Warehouse|Stock|Price|Vendor| |--------------------------------------| |31437 |WA12 |200 |160 |AS12 | |31438 |WA11 |26 |12 |AS11 | |31439 |WA13 |202 |161 |AS16 | ---------------------------------------- ``` Cleaning data to form DataFrame: -------------------------------- This is how you can parse your data to create a desired DataFrame: ``` #!/home/nxf59093/Karn_python3/bin/python import pandas as pd ##### Python pandas, widen output display to see more columns. #### #pd.set_option('display.height', None) pd.set_option('display.max_rows', None) pd.set_option('display.max_columns', None) pd.set_option('display.width', None) pd.set_option('expand_frame_repr', True) ################################################################## # read the with `read_csv` df = pd.read_csv("weired_data") # replace all hyphens and pipes using `str.replace` df['2020-06-13'] = df['2020-06-13'].str.replace('|', '') df['2020-06-13'] = df['2020-06-13'].str.replace('-', '') # as every row contains `31` and that's the way to pick the lines df = df[df['2020-06-13'].str.contains('31')] # as default it has `2020-06-13` column name hence we'll Limit # number of splits in output by using `n=5` as we need 5 columns which # will return ` 0 1 2 3 4` columns names df = df['2020-06-13'].str.split(n=5, expand=True) # as we have got column names which we can rename as we want them to be df = df.rename(columns={0: 'Order', 1: 'Warehouse', 2: 'Stock', 3: 'Price', 4: 'Vendor'}) print(df) ``` Desired Parsed DataFrame: ------------------------- ``` $ ./test_data.py Order Warehouse Stock Price Vendor 3 31434 WA12 200 160 AS12 4 31435 WA11 26 12 AS11 5 31436 WA13 202 161 AS16 11 31437 WA12 200 160 AS12 12 31438 WA11 26 12 AS11 13 31439 WA13 202 161 AS16 ``` **Another Method with less slicing:** ``` df = pd.read_csv("weired_data", sep="|", skiprows=2, index_col=0) df = df.dropna(axis=0,how='all') df.columns = df.columns.str.replace(' ', '') df = df[df['Order'].str.contains('31')] df = df.reset_index() df = df.dropna(axis=1,how='all') print(df) ``` **Result:** ``` Order Warehouse Stock Price Vendor 0 31434 WA12 200 160 AS12 1 31435 WA11 26 12 AS11 2 31436 WA13 202 161 AS16 3 31437 WA12 200 160 AS12 4 31438 WA11 26 12 AS11 5 31439 WA13 202 161 AS16 ``` In case you want your data to be looked like as sql tables then you need to use tabulate and print that . ``` from tabulate import tabulate print(tabulate(df, headers='keys', tablefmt='psql', showindex=False)) +-----------+-------------+---------+---------+----------+ | Order | Warehouse | Stock | Price | Vendor | |-----------+-------------+---------+---------+----------| | 31434 | WA12 | 200 | 160 | AS12 | | 31435 | WA11 | 26 | 12 | AS11 | | 31436 | WA13 | 202 | 161 | AS16 | | 31437 | WA12 | 200 | 160 | AS12 | | 31438 | WA11 | 26 | 12 | AS11 | | 31439 | WA13 | 202 | 161 | AS16 | +-----------+-------------+---------+---------+----------+ ```
Maybe this will work for you. ``` import pandas as pd import re file = open('weird_data.txt', 'r').read() ###Removing strange characters### to_replace = ['\n', '--------------------------------------', ' '] for char in to_replace: file = file.replace(char, '') file = file.replace('--', '') ###Removing column names. I will only work with the pattern### column_names = ['Order','Warehouse','Stock','Price','Vendor'] for name in column_names: file = file.replace(name, '') file = file.replace('|||||||||', '|') ###Here we get all the possible dates### dates = re.findall('\d{4}-\d{2}-\d{2}', file) ###Here we split out string between every possible date### undated_rows = re.split('\d{4}-\d{2}-\d{2}', file)[1::] print('Date|Order|Warehouse|Stock|Price|Vendor', file = open('regular_data.txt', 'w')) ###This is the first line of our csv with the column names### rows = [] for t in zip(dates, undated_rows): ###This zip every line with it's respective date row = list(t[1]) row[0] = t[0] row.insert(1, '|') row = ''.join(row) row = row.replace('||', '\n'+t[0]+'|') if row[-1] == '|': row = row[0:-1] print(row, file = open('regular_data.txt', 'a')) df = pd.read_csv('regular_data.txt', sep = '|') ``` I believe this a very manual solution, but it works.
10,331
We have recently upgraded from 4.4 to 4.7.3 and are now experiencing an issue with one of our profiles. It seems that the civi will no longer use the postURL we are passing to it in an html form. I don't see any release notes saying this was removed and I am kind of at a loss of what could be causing this. Any suggestions? Thanks David
2016/03/10
[ "https://civicrm.stackexchange.com/questions/10331", "https://civicrm.stackexchange.com", "https://civicrm.stackexchange.com/users/2965/" ]
I assume you're talking about a profile where you've copied the HTML Snippet and pasted it onto another site. If so, you should be aware that the necessary code does change periodically between major versions. Thankfully, the answer is pretty straightforward: just generate the HTML Snippet all over again. Go to **Administer > Customize Data and Screens > Profiles** and select **More > HTML Form Snippet** next to your profile. Copy the HTML and paste it into your other page.
I couldn't get the postURL to work on HTML snippets either, but setting a redirect URL in the actual profile settings worked ok.
18,920,687
I have below code to encrypt and decrypt the message in c#. when i am trying to run it is giving an exception ie "The data to be decrypted exceeds the maximum for this modulus of 256 bytes" ``` public static void Main(string[] args) { X509Certificate2 cert = new X509Certificate2(@"C:\Data\ABC-rsa-public-key-certificate.cer"); string encryptedText = EncrypIt("Hello", cert); string decryptedText = DecrptIt(encryptedText, cert); System.Console.WriteLine(decryptedText); } public static string EncrypIt(string inputString, X509Certificate2 cert) { RSACryptoServiceProvider publicKey = (RSACryptoServiceProvider)cert.PublicKey.Key; byte[] plainBytes = Encoding.UTF8.GetBytes(inputString); byte[] encryptedBytes = publicKey.Encrypt(plainBytes, false); string encryptedText = Encoding.UTF8.GetString(encryptedBytes); return encryptedText; } public static string DecrptIt(string encryptedText, X509Certificate2 cert) { RSACryptoServiceProvider privateKey = (RSACryptoServiceProvider)cert.PublicKey.Key; byte[] encryptedBytes = Encoding.UTF8.GetBytes(encryptedText); byte[] decryptedBytes = privateKey.Decrypt(encryptedBytes, false); string decryptedText = Encoding.UTF8.GetString(decryptedBytes); return decryptedText; } ```
2013/09/20
[ "https://Stackoverflow.com/questions/18920687", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2791316/" ]
Several problems: 1. RSA by default only encrypts one block. It's not suitable for long messages. You shouldn't encrypt the message itself with RSA. Generate a random AES key and encrypt the key with RSA and the actual message with AES. 2. You must use a binary safe encoding such as Hex or Base64 for the ciphertext. Using UTF-8 corrupts the data since it doesn't allow arbitrary byte sequences. UTF-8 is designed to encode text, so it's fine for your plaintext. 3. Use OAEP, the old 1.5 padding mode is not secure. i.e. pass `true` as second parameter to `Encrypt`/`Decrypt`. *(Technically it's possible to use it securely, but it's tricky and I wouldn't recommend it)* --- As a further note, once you use AES, there are some more pitfalls: 1) Use a MAC in an encrypt-then-mac scheme, else active attacks including padding-oracles will break your code 2) Use a random IV that's different for each message
RSA should not be used to encrypt this kind of data. You should be encrypting your data with a symmetric key like AES, then encrypting the symmetric key with RSA.
8,364,277
When I press an image on the screen, it calls the powerButton.OnClickListener() like it's supposed to and, after a few seconds of buffering, the stream plays just fine. However, the folks would like a brief toast popup to display to notify the user "Radio Stream Connecting, Please Wait..." This is where the problem is, no matter what I've tried and where I've placed the line to create the toast popup, it simply will not display before it goes into buffering. Any help would be greatly appreciated and I've added most of the code and will provide more if necessary. ``` // run on powerButton click powerButton.setOnClickListener(new OnClickListener() { public void onClick(View view) { // check if the player is started or stopped if (isPlaying) // player is streaming { // stop the stream and set isPlaying to false mediaPlayer.stop(); // release the media player releaseMediaPlayer(); // update notification mNotificationManager.cancel(SIMPLE_NOTFICATION_ID); // set power button to "powered off" image powerButton.setImageResource(R.drawable.power_off); } else // player not streaming { // notify the user that the stream is loading final Toast streamLoading = toast.makeText(getBaseContext(), "Radio Stream Connecting, Please Wait...", Toast.LENGTH_SHORT); streamLoading.show(); // try catch block to attempt connecting to radioUrl try { // create new instance of media player mediaPlayer = new MediaPlayer(); // set media player to handle audio streams mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); // connect to radio stream and fill buffer mediaPlayer.setDataSource(radioUrl); mediaPlayer.prepare(); // might take long depending on buffering speed // start the media player and set isPlaying to true mediaPlayer.start(); isPlaying = true; // update notification, clear stream message createNotification(); // set power button to "powered on" image powerButton.setImageResource(R.drawable.power_on); } catch (IllegalArgumentException e) // cannot connect to stream { // clear streaming text and notify user of failure final Toast streamError1 = Toast.makeText(MainMenu.this, "Failed to load: Unable to connect to stream!", Toast.LENGTH_SHORT); streamError1.show(); // release the media player and display error releaseMediaPlayer(); mNotificationManager.cancel(SIMPLE_NOTFICATION_ID); e.printStackTrace(); } catch (IllegalStateException e) // stream cannot play audio { // clear streaming text and notify user of failure final Toast streamError2 = Toast.makeText(getBaseContext(), "Failed to load: cannot play stream!", Toast.LENGTH_SHORT); streamError2.show(); // release the media player and display error releaseMediaPlayer(); mNotificationManager.cancel(SIMPLE_NOTFICATION_ID); e.printStackTrace(); } catch (IOException e) // general connection issue { // clear streaming text and notify user of failure final Toast streamError3 = Toast.makeText(getBaseContext(), "Failed to Load: Connection issue!", Toast.LENGTH_SHORT); streamError3.show(); // release the media player and display error releaseMediaPlayer(); mNotificationManager.cancel(SIMPLE_NOTFICATION_ID); e.printStackTrace(); } } } }); ```
2011/12/03
[ "https://Stackoverflow.com/questions/8364277", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1020924/" ]
That's because the toast won't show until you return from the onClick because that is the UI thread. I You won't do that until after the buffering is started. I think to get the effect you want, you check the AsynchTask to do the buffering in a background thread and return right away from the onClick. As a matter of fact the way you are doing it, if the buffering takes too long your app will get flagged as non responsive by android.
Try using an [AsyncTask](http://developer.android.com/reference/android/os/AsyncTask.html) where the first thing the AsyncTask does is display the toast before falling into the buffering procedure.
33,211,659
I am wondering how Laravel implement eloquent syntax so that the first where clause can be called statically with `User::where()` ``` User::where('id', 23)->where('email', $email)->first(); ``` Do they have a `public static function where()` and a `public function where()`
2015/10/19
[ "https://Stackoverflow.com/questions/33211659", "https://Stackoverflow.com", "https://Stackoverflow.com/users/45066/" ]
Calling `where` on an Eloquent model does involve a little bit of magic that occurs behind the scenes. Firstly, take the example of: ``` User::where(’name’, ‘Joe’)->first; ``` There’s no static `where` method that exists on the `Model` class that the `User` class extends. What happens, is that the PHP magic method `__callStatic` is called which attempts to then call the `where` method. ``` public static function __callStatic($method, $parameters) { $instance = new static; return call_user_func_array([$instance, $method], $parameters); } ``` As there’s no explicitly defined user function called `where`, the next magic PHP method `__call` which is defined in `Model` is executed. ``` public function __call($method, $parameters) { if (in_array($method, ['increment', 'decrement'])) { return call_user_func_array([$this, $method], $parameters); } $query = $this->newQuery(); return call_user_func_array([$query, $method], $parameters); } ``` The common database related methods become accessible via: ``` $query = $this->newQuery(); ``` This instantiates a new Eloquent query builder object, and it’s on this object that the `where` method runs. So, when you use ```User::where()`` you’re actually using: ``` Illuminate\Database\Eloquent\Builder::where() ``` Take a look at the [Builder class](http://laravel.com/api/5.1/Illuminate/Database/Eloquent/Builder.html) to see all of the common Eloquent methods you’re used to using, like `where()`, `get()`, `first()`, `update()`, etc. [Laracasts](https://laracasts.com/series/advanced-eloquent/episodes/3) has a great in-depth (paid) video on how Eloquent works behind the scenes, which I recommend.
Well let's find out. When we open a model it extends `Model` so let's open that class. In the class `Model` we find 2 "magic" methods called `__call()` and `__callStatic()` *`__call()` is triggered when invoking inaccessible methods in an object context.* *`__callStatic()` is triggered when invoking inaccessible methods in a static context.* We also see in class `Model` it makes use of the class `use Illuminate\Database\Query\Builder as QueryBuilder;` If we open the `Builder` class we find a method called `public function where()` So if you call `User::where` it calls `__callStatic('where', $parameters)` from the `Model` class. I hope this makes sense.
10,537,184
I wrote some service which uses BroadcastReceiver to capture one of media buttons ("play button" from a headset), and it works perfectly on android 2.3.x (HTC Nexus One or HTC Desire) When I tried to run in on Android 4.0.3 (Samsung Nexus S) it doesn't work (my application doesn't receive intent "android.intent.action.MEDIA\_BUTTON" and "play" button behaves as usual: stops/starts music). Content of manifest: > > > ``` > ... > <application > android:icon="@drawable/ic_launcher" > android:label="@string/app_name" > > <receiver android:name=".buttonreceiver.MediaButtonIntentReceiver" > > <intent-filter android:priority="10000" > > <action android:name="android.intent.action.MEDIA_BUTTON" /> > </intent-filter> > </receiver> > ... > > ``` > > Is there way to make it work on android 4.0.3 --- edit: I've try proposed solution, I've added action and run it, but my receiver still doesn't receive intent. What is more strange registering receiver by code also doesn't work: ``` @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.about_and_activation_view); Log.d("MR", "onCreate - " + getIntent().getAction()); mReceiver = new MediaButtonIntentReceiver(); registerReceiver(mReceiver, new IntentFilter(Intent.ACTION_MEDIA_BUTTON)); } ``` Now I'm totally confused.
2012/05/10
[ "https://Stackoverflow.com/questions/10537184", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1387438/" ]
Make sure that you have an activity in your app, and that the user runs this activity before attempting to press that button. Until then, your `<receiver>` [will not receive any broadcasts](http://commonsware.com/blog/2011/07/13/boot-completed-regression-confirmed.html). --- **UPDATE** On Android 4.0 and higher, it appears that you also need to call [`registerMediaButtonEventReceiver()` on `AudioManager`](http://developer.android.com/reference/android/media/AudioManager.html#registerMediaButtonEventReceiver%28android.content.ComponentName%29) in order to receive the events. That state will hold until something else calls `registerMediaButtonEventReceiver()` or until you call `unregisterMediaButtonEventReceiver()`. For example, an activity like this: ``` public class MediaButtonActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); ((AudioManager)getSystemService(AUDIO_SERVICE)).registerMediaButtonEventReceiver(new ComponentName( this, MediaButtonReceiver.class)); } } ``` will enable a manifest-registered `MediaButtonReceiver` to get ACTION\_MEDIA\_BUTTON events.
If you just want your app to be the default but don't need to do anything with the button presses you can use the following method. Add this to the manifest file (in the "Application" node): ``` <receiver android:name="BroadcastReceiver"> <intent-filter> <action android:name="android.intent.action.MEDIA_BUTTON" /> </intent-filter> </receiver> ``` Add this to onCreate() in the main activity or anywhere you want that is called when the app is run. Could be useful in the onResume() event too: ``` mAudioManager = (AudioManager) getActivity().getSystemService(Context.AUDIO_SERVICE); mRemoteControlResponder = new ComponentName(getActivity().getPackageName(), BroadcastReceiver.class.getCanonicalName()); mAudioManager.registerMediaButtonEventReceiver(mRemoteControlResponder); ```
54,936,022
I am not exactly sure how to phrase this question properly. However, it goes something like this. Suppose that we have some macros that work similar to `defun` in Common Lisp and are built on top of that. I made a declaration with one of such macros, and it compiled just fine. However, when I made a call at the REPL, I got `NIL` as the result. That seemed puzzling, so I evaluated the original declaration at the REPL. It evaluated to `NIL`. I need to debug this. My question is whether I should be looking at the reader level or somewhere else. That is, if there is no error thrown, where could I look to begin troubleshooting this?
2019/02/28
[ "https://Stackoverflow.com/questions/54936022", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5969463/" ]
Use the `MACROEXPAND` function to see what your macro call is expanding into. ``` (pprint (macroexpand '(my-defun ...))) ```
You can use something such as the macroexpand-1 function and i'll explain why that's better than a normal macro expansion: ``` CL-USER> (defmacro our-when(test &body body) `(if ,test (progn ,@body))) OUR-WHEN CL-USER> (macroexpand-1 '(our-when(> 2 1)(format t "Hello World"))) (IF (> 2 1) (PROGN ((FORMAT T "Hello World")))) T CL-USER> ``` Here we create a macro and we can actually see how the macro expands the expressions within it. It's preferable at times when debugging to use macroexpand-1 vs. using macroexpand because macroexpand will also breakdown any macro that you have within your macro (like the built-in Common Lisp macros). Macroexpand-1 will limit the breakdown to the macro that you created.
20,961,689
I have the following CustomAdapter: ``` package com.test.testing; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Locale; import android.app.Activity; import android.content.Context; import android.graphics.Color; import android.graphics.Typeface; import android.text.Spannable; import android.text.SpannableString; import android.text.style.ForegroundColorSpan; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.TextView; public class SetRowsCustomAdapter extends ArrayAdapter<SetRows> { Context context; int layoutResourceId; ArrayList<SetRows> data=new ArrayList<SetRows>(); DateFormat df = new SimpleDateFormat("EEEEE, LLLL d", Locale.US); String[] suspendedDates = { "Monday, January 20", "Friday, January 31", }; public SetRowsCustomAdapter(Context context, int layoutResourceId, ArrayList<SetRows> data) { super(context, layoutResourceId, data); this.layoutResourceId = layoutResourceId; this.context = context; this.data = data; } @Override public View getView(int position, View convertView, ViewGroup parent) { View row = convertView; ImageHolder holder = null; if(row == null) { LayoutInflater inflater = ((Activity)context).getLayoutInflater(); row = inflater.inflate(layoutResourceId, parent, false); holder = new ImageHolder(); holder.txtTitle = (TextView)row.findViewById(R.id.tvDateVal); //holder.txtTitle.setTypeface(Typeface.createFromAsset(getContext().getAssets(), "fonts/robm.ttf")); holder.imgIcon = (ImageView)row.findViewById(R.id.ivIcon0); holder.txtDate = (TextView)row.findViewById(R.id.tvDateNum); holder.txtID = (TextView)row.findViewById(R.id.tvReasonVal); //holder.txtID.setTypeface(Typeface.createFromAsset(getContext().getAssets(), "fonts/robm.ttf")); row.setTag(holder); } else { holder = (ImageHolder)row.getTag(); } SetRows myImage = data.get(position); int inReason = myImage.name.indexOf(","); //myImage.name is the same string as suspendedDates[]; String strR = myImage.name.substring(0, inReason); Spannable WordToSpan = new SpannableString(strR); WordToSpan.setSpan(new ForegroundColorSpan(Color.parseColor("#4787ED")), 0, WordToSpan.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); String strRNext = myImage.name.substring(inReason, myImage.name.length()); Spannable WordToSpan1 = new SpannableString(strRNext); WordToSpan1.setSpan(new ForegroundColorSpan(R.color.dateholiday), 0, WordToSpan1.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); String strConcat = WordToSpan.toString() + WordToSpan1.toString(); holder.txtTitle.setText(strConcat);//myImage.name); holder.txtID.setText(myImage.id); holder.txtDate.setText(myImage.date); int outImage=myImage.image; /*if (myImage.name.contains(df.format(Calendar.getInstance(Locale.US).getTime()))) { holder.imgIcon.setImageResource(R.drawable.caliconpressed); } else { holder.imgIcon.setImageResource(R.drawable.calicon); }*/ return row; } static class ImageHolder { ImageView imgIcon; TextView txtTitle; TextView txtID; TextView txtDate; } } ``` I am using `Spannable` to set a separate color of a string. It is supposed to produce something like this: ![enter image description here](https://i.stack.imgur.com/e3BBF.png) But it is still displaying this: ![enter image description here](https://i.stack.imgur.com/LDzwR.png) Anyone know how to edit the Adapter to achieve what I am looking to do?
2014/01/07
[ "https://Stackoverflow.com/questions/20961689", "https://Stackoverflow.com", "https://Stackoverflow.com/users/837722/" ]
No, C++ has no operator similar to `[:]` in Fortran. Depending on whether you are storing things in row major or column major order, this can be done in similar ways however. Firstly, arrays aren't really first class citizens in C++. It's much easier to work with either `std::array` (for small `M, N` as these are stack allocated), or `std::vector`. Let's assume we're using a `std::vector`: ``` template <typename T> using matrix<T> = std::vector<std::vector<T>>; matrix<int> m = {{1,2,3}, {4,5,6}, {7,8,9}}; ``` To get a single row out of this, we can simply use `operator[]`: ``` auto& row = m[0]; // Returns a std::vector<int>& containing {1, 2, 3} ``` Getting columns when it is in row major order is more difficult. If you require more sophisticated sort of operations, using a matrix library (like [Eigen](http://eigen.tuxfamily.org/index.php?title=Main_Page)) might be a better way to go. Edit: If you wanted to fill an entire row with zeros, this can be done easily with `std::fill` on the result: ``` //m defined as before std::fill(std::begin(m[0]), std::end(m[0]), 0); ``` Note that this is still (obviously) linear in the size of the row. This could also easily be wrapped in a function: ``` template <typename T> void clear_row(matrix<T>& m, std::size_t row, const T& new_value) { std::fill(std::begin(m[row]), std::end(m[row]), new_value); } ``` If you wanted to replace all the values in a row with a set of different values, you'd use iterators: ``` template <typename T, typename Iterator> void modify_row(matrix<T>& m, std::size_t row, Iterator new_start) { std::copy(std::begin(m[row]), std::end(m[row]), new_start); } ```
You can only take the last dimension ``` int A[3][5]; int * x = A[2]; int y = x[3]; ``` To get `A[?][3]` - you would need a loop
20,961,689
I have the following CustomAdapter: ``` package com.test.testing; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Locale; import android.app.Activity; import android.content.Context; import android.graphics.Color; import android.graphics.Typeface; import android.text.Spannable; import android.text.SpannableString; import android.text.style.ForegroundColorSpan; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.TextView; public class SetRowsCustomAdapter extends ArrayAdapter<SetRows> { Context context; int layoutResourceId; ArrayList<SetRows> data=new ArrayList<SetRows>(); DateFormat df = new SimpleDateFormat("EEEEE, LLLL d", Locale.US); String[] suspendedDates = { "Monday, January 20", "Friday, January 31", }; public SetRowsCustomAdapter(Context context, int layoutResourceId, ArrayList<SetRows> data) { super(context, layoutResourceId, data); this.layoutResourceId = layoutResourceId; this.context = context; this.data = data; } @Override public View getView(int position, View convertView, ViewGroup parent) { View row = convertView; ImageHolder holder = null; if(row == null) { LayoutInflater inflater = ((Activity)context).getLayoutInflater(); row = inflater.inflate(layoutResourceId, parent, false); holder = new ImageHolder(); holder.txtTitle = (TextView)row.findViewById(R.id.tvDateVal); //holder.txtTitle.setTypeface(Typeface.createFromAsset(getContext().getAssets(), "fonts/robm.ttf")); holder.imgIcon = (ImageView)row.findViewById(R.id.ivIcon0); holder.txtDate = (TextView)row.findViewById(R.id.tvDateNum); holder.txtID = (TextView)row.findViewById(R.id.tvReasonVal); //holder.txtID.setTypeface(Typeface.createFromAsset(getContext().getAssets(), "fonts/robm.ttf")); row.setTag(holder); } else { holder = (ImageHolder)row.getTag(); } SetRows myImage = data.get(position); int inReason = myImage.name.indexOf(","); //myImage.name is the same string as suspendedDates[]; String strR = myImage.name.substring(0, inReason); Spannable WordToSpan = new SpannableString(strR); WordToSpan.setSpan(new ForegroundColorSpan(Color.parseColor("#4787ED")), 0, WordToSpan.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); String strRNext = myImage.name.substring(inReason, myImage.name.length()); Spannable WordToSpan1 = new SpannableString(strRNext); WordToSpan1.setSpan(new ForegroundColorSpan(R.color.dateholiday), 0, WordToSpan1.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); String strConcat = WordToSpan.toString() + WordToSpan1.toString(); holder.txtTitle.setText(strConcat);//myImage.name); holder.txtID.setText(myImage.id); holder.txtDate.setText(myImage.date); int outImage=myImage.image; /*if (myImage.name.contains(df.format(Calendar.getInstance(Locale.US).getTime()))) { holder.imgIcon.setImageResource(R.drawable.caliconpressed); } else { holder.imgIcon.setImageResource(R.drawable.calicon); }*/ return row; } static class ImageHolder { ImageView imgIcon; TextView txtTitle; TextView txtID; TextView txtDate; } } ``` I am using `Spannable` to set a separate color of a string. It is supposed to produce something like this: ![enter image description here](https://i.stack.imgur.com/e3BBF.png) But it is still displaying this: ![enter image description here](https://i.stack.imgur.com/LDzwR.png) Anyone know how to edit the Adapter to achieve what I am looking to do?
2014/01/07
[ "https://Stackoverflow.com/questions/20961689", "https://Stackoverflow.com", "https://Stackoverflow.com/users/837722/" ]
No, C++ has no operator similar to `[:]` in Fortran. Depending on whether you are storing things in row major or column major order, this can be done in similar ways however. Firstly, arrays aren't really first class citizens in C++. It's much easier to work with either `std::array` (for small `M, N` as these are stack allocated), or `std::vector`. Let's assume we're using a `std::vector`: ``` template <typename T> using matrix<T> = std::vector<std::vector<T>>; matrix<int> m = {{1,2,3}, {4,5,6}, {7,8,9}}; ``` To get a single row out of this, we can simply use `operator[]`: ``` auto& row = m[0]; // Returns a std::vector<int>& containing {1, 2, 3} ``` Getting columns when it is in row major order is more difficult. If you require more sophisticated sort of operations, using a matrix library (like [Eigen](http://eigen.tuxfamily.org/index.php?title=Main_Page)) might be a better way to go. Edit: If you wanted to fill an entire row with zeros, this can be done easily with `std::fill` on the result: ``` //m defined as before std::fill(std::begin(m[0]), std::end(m[0]), 0); ``` Note that this is still (obviously) linear in the size of the row. This could also easily be wrapped in a function: ``` template <typename T> void clear_row(matrix<T>& m, std::size_t row, const T& new_value) { std::fill(std::begin(m[row]), std::end(m[row]), new_value); } ``` If you wanted to replace all the values in a row with a set of different values, you'd use iterators: ``` template <typename T, typename Iterator> void modify_row(matrix<T>& m, std::size_t row, Iterator new_start) { std::copy(std::begin(m[row]), std::end(m[row]), new_start); } ```
A 2D array is just an array of arrays. So `int A[10][20]` declares an array of size 10, each of whose elements is an array of size 20, each of whose elements is an `int`. The expression `A[3]` has type "array of 20 ints", and you can use it as such. It will decay into an `int *` pointing to the first element of the row (assuming you are thinking of them as rows). There is no equivalent expression for the columns; you will need a loop for that.
20,961,689
I have the following CustomAdapter: ``` package com.test.testing; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Locale; import android.app.Activity; import android.content.Context; import android.graphics.Color; import android.graphics.Typeface; import android.text.Spannable; import android.text.SpannableString; import android.text.style.ForegroundColorSpan; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.TextView; public class SetRowsCustomAdapter extends ArrayAdapter<SetRows> { Context context; int layoutResourceId; ArrayList<SetRows> data=new ArrayList<SetRows>(); DateFormat df = new SimpleDateFormat("EEEEE, LLLL d", Locale.US); String[] suspendedDates = { "Monday, January 20", "Friday, January 31", }; public SetRowsCustomAdapter(Context context, int layoutResourceId, ArrayList<SetRows> data) { super(context, layoutResourceId, data); this.layoutResourceId = layoutResourceId; this.context = context; this.data = data; } @Override public View getView(int position, View convertView, ViewGroup parent) { View row = convertView; ImageHolder holder = null; if(row == null) { LayoutInflater inflater = ((Activity)context).getLayoutInflater(); row = inflater.inflate(layoutResourceId, parent, false); holder = new ImageHolder(); holder.txtTitle = (TextView)row.findViewById(R.id.tvDateVal); //holder.txtTitle.setTypeface(Typeface.createFromAsset(getContext().getAssets(), "fonts/robm.ttf")); holder.imgIcon = (ImageView)row.findViewById(R.id.ivIcon0); holder.txtDate = (TextView)row.findViewById(R.id.tvDateNum); holder.txtID = (TextView)row.findViewById(R.id.tvReasonVal); //holder.txtID.setTypeface(Typeface.createFromAsset(getContext().getAssets(), "fonts/robm.ttf")); row.setTag(holder); } else { holder = (ImageHolder)row.getTag(); } SetRows myImage = data.get(position); int inReason = myImage.name.indexOf(","); //myImage.name is the same string as suspendedDates[]; String strR = myImage.name.substring(0, inReason); Spannable WordToSpan = new SpannableString(strR); WordToSpan.setSpan(new ForegroundColorSpan(Color.parseColor("#4787ED")), 0, WordToSpan.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); String strRNext = myImage.name.substring(inReason, myImage.name.length()); Spannable WordToSpan1 = new SpannableString(strRNext); WordToSpan1.setSpan(new ForegroundColorSpan(R.color.dateholiday), 0, WordToSpan1.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); String strConcat = WordToSpan.toString() + WordToSpan1.toString(); holder.txtTitle.setText(strConcat);//myImage.name); holder.txtID.setText(myImage.id); holder.txtDate.setText(myImage.date); int outImage=myImage.image; /*if (myImage.name.contains(df.format(Calendar.getInstance(Locale.US).getTime()))) { holder.imgIcon.setImageResource(R.drawable.caliconpressed); } else { holder.imgIcon.setImageResource(R.drawable.calicon); }*/ return row; } static class ImageHolder { ImageView imgIcon; TextView txtTitle; TextView txtID; TextView txtDate; } } ``` I am using `Spannable` to set a separate color of a string. It is supposed to produce something like this: ![enter image description here](https://i.stack.imgur.com/e3BBF.png) But it is still displaying this: ![enter image description here](https://i.stack.imgur.com/LDzwR.png) Anyone know how to edit the Adapter to achieve what I am looking to do?
2014/01/07
[ "https://Stackoverflow.com/questions/20961689", "https://Stackoverflow.com", "https://Stackoverflow.com/users/837722/" ]
No, C++ has no operator similar to `[:]` in Fortran. Depending on whether you are storing things in row major or column major order, this can be done in similar ways however. Firstly, arrays aren't really first class citizens in C++. It's much easier to work with either `std::array` (for small `M, N` as these are stack allocated), or `std::vector`. Let's assume we're using a `std::vector`: ``` template <typename T> using matrix<T> = std::vector<std::vector<T>>; matrix<int> m = {{1,2,3}, {4,5,6}, {7,8,9}}; ``` To get a single row out of this, we can simply use `operator[]`: ``` auto& row = m[0]; // Returns a std::vector<int>& containing {1, 2, 3} ``` Getting columns when it is in row major order is more difficult. If you require more sophisticated sort of operations, using a matrix library (like [Eigen](http://eigen.tuxfamily.org/index.php?title=Main_Page)) might be a better way to go. Edit: If you wanted to fill an entire row with zeros, this can be done easily with `std::fill` on the result: ``` //m defined as before std::fill(std::begin(m[0]), std::end(m[0]), 0); ``` Note that this is still (obviously) linear in the size of the row. This could also easily be wrapped in a function: ``` template <typename T> void clear_row(matrix<T>& m, std::size_t row, const T& new_value) { std::fill(std::begin(m[row]), std::end(m[row]), new_value); } ``` If you wanted to replace all the values in a row with a set of different values, you'd use iterators: ``` template <typename T, typename Iterator> void modify_row(matrix<T>& m, std::size_t row, Iterator new_start) { std::copy(std::begin(m[row]), std::end(m[row]), new_start); } ```
if you define int A[5][10] , then A will have 5 \* 10 \* sizeof(int) continue space, , in this case , A[3][:] would be in 31'th location to 40'th location in this array !! ``` int* p = &(A[30]) ; ``` \*(p+0) to \*(p+9) will be A[3][0] to A[3][9] , you can directly access each element of A by the pointer p . Edit : typo , it should be : ``` int* p = &(A[3][0]) ; ```
20,961,689
I have the following CustomAdapter: ``` package com.test.testing; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Locale; import android.app.Activity; import android.content.Context; import android.graphics.Color; import android.graphics.Typeface; import android.text.Spannable; import android.text.SpannableString; import android.text.style.ForegroundColorSpan; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.TextView; public class SetRowsCustomAdapter extends ArrayAdapter<SetRows> { Context context; int layoutResourceId; ArrayList<SetRows> data=new ArrayList<SetRows>(); DateFormat df = new SimpleDateFormat("EEEEE, LLLL d", Locale.US); String[] suspendedDates = { "Monday, January 20", "Friday, January 31", }; public SetRowsCustomAdapter(Context context, int layoutResourceId, ArrayList<SetRows> data) { super(context, layoutResourceId, data); this.layoutResourceId = layoutResourceId; this.context = context; this.data = data; } @Override public View getView(int position, View convertView, ViewGroup parent) { View row = convertView; ImageHolder holder = null; if(row == null) { LayoutInflater inflater = ((Activity)context).getLayoutInflater(); row = inflater.inflate(layoutResourceId, parent, false); holder = new ImageHolder(); holder.txtTitle = (TextView)row.findViewById(R.id.tvDateVal); //holder.txtTitle.setTypeface(Typeface.createFromAsset(getContext().getAssets(), "fonts/robm.ttf")); holder.imgIcon = (ImageView)row.findViewById(R.id.ivIcon0); holder.txtDate = (TextView)row.findViewById(R.id.tvDateNum); holder.txtID = (TextView)row.findViewById(R.id.tvReasonVal); //holder.txtID.setTypeface(Typeface.createFromAsset(getContext().getAssets(), "fonts/robm.ttf")); row.setTag(holder); } else { holder = (ImageHolder)row.getTag(); } SetRows myImage = data.get(position); int inReason = myImage.name.indexOf(","); //myImage.name is the same string as suspendedDates[]; String strR = myImage.name.substring(0, inReason); Spannable WordToSpan = new SpannableString(strR); WordToSpan.setSpan(new ForegroundColorSpan(Color.parseColor("#4787ED")), 0, WordToSpan.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); String strRNext = myImage.name.substring(inReason, myImage.name.length()); Spannable WordToSpan1 = new SpannableString(strRNext); WordToSpan1.setSpan(new ForegroundColorSpan(R.color.dateholiday), 0, WordToSpan1.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); String strConcat = WordToSpan.toString() + WordToSpan1.toString(); holder.txtTitle.setText(strConcat);//myImage.name); holder.txtID.setText(myImage.id); holder.txtDate.setText(myImage.date); int outImage=myImage.image; /*if (myImage.name.contains(df.format(Calendar.getInstance(Locale.US).getTime()))) { holder.imgIcon.setImageResource(R.drawable.caliconpressed); } else { holder.imgIcon.setImageResource(R.drawable.calicon); }*/ return row; } static class ImageHolder { ImageView imgIcon; TextView txtTitle; TextView txtID; TextView txtDate; } } ``` I am using `Spannable` to set a separate color of a string. It is supposed to produce something like this: ![enter image description here](https://i.stack.imgur.com/e3BBF.png) But it is still displaying this: ![enter image description here](https://i.stack.imgur.com/LDzwR.png) Anyone know how to edit the Adapter to achieve what I am looking to do?
2014/01/07
[ "https://Stackoverflow.com/questions/20961689", "https://Stackoverflow.com", "https://Stackoverflow.com/users/837722/" ]
No, C++ has no operator similar to `[:]` in Fortran. Depending on whether you are storing things in row major or column major order, this can be done in similar ways however. Firstly, arrays aren't really first class citizens in C++. It's much easier to work with either `std::array` (for small `M, N` as these are stack allocated), or `std::vector`. Let's assume we're using a `std::vector`: ``` template <typename T> using matrix<T> = std::vector<std::vector<T>>; matrix<int> m = {{1,2,3}, {4,5,6}, {7,8,9}}; ``` To get a single row out of this, we can simply use `operator[]`: ``` auto& row = m[0]; // Returns a std::vector<int>& containing {1, 2, 3} ``` Getting columns when it is in row major order is more difficult. If you require more sophisticated sort of operations, using a matrix library (like [Eigen](http://eigen.tuxfamily.org/index.php?title=Main_Page)) might be a better way to go. Edit: If you wanted to fill an entire row with zeros, this can be done easily with `std::fill` on the result: ``` //m defined as before std::fill(std::begin(m[0]), std::end(m[0]), 0); ``` Note that this is still (obviously) linear in the size of the row. This could also easily be wrapped in a function: ``` template <typename T> void clear_row(matrix<T>& m, std::size_t row, const T& new_value) { std::fill(std::begin(m[row]), std::end(m[row]), new_value); } ``` If you wanted to replace all the values in a row with a set of different values, you'd use iterators: ``` template <typename T, typename Iterator> void modify_row(matrix<T>& m, std::size_t row, Iterator new_start) { std::copy(std::begin(m[row]), std::end(m[row]), new_start); } ```
Not with regular arrays. `std::valarray` supports `std::slice`, which does allow for row access (stride = 1) and column access (stride=row width)
54,375,227
I have a JSON file that I'd like to get values from and display. I tried to use a ternary operator but I couldn't seem to get the output I wanted since I have multiple variables. Here's what I tried: ``` //If there's a word, display its character / reading. Otherwise, just display the reading return `${json.data[0].word} ? ${json.data[0].word (${json.data[0].reading}) : ${json.data[0].reading}` ``` This just outputs the actual string but with undefined if json.data[0].word is undefined. I'd like to only display the reading in this case.
2019/01/26
[ "https://Stackoverflow.com/questions/54375227", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4838705/" ]
Placeholders don't work recursively in String templates. Write a clearer code. If you insist in using a compact ternary code: ``` json.data[0].word ? `${json.data[0].word} (${json.data[0].reading})` : `${json.data[0].reading}` ``` Your external placeholder is unnecessary.
There is a much easier way to go about this. First I would create a variable that contained the resulting evaluation, and simply returned a literal of that result. Then I would split up the nested ternaries into a set of nested if statements that are much easier to understand and modify in the future. Take a look at the code block below, you should be able to structure your code very easily and cleanly. Nested ternaries I believe to be very bad practice, and should be avoided at all times. ``` let $result; if (true) { if (true) { $result = 'output 2'; } else { $result = 'output 3'; } $result = 'output 1'; } return `${result}`; ```
121,292
In *Star Trek III: The Search for Spock*, Spock's father (Sarek) told Kirk to bring Dr. McCoy to Vulcan. At the time Enterprise was all busted up and being decommissioned. Kirk told Sarek that it would be difficult and Sarek basically just told Kirk to figure it out. Why didn't Spock's father help? He was an Ambassador with a fancy Vulcan ship and he was going to meet them at Vulcan anyway. Instead of driving Kirk and his entire senior staff to turn to crime by seeking illegal commercial passage and ultimately stealing the damaged Enterprise ship, why didn't Sarek just give them a ride?
2016/03/06
[ "https://scifi.stackexchange.com/questions/121292", "https://scifi.stackexchange.com", "https://scifi.stackexchange.com/users/-1/" ]
The issue is not about bringing McCoy to Vulcan. The real issue is about bringing Spock from Genesis to Vulcan. =============================================================================================================== It's certainly a minor issue to bring McCoy to Vulcan. Rather, the point of much of the film is to bring *Spock* to Vulcan. > > **SAREK:** Why did you leave him on Genesis! Spock trusted you. You denied him his future!... > > > **KIRK:** What must I do? > > > **SAREK:** You must bring them to Mount Selaya — on Vulcan. Only there is the passage possible. Only there can both find peace. > > > Retrieving Spock would be an extremely difficult feat, considering that Spock's body was laid to rest on Genesis and Genesis was now off-limits to all but a handful of Federation scientists. Now, regarding Sarek's level of involvement, remember that Sarek was the Vulcan Ambassador to Earth and the Genesis planet had become a serious political issue. It is made clear in both *The Search for Spock* and *The Voyage Home* that the Genesis project was viewed as a weapon of mass destruction by the Klingon Empire, and the existence of the Genesis planet had become politically toxic, risking a flare-up of hostilities between the Federation and the Empire. Sarek, as one of the principal negotiators between the Federation and the Empire (as depicted in *The Voyage Home*), would have to stay clear of this. To summarize: * The issue is not about bringing McCoy to Vulcan (although that is part of the end goal). The main issue is about finding Spock, or Spock's body, and bringing *both* Spock and McCoy to Vulcan. * Bringing Spock to Vulcan involves visiting the restricted Genesis planet, something that the principal Federation negotiator, Sarek, could not be involved with, even tangentially. Better leave it all to Kirk!
What Sarek actually said was that Kirk had to bring both McCoy *and* Spock to Vulcan: > > [The two see footage of Spock mind-melding with McCoy] > > > Kirk: Bones!... > > > Sarek: One alive, one not. Yet both in pain. > > > Kirk: What must I do? > > > Sarek: You must bring them to Mount Selaya -- on Vulcan. Only there is the passage possible. Only there can both find peace. > > > As we find out later when McCoy tries to hire an alien to take him to Genesis, it is off limits: > > Genesis allowed is not... Is planet forbidden. > > > Sarek couldn't have helped take them to Genesis without causing a diplomatic incident. It's unlikely that Sarek could have used his weight as ambassador to convince Starfleet to bring Spock back from Genesis, given that he has a conflict of interest.
121,292
In *Star Trek III: The Search for Spock*, Spock's father (Sarek) told Kirk to bring Dr. McCoy to Vulcan. At the time Enterprise was all busted up and being decommissioned. Kirk told Sarek that it would be difficult and Sarek basically just told Kirk to figure it out. Why didn't Spock's father help? He was an Ambassador with a fancy Vulcan ship and he was going to meet them at Vulcan anyway. Instead of driving Kirk and his entire senior staff to turn to crime by seeking illegal commercial passage and ultimately stealing the damaged Enterprise ship, why didn't Sarek just give them a ride?
2016/03/06
[ "https://scifi.stackexchange.com/questions/121292", "https://scifi.stackexchange.com", "https://scifi.stackexchange.com/users/-1/" ]
The issue is not about bringing McCoy to Vulcan. The real issue is about bringing Spock from Genesis to Vulcan. =============================================================================================================== It's certainly a minor issue to bring McCoy to Vulcan. Rather, the point of much of the film is to bring *Spock* to Vulcan. > > **SAREK:** Why did you leave him on Genesis! Spock trusted you. You denied him his future!... > > > **KIRK:** What must I do? > > > **SAREK:** You must bring them to Mount Selaya — on Vulcan. Only there is the passage possible. Only there can both find peace. > > > Retrieving Spock would be an extremely difficult feat, considering that Spock's body was laid to rest on Genesis and Genesis was now off-limits to all but a handful of Federation scientists. Now, regarding Sarek's level of involvement, remember that Sarek was the Vulcan Ambassador to Earth and the Genesis planet had become a serious political issue. It is made clear in both *The Search for Spock* and *The Voyage Home* that the Genesis project was viewed as a weapon of mass destruction by the Klingon Empire, and the existence of the Genesis planet had become politically toxic, risking a flare-up of hostilities between the Federation and the Empire. Sarek, as one of the principal negotiators between the Federation and the Empire (as depicted in *The Voyage Home*), would have to stay clear of this. To summarize: * The issue is not about bringing McCoy to Vulcan (although that is part of the end goal). The main issue is about finding Spock, or Spock's body, and bringing *both* Spock and McCoy to Vulcan. * Bringing Spock to Vulcan involves visiting the restricted Genesis planet, something that the principal Federation negotiator, Sarek, could not be involved with, even tangentially. Better leave it all to Kirk!
Kirk, et. al. still had to go to the Genesis planet to retrieve Spock's body so it could be brought to Vulcan. Sarek was not going to Genesis.
2,370,177
Developers are sometimes scathing of mult-tier Enterprise web applications... 'Enterprise' is viewed by some as synonymous with slow, bloated and resource-hungry. Do frameworks such as Hibernate actually bring in a non-trivial impact on performance compared to writing your own DAOs or other less abstracted approaches? By non-trivial I suppose the question is "does the user notice pages load slower as a result".
2010/03/03
[ "https://Stackoverflow.com/questions/2370177", "https://Stackoverflow.com", "https://Stackoverflow.com/users/197229/" ]
With proper usage you are likely to improve performance rather than decrease it. In most cases you'll get comparable performance and when there're problems you'll have much more time to troubleshoot them. PS Remember to use proper tools with Hibernate like [Hibernate profiler](http://hibernateprofiler.com/). They can make wonders! PPS Using Hibernate is not a replacement for knowing your SQL!
It depends a lot on what you're doing. Generally your users won't notice a difference on the front-end but there are a few things to watch out for: * ORM mappers aren't great at doing batch updates or handling large results sets. * If you have a complex set of relationships your ORM mapper might slow things down because it does joins in the "wrong" way. Or fetches too much data. * If your site has really heavy load the extra CPU cycles might get in the way but it is unlikely. An ORM mapper can make your software much easier to develop. Keep an eye on performance and do the 1% of things in straight SQL but keep Hibernate in the other 99% of things.
2,370,177
Developers are sometimes scathing of mult-tier Enterprise web applications... 'Enterprise' is viewed by some as synonymous with slow, bloated and resource-hungry. Do frameworks such as Hibernate actually bring in a non-trivial impact on performance compared to writing your own DAOs or other less abstracted approaches? By non-trivial I suppose the question is "does the user notice pages load slower as a result".
2010/03/03
[ "https://Stackoverflow.com/questions/2370177", "https://Stackoverflow.com", "https://Stackoverflow.com/users/197229/" ]
With proper usage you are likely to improve performance rather than decrease it. In most cases you'll get comparable performance and when there're problems you'll have much more time to troubleshoot them. PS Remember to use proper tools with Hibernate like [Hibernate profiler](http://hibernateprofiler.com/). They can make wonders! PPS Using Hibernate is not a replacement for knowing your SQL!
That really depends on what you are doing or more exactly how you use the framework. Also, with today's hardware capabilities what is an issue today might not count in a few months. Not sure if you ask this because there is an application requirement which says that performance is important or you are just wondering, but consider this: there were some people that used Hibernate in an application and noticed it was sloooow. Then some guys refactored it, optimized it, with plain JDBC, iBatis or whatever and it ran faaaaast. So, the conclusion was: Hibernate is slow. But they did not consider that the technology was misused. Yeah... it's cool that you can write `object.getX().getZ().getW().getSomeOtherThing().getEtc()` and it just works, but Hibernate will generate the SQL and Heaven help you there. Before doing anything, consider the rules of optimisation: * First rule of optimization - Don't do it. * Second rule of optimization (for experts) - Don't do it... yet. Adding a framework is usually a good thing because it eases development. If it adds overhead? Well... you can't tell just by looking at it. You have to profile it and test it.
2,370,177
Developers are sometimes scathing of mult-tier Enterprise web applications... 'Enterprise' is viewed by some as synonymous with slow, bloated and resource-hungry. Do frameworks such as Hibernate actually bring in a non-trivial impact on performance compared to writing your own DAOs or other less abstracted approaches? By non-trivial I suppose the question is "does the user notice pages load slower as a result".
2010/03/03
[ "https://Stackoverflow.com/questions/2370177", "https://Stackoverflow.com", "https://Stackoverflow.com/users/197229/" ]
With proper usage you are likely to improve performance rather than decrease it. In most cases you'll get comparable performance and when there're problems you'll have much more time to troubleshoot them. PS Remember to use proper tools with Hibernate like [Hibernate profiler](http://hibernateprofiler.com/). They can make wonders! PPS Using Hibernate is not a replacement for knowing your SQL!
> > By non-trivial I suppose the question is "does the user notice pages load slower as a result". > > > For most CRUD applications, it's the contrary actually. Properly used and tuned, Hibernate will generate better SQL than most developers (sorry to say that but it's true) and features like lazy-loading, first level caching (transaction-level cache), second level caching (global-level cache), query caching will make it perform better than lower level approaches (custom SQL and DAOs). And because someone mentioned batch updates and large result sets, I'd underline that Hibernate has a [`StatelessSession`](http://docs.jboss.org/hibernate/core/3.3/reference/en/html/batch.html) for these use cases. But I don't think that they're in the scope of the interactive part of a webapp (if your search retrieves 10⁶ records in a webapp, you are doing it wrong).
2,370,177
Developers are sometimes scathing of mult-tier Enterprise web applications... 'Enterprise' is viewed by some as synonymous with slow, bloated and resource-hungry. Do frameworks such as Hibernate actually bring in a non-trivial impact on performance compared to writing your own DAOs or other less abstracted approaches? By non-trivial I suppose the question is "does the user notice pages load slower as a result".
2010/03/03
[ "https://Stackoverflow.com/questions/2370177", "https://Stackoverflow.com", "https://Stackoverflow.com/users/197229/" ]
That really depends on what you are doing or more exactly how you use the framework. Also, with today's hardware capabilities what is an issue today might not count in a few months. Not sure if you ask this because there is an application requirement which says that performance is important or you are just wondering, but consider this: there were some people that used Hibernate in an application and noticed it was sloooow. Then some guys refactored it, optimized it, with plain JDBC, iBatis or whatever and it ran faaaaast. So, the conclusion was: Hibernate is slow. But they did not consider that the technology was misused. Yeah... it's cool that you can write `object.getX().getZ().getW().getSomeOtherThing().getEtc()` and it just works, but Hibernate will generate the SQL and Heaven help you there. Before doing anything, consider the rules of optimisation: * First rule of optimization - Don't do it. * Second rule of optimization (for experts) - Don't do it... yet. Adding a framework is usually a good thing because it eases development. If it adds overhead? Well... you can't tell just by looking at it. You have to profile it and test it.
It depends a lot on what you're doing. Generally your users won't notice a difference on the front-end but there are a few things to watch out for: * ORM mappers aren't great at doing batch updates or handling large results sets. * If you have a complex set of relationships your ORM mapper might slow things down because it does joins in the "wrong" way. Or fetches too much data. * If your site has really heavy load the extra CPU cycles might get in the way but it is unlikely. An ORM mapper can make your software much easier to develop. Keep an eye on performance and do the 1% of things in straight SQL but keep Hibernate in the other 99% of things.
2,370,177
Developers are sometimes scathing of mult-tier Enterprise web applications... 'Enterprise' is viewed by some as synonymous with slow, bloated and resource-hungry. Do frameworks such as Hibernate actually bring in a non-trivial impact on performance compared to writing your own DAOs or other less abstracted approaches? By non-trivial I suppose the question is "does the user notice pages load slower as a result".
2010/03/03
[ "https://Stackoverflow.com/questions/2370177", "https://Stackoverflow.com", "https://Stackoverflow.com/users/197229/" ]
> > By non-trivial I suppose the question is "does the user notice pages load slower as a result". > > > For most CRUD applications, it's the contrary actually. Properly used and tuned, Hibernate will generate better SQL than most developers (sorry to say that but it's true) and features like lazy-loading, first level caching (transaction-level cache), second level caching (global-level cache), query caching will make it perform better than lower level approaches (custom SQL and DAOs). And because someone mentioned batch updates and large result sets, I'd underline that Hibernate has a [`StatelessSession`](http://docs.jboss.org/hibernate/core/3.3/reference/en/html/batch.html) for these use cases. But I don't think that they're in the scope of the interactive part of a webapp (if your search retrieves 10⁶ records in a webapp, you are doing it wrong).
It depends a lot on what you're doing. Generally your users won't notice a difference on the front-end but there are a few things to watch out for: * ORM mappers aren't great at doing batch updates or handling large results sets. * If you have a complex set of relationships your ORM mapper might slow things down because it does joins in the "wrong" way. Or fetches too much data. * If your site has really heavy load the extra CPU cycles might get in the way but it is unlikely. An ORM mapper can make your software much easier to develop. Keep an eye on performance and do the 1% of things in straight SQL but keep Hibernate in the other 99% of things.
11,228,711
I have a table with a form below it. You can fill out the form, but hitting the 'Undo' button will revert any entered information to what it was before edits were made. I would like to assert the text that is manually entered so I can confirm the 'Undo' button is reverting the fields. The 'value' attribute does not change unless the item is saved, so I cannot use that for attribute for assertion. The XPath for a field is below if that will help. ``` <table id="userAdminForm" class="c4i-ui-fieldGrid"> <tbody> <tr> <td class="c4i-labelCell"> <td class="c4i-fieldCell" rowspan="1" colspan="1"> <div class="c4i-fieldDiv rel" style="min-height: 36px"> <input id="userName" class="ui-inputfield ui-inputtext ui-widget ui-state-default ui-corner-all" type="text" value="Super User" name="userName" role="textbox" aria-disabled="false" aria-readonly="false" aria-multiline="false"> ```
2012/06/27
[ "https://Stackoverflow.com/questions/11228711", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1467348/" ]
Use the `apply` method: ``` app[fn_name].apply(app, fn_args); ``` <https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/apply>
Use `function.apply()`. ``` app[fn_name].apply(app, fn_args); ``` The first arguument is the context (`this`) inside the function, and the second is the array whose items should be passed as arguments.
50,729,551
I am generating multi Data entry Line using ASP MVC , however looking at the HTML source after generating by MVC, I've just noticed those HTML elements has a duplicated ID , even with the same html type it is look something wrong ? is that normal behavior in MVC and how to avoid it ? , I need really to have it unique, assuming MVC should handle the ID generation for multi line, which is additional concern to me . My code : ``` @foreach (var item in Model.lstMeals) { <tr> <td> <input asp-for="@item.cuisine.CuisineName" /> @Html.DisplayFor(modelItem => item.cuisine.CuisineName) </td> </tr> } ``` then looking in HTML Source : ```html <tr> <td> <input type="text" id="item_cuisine_CuisineName" name="item.cuisine.CuisineName" value="Italian" /> Italian </td> </tr> <tr> <td> <input type="text" id="item_cuisine_CuisineName" name="item.cuisine.CuisineName" value="French" /> French </td> </tr> <tr> <td> <input type="text" id="item_cuisine_CuisineName" name="item.cuisine.CuisineName" value="Greek" /> Greek </td> </tr> ```
2018/06/06
[ "https://Stackoverflow.com/questions/50729551", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3767719/" ]
Why compiling? You should be able to install the package: ``` sudo add-apt-repository ppa:ubuntu-toolchain-r/test sudo apt update sudo apt install g++-7 -y ``` Verify using: ``` gcc-7 --version ``` See [How to install gcc-7 or clang 4.0?](https://askubuntu.com/questions/859256/how-to-install-gcc-7-or-clang-4-0)
`crt1.o` is generally provided as part of the `libdevc` dependency (or something similar). I would suggest running `sudo apt search libc` or some similar variant with `lib6c`, `libdev`, `libc-dev` etc. Installing those fixed a similar issue I had recently. Failing that, run `find / -iname ctri.o` and add the folder it appears in to your PATH with `export PATH="[folder]:$PATH"`, and see if that helps.
50,729,551
I am generating multi Data entry Line using ASP MVC , however looking at the HTML source after generating by MVC, I've just noticed those HTML elements has a duplicated ID , even with the same html type it is look something wrong ? is that normal behavior in MVC and how to avoid it ? , I need really to have it unique, assuming MVC should handle the ID generation for multi line, which is additional concern to me . My code : ``` @foreach (var item in Model.lstMeals) { <tr> <td> <input asp-for="@item.cuisine.CuisineName" /> @Html.DisplayFor(modelItem => item.cuisine.CuisineName) </td> </tr> } ``` then looking in HTML Source : ```html <tr> <td> <input type="text" id="item_cuisine_CuisineName" name="item.cuisine.CuisineName" value="Italian" /> Italian </td> </tr> <tr> <td> <input type="text" id="item_cuisine_CuisineName" name="item.cuisine.CuisineName" value="French" /> French </td> </tr> <tr> <td> <input type="text" id="item_cuisine_CuisineName" name="item.cuisine.CuisineName" value="Greek" /> Greek </td> </tr> ```
2018/06/06
[ "https://Stackoverflow.com/questions/50729551", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3767719/" ]
Why compiling? You should be able to install the package: ``` sudo add-apt-repository ppa:ubuntu-toolchain-r/test sudo apt update sudo apt install g++-7 -y ``` Verify using: ``` gcc-7 --version ``` See [How to install gcc-7 or clang 4.0?](https://askubuntu.com/questions/859256/how-to-install-gcc-7-or-clang-4-0)
run the following ``` sudo apt install aptitude sudo aptitude install gcc-7 g++-7 ``` or ``` sudo apt install aptitude && sudo aptitude install golang gcc-7 g++-7 ```
50,729,551
I am generating multi Data entry Line using ASP MVC , however looking at the HTML source after generating by MVC, I've just noticed those HTML elements has a duplicated ID , even with the same html type it is look something wrong ? is that normal behavior in MVC and how to avoid it ? , I need really to have it unique, assuming MVC should handle the ID generation for multi line, which is additional concern to me . My code : ``` @foreach (var item in Model.lstMeals) { <tr> <td> <input asp-for="@item.cuisine.CuisineName" /> @Html.DisplayFor(modelItem => item.cuisine.CuisineName) </td> </tr> } ``` then looking in HTML Source : ```html <tr> <td> <input type="text" id="item_cuisine_CuisineName" name="item.cuisine.CuisineName" value="Italian" /> Italian </td> </tr> <tr> <td> <input type="text" id="item_cuisine_CuisineName" name="item.cuisine.CuisineName" value="French" /> French </td> </tr> <tr> <td> <input type="text" id="item_cuisine_CuisineName" name="item.cuisine.CuisineName" value="Greek" /> Greek </td> </tr> ```
2018/06/06
[ "https://Stackoverflow.com/questions/50729551", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3767719/" ]
Why compiling? You should be able to install the package: ``` sudo add-apt-repository ppa:ubuntu-toolchain-r/test sudo apt update sudo apt install g++-7 -y ``` Verify using: ``` gcc-7 --version ``` See [How to install gcc-7 or clang 4.0?](https://askubuntu.com/questions/859256/how-to-install-gcc-7-or-clang-4-0)
As you can see [here](https://packages.ubuntu.com/search?keywords=g%2B%2B), `g++` is just a package in the default ubuntu package repository (for ubuntu 18.04, 20.04 and 22.04 and others). So it's actually enough to just run this. ``` sudo apt update sudo apt install g++ ``` Afterwards you can check with: ``` g++ --version ``` which resulted in version 9.4.0 at the time of writing. However, you can also pick a specific version (e.g. `apt install g++-12`). However then the binary will also have a specific name (e.g. `g++-12`) and you may need to add a symlink if you need it to be `g++`. (e.g. `ln -s /usr/bin/g++-12 /usr/bin/g++`).
50,729,551
I am generating multi Data entry Line using ASP MVC , however looking at the HTML source after generating by MVC, I've just noticed those HTML elements has a duplicated ID , even with the same html type it is look something wrong ? is that normal behavior in MVC and how to avoid it ? , I need really to have it unique, assuming MVC should handle the ID generation for multi line, which is additional concern to me . My code : ``` @foreach (var item in Model.lstMeals) { <tr> <td> <input asp-for="@item.cuisine.CuisineName" /> @Html.DisplayFor(modelItem => item.cuisine.CuisineName) </td> </tr> } ``` then looking in HTML Source : ```html <tr> <td> <input type="text" id="item_cuisine_CuisineName" name="item.cuisine.CuisineName" value="Italian" /> Italian </td> </tr> <tr> <td> <input type="text" id="item_cuisine_CuisineName" name="item.cuisine.CuisineName" value="French" /> French </td> </tr> <tr> <td> <input type="text" id="item_cuisine_CuisineName" name="item.cuisine.CuisineName" value="Greek" /> Greek </td> </tr> ```
2018/06/06
[ "https://Stackoverflow.com/questions/50729551", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3767719/" ]
run the following ``` sudo apt install aptitude sudo aptitude install gcc-7 g++-7 ``` or ``` sudo apt install aptitude && sudo aptitude install golang gcc-7 g++-7 ```
`crt1.o` is generally provided as part of the `libdevc` dependency (or something similar). I would suggest running `sudo apt search libc` or some similar variant with `lib6c`, `libdev`, `libc-dev` etc. Installing those fixed a similar issue I had recently. Failing that, run `find / -iname ctri.o` and add the folder it appears in to your PATH with `export PATH="[folder]:$PATH"`, and see if that helps.
50,729,551
I am generating multi Data entry Line using ASP MVC , however looking at the HTML source after generating by MVC, I've just noticed those HTML elements has a duplicated ID , even with the same html type it is look something wrong ? is that normal behavior in MVC and how to avoid it ? , I need really to have it unique, assuming MVC should handle the ID generation for multi line, which is additional concern to me . My code : ``` @foreach (var item in Model.lstMeals) { <tr> <td> <input asp-for="@item.cuisine.CuisineName" /> @Html.DisplayFor(modelItem => item.cuisine.CuisineName) </td> </tr> } ``` then looking in HTML Source : ```html <tr> <td> <input type="text" id="item_cuisine_CuisineName" name="item.cuisine.CuisineName" value="Italian" /> Italian </td> </tr> <tr> <td> <input type="text" id="item_cuisine_CuisineName" name="item.cuisine.CuisineName" value="French" /> French </td> </tr> <tr> <td> <input type="text" id="item_cuisine_CuisineName" name="item.cuisine.CuisineName" value="Greek" /> Greek </td> </tr> ```
2018/06/06
[ "https://Stackoverflow.com/questions/50729551", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3767719/" ]
`crt1.o` is generally provided as part of the `libdevc` dependency (or something similar). I would suggest running `sudo apt search libc` or some similar variant with `lib6c`, `libdev`, `libc-dev` etc. Installing those fixed a similar issue I had recently. Failing that, run `find / -iname ctri.o` and add the folder it appears in to your PATH with `export PATH="[folder]:$PATH"`, and see if that helps.
As you can see [here](https://packages.ubuntu.com/search?keywords=g%2B%2B), `g++` is just a package in the default ubuntu package repository (for ubuntu 18.04, 20.04 and 22.04 and others). So it's actually enough to just run this. ``` sudo apt update sudo apt install g++ ``` Afterwards you can check with: ``` g++ --version ``` which resulted in version 9.4.0 at the time of writing. However, you can also pick a specific version (e.g. `apt install g++-12`). However then the binary will also have a specific name (e.g. `g++-12`) and you may need to add a symlink if you need it to be `g++`. (e.g. `ln -s /usr/bin/g++-12 /usr/bin/g++`).
50,729,551
I am generating multi Data entry Line using ASP MVC , however looking at the HTML source after generating by MVC, I've just noticed those HTML elements has a duplicated ID , even with the same html type it is look something wrong ? is that normal behavior in MVC and how to avoid it ? , I need really to have it unique, assuming MVC should handle the ID generation for multi line, which is additional concern to me . My code : ``` @foreach (var item in Model.lstMeals) { <tr> <td> <input asp-for="@item.cuisine.CuisineName" /> @Html.DisplayFor(modelItem => item.cuisine.CuisineName) </td> </tr> } ``` then looking in HTML Source : ```html <tr> <td> <input type="text" id="item_cuisine_CuisineName" name="item.cuisine.CuisineName" value="Italian" /> Italian </td> </tr> <tr> <td> <input type="text" id="item_cuisine_CuisineName" name="item.cuisine.CuisineName" value="French" /> French </td> </tr> <tr> <td> <input type="text" id="item_cuisine_CuisineName" name="item.cuisine.CuisineName" value="Greek" /> Greek </td> </tr> ```
2018/06/06
[ "https://Stackoverflow.com/questions/50729551", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3767719/" ]
run the following ``` sudo apt install aptitude sudo aptitude install gcc-7 g++-7 ``` or ``` sudo apt install aptitude && sudo aptitude install golang gcc-7 g++-7 ```
As you can see [here](https://packages.ubuntu.com/search?keywords=g%2B%2B), `g++` is just a package in the default ubuntu package repository (for ubuntu 18.04, 20.04 and 22.04 and others). So it's actually enough to just run this. ``` sudo apt update sudo apt install g++ ``` Afterwards you can check with: ``` g++ --version ``` which resulted in version 9.4.0 at the time of writing. However, you can also pick a specific version (e.g. `apt install g++-12`). However then the binary will also have a specific name (e.g. `g++-12`) and you may need to add a symlink if you need it to be `g++`. (e.g. `ln -s /usr/bin/g++-12 /usr/bin/g++`).
2,063,619
I'm new in this XSLT-thing and I can't figure out how to this: This is a snippet from the xml i start with: ``` <Article> <Bullettext>10,00 </Bullettext> <Bullettext>8,00 </Bullettext> </Article> <Article> <something>some text</something> </Article> <Article> <Corpsdetexte>Bulgaria</Corpsdetexte> <Bullettext>15,0 </Bullettext> <Bullettext>10,0 </Bullettext> </Article> ` ``` This is what i want the output to be: ``` <LIST> <ITEM>12,00 </ITEM> <ITEM>10,00 </ITEM> <ITEM>8,00 </ITEM> </LIST> <P> <something>some text</something> </P> <P> <Corpsdetexte>Bulgaria</Corpsdetexte> </P> <LIST> <ITEM>15,0 </ITEM> <ITEM>10,0 </ITEM> </LIST> ``` Any ideas??
2010/01/14
[ "https://Stackoverflow.com/questions/2063619", "https://Stackoverflow.com", "https://Stackoverflow.com/users/250665/" ]
I think you're looking for a [conditional deep-copy](http://www.dpawson.co.uk/xsl/sect2/N8367.html#d11679e58). Here's the code in the link above rewritten for your situation: ``` <?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:template match="@*|node()"> <xsl:copy> <xsl:apply-templates select="@*|node()" /> </xsl:copy> </xsl:template> <!-- nodes with Bullettext children --> <xsl:template match="*[Bullettext]"> <!-- for every child --> <xsl:copy> <xsl:for-each select="*"> <!-- if child is a Bullettext and it has a Bullettext before it, don't copy it (it has already been copied) --> <xsl:if test="not(local-name(.) = 'Bullettext' and local-name(./preceding-sibling::*[1]) = 'Bullettext')"> <xsl:choose> <xsl:when test="local-name(.) = 'Bullettext'"> <!-- copy all Bullettext children adjacent to this one and each other --> <LIST> <xsl:call-template name="get-all-adjacent-siblings"> <xsl:with-param name="sibling-before" select="." /> </xsl:call-template> </LIST> </xsl:when> <xsl:otherwise> <!-- copy non-Bullettext child --> <xsl:apply-templates select="." /> </xsl:otherwise> </xsl:choose> </xsl:if> </xsl:for-each> </xsl:copy> </xsl:template> <xsl:template name="get-all-adjacent-siblings"> <xsl:param name="sibling-before" /> <!-- return me --> <xsl:copy> <xsl:value-of select="$sibling-before" /> </xsl:copy> <!-- return my adjacent Bullettext siblings below me --> <xsl:if test="local-name($sibling-before/following-sibling::*[1]) = 'Bullettext'"> <xsl:call-template name="get-all-adjacent-siblings"> <xsl:with-param name="sibling-before" select="$sibling-before/following-sibling::*[1]" /> </xsl:call-template> </xsl:if> </xsl:template> </xsl:stylesheet> ``` The input I used was: ``` <?xml version="1.0" encoding="utf-8"?> <Articles> <Article> <Bullettext>10,00 </Bullettext> <Bullettext>8,00 </Bullettext> </Article> <Article> <something>some text</something> </Article> <Article> <Corpsdetexte>Bulgaria</Corpsdetexte> <deeper> <before>dogs</before> <Bullettext>15,0 </Bullettext> <Bullettext>10,0 </Bullettext> <middle>cats</middle> <Bullettext>25,0 </Bullettext> <Bullettext>20,0 </Bullettext> <after>cows</after> </deeper> </Article> </Articles> ``` And it gave me: ``` <?xml version="1.0" encoding="UTF-8"?> <Articles> <Article> <LIST> <Bullettext>10,00 </Bullettext> <Bullettext>8,00 </Bullettext> </LIST> </Article> <Article> <something>some text</something> </Article> <Article> <Corpsdetexte>Bulgaria</Corpsdetexte> <deeper> <before>dogs</before> <LIST> <Bullettext>15,0 </Bullettext> <Bullettext>10,0 </Bullettext> </LIST> <middle>cats</middle> <LIST> <Bullettext>25,0 </Bullettext> <Bullettext>20,0 </Bullettext> </LIST> <after>cows</after> </deeper> </Article> </Articles> ``` It's a bit messy if you want to do the other transformations like adding `<p></p>`s in the same stylesheet but if you do a two step transformation with two stylesheets, the first doing the conditional deep copy above and then the second doing your main transformation using the result of the first, you should be good to go.
Try something like this: ``` <?xml version="1.0" encoding="iso-8859-1"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:template match="/Articles"> <LIST> <xsl:for-each select="Article[1]/Bullettext"> <ITEM> <xsl:value-of select="." /> </ITEM> </xsl:for-each> </LIST> <p> <something> <xsl:value-of select="Article[2]/something" /> </something> </p> <p> <Corpsdetexte> <xsl:value-of select="Article[3]/Corpsdetexte" /> </Corpsdetexte> </p> <LIST> <xsl:for-each select="Article[4]/Bullettext"> <ITEM> <xsl:value-of select="." /> </ITEM> </xsl:for-each> </LIST> </xsl:template> </xsl:stylesheet> ```
2,063,619
I'm new in this XSLT-thing and I can't figure out how to this: This is a snippet from the xml i start with: ``` <Article> <Bullettext>10,00 </Bullettext> <Bullettext>8,00 </Bullettext> </Article> <Article> <something>some text</something> </Article> <Article> <Corpsdetexte>Bulgaria</Corpsdetexte> <Bullettext>15,0 </Bullettext> <Bullettext>10,0 </Bullettext> </Article> ` ``` This is what i want the output to be: ``` <LIST> <ITEM>12,00 </ITEM> <ITEM>10,00 </ITEM> <ITEM>8,00 </ITEM> </LIST> <P> <something>some text</something> </P> <P> <Corpsdetexte>Bulgaria</Corpsdetexte> </P> <LIST> <ITEM>15,0 </ITEM> <ITEM>10,0 </ITEM> </LIST> ``` Any ideas??
2010/01/14
[ "https://Stackoverflow.com/questions/2063619", "https://Stackoverflow.com", "https://Stackoverflow.com/users/250665/" ]
From your comment in response to Rubens Farias's answer (and really, that's something you should edit your question to include), it seems that you want a generic way to transform any group of adjacent `BulletText` elements into a list. That gets us to two questions: how do we find such groups, and having found them, how do we transform them into a list? To find a group, we need to look for all `BulletText` elements whose immediately preceding sibling *isn't* a `BulletText` element. Each one of those starts a group, and those are the elements that we're going to transform into lists. So the first thing we want to do is create an XPath expression that will find them: ``` BulletText[not(preceding-sibling::*[1][name()='BulletText'])] ``` If you look at the predicates in that XPath expression, it's doing just what I said we need to do: it matches a `BulletText` element if it's not the case that its first preceding sibling (`preceding-sibling::*[1]`) has a name of `BulletText`. Note that if the element *has* no preceding sibling, this expression will still match it. So now we can create a template that matches these start-of-group elements. What do we put inside this template? We're going to transform these elements into `LIST` elements, so the template's going to start out looking like: ``` <LIST> ... </LIST> ``` Easy enough. But how do we find the elements that are going to populate that list? There are two cases we have to deal with. The first is simple: if all of the following siblings are `BulletText` elements, we want to populate the list with this element and all of its following siblings. The second is harder. If there's a following sibling that's not a `BulletText` element, we want our list to be all of the children of the current element's parent, starting at the current element and ending before the stop element. Here is a case where we need to use the `count()` function to calculate the starting and ending indexes, and the `position()` function to find the position of each element. The completed template looks like this: ``` <xsl:template match="BulletText[not(preceding-sibling::*[1][name()='BulletText'])]"> <!-- find the element that we want to stop at --> <xsl:variable name="stop" select="./following-sibling::*[name() != 'BulletText'][1]"/> <LIST> <xsl:choose> <!-- first, the simple case: there's no element we have to stop at --> <xsl:when test="not($stop)"> <xsl:apply-templates select="." mode="item"/> <xsl:apply-templates select="./following-sibling::BulletText" mode="item"/> </xsl:when> <!-- transform all elements between the start and stop index into items --> <xsl:otherwise> <xsl:variable name="start_index" select="count(preceding-sibling::*) + 1"/> <xsl:variable name="stop_index" select="count($stop/preceding-sibling::*)"/> <xsl:apply-templates select="../*[position() &gt;= $start_index and position() &lt;= $stop_index]" mode="item"/> </xsl:otherwise> </xsl:choose> </LIST> </xsl:template> ``` You need two other templates. One converts `BulletText` elements into items - we use `mode` here so that we can apply it to `BulletText` elements without invoking the template we're currently using: ``` <xsl:template match="BulletText" mode="item"> <ITEM> <xsl:value-of select="."/> </ITEM> </xsl:template> ``` Then you also need a template that keeps `BulletText` elements that our first template *doesn't* match from generating any output (because if we're using the identity transform, they'll just get copied if we don't): ``` <xsl:template match='BulletText'/> ``` Because of the magic of XSLT's template precedence rules, any `BulletText` element that both templates match will be transformed by the first one, and this one will catch the rest. Just add those three templates to the identity transform and you're good to go.
Try something like this: ``` <?xml version="1.0" encoding="iso-8859-1"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:template match="/Articles"> <LIST> <xsl:for-each select="Article[1]/Bullettext"> <ITEM> <xsl:value-of select="." /> </ITEM> </xsl:for-each> </LIST> <p> <something> <xsl:value-of select="Article[2]/something" /> </something> </p> <p> <Corpsdetexte> <xsl:value-of select="Article[3]/Corpsdetexte" /> </Corpsdetexte> </p> <LIST> <xsl:for-each select="Article[4]/Bullettext"> <ITEM> <xsl:value-of select="." /> </ITEM> </xsl:for-each> </LIST> </xsl:template> </xsl:stylesheet> ```
2,063,619
I'm new in this XSLT-thing and I can't figure out how to this: This is a snippet from the xml i start with: ``` <Article> <Bullettext>10,00 </Bullettext> <Bullettext>8,00 </Bullettext> </Article> <Article> <something>some text</something> </Article> <Article> <Corpsdetexte>Bulgaria</Corpsdetexte> <Bullettext>15,0 </Bullettext> <Bullettext>10,0 </Bullettext> </Article> ` ``` This is what i want the output to be: ``` <LIST> <ITEM>12,00 </ITEM> <ITEM>10,00 </ITEM> <ITEM>8,00 </ITEM> </LIST> <P> <something>some text</something> </P> <P> <Corpsdetexte>Bulgaria</Corpsdetexte> </P> <LIST> <ITEM>15,0 </ITEM> <ITEM>10,0 </ITEM> </LIST> ``` Any ideas??
2010/01/14
[ "https://Stackoverflow.com/questions/2063619", "https://Stackoverflow.com", "https://Stackoverflow.com/users/250665/" ]
Grouping Siblings with Three Templates -------------------------------------- Although there are currently several working answers to this question, you can actually group siblings very easily with three templates and the identity. First, you need a template that will just remove all of the nodes and set its priority, so that we can override it with another template. ``` <xsl:template match="Bullettext" priority="1"/> ``` Then, define a template that matches any node that is not preceded by itself, assigning it a higher priority. This template will inject the group and then start copying nodes in a different mode. ``` <xsl:template match="Bullettext[not(preceding-sibling::*[1][self::Bullettext])]" priority="2"> <LIST> <xsl:apply-templates select="." mode="bullet-list"/> </LIST> </xsl:template> ``` Finally, define a tail recursive template to deal with the items being grouped. ``` <xsl:template match="Bullettext" mode="bullet-list"> <ITEM> <xsl:apply-templates select="@*|node()"/> </ITEM> <xsl:apply-templates select="following-sibling::*[1][self::Bullettext]" mode="bullet-list"/> </xsl:template> ``` Here is a complete stylesheet that will group the Bullettext elements in the example: ``` <?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output indent="yes" /> <!-- Identity --> <xsl:template match="@*|node()"> <xsl:copy> <xsl:apply-templates select="@*|node()" /> </xsl:copy> </xsl:template> <!-- Removes the Bullettext elements in the default mode. --> <xsl:template match="Bullettext" priority="1" /> <!-- Creates the LIST elements around the removed Bullettext elements. --> <xsl:template match="Bullettext[not(preceding-sibling::*[1][self::Bullettext])]" priority="2"> <LIST> <xsl:apply-templates select="." mode="bullet-list" /> </LIST> </xsl:template> <!-- Converts sequential Bullettext elements into ITEM elements. --> <xsl:template match="Bullettext" mode="bullet-list"> <ITEM> <xsl:apply-templates select="@*|node()" /> </ITEM> <xsl:apply-templates select="following-sibling::*[1][self::Bullettext]" mode="bullet-list" /> </xsl:template> </xsl:stylesheet> ```
Try something like this: ``` <?xml version="1.0" encoding="iso-8859-1"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:template match="/Articles"> <LIST> <xsl:for-each select="Article[1]/Bullettext"> <ITEM> <xsl:value-of select="." /> </ITEM> </xsl:for-each> </LIST> <p> <something> <xsl:value-of select="Article[2]/something" /> </something> </p> <p> <Corpsdetexte> <xsl:value-of select="Article[3]/Corpsdetexte" /> </Corpsdetexte> </p> <LIST> <xsl:for-each select="Article[4]/Bullettext"> <ITEM> <xsl:value-of select="." /> </ITEM> </xsl:for-each> </LIST> </xsl:template> </xsl:stylesheet> ```
2,063,619
I'm new in this XSLT-thing and I can't figure out how to this: This is a snippet from the xml i start with: ``` <Article> <Bullettext>10,00 </Bullettext> <Bullettext>8,00 </Bullettext> </Article> <Article> <something>some text</something> </Article> <Article> <Corpsdetexte>Bulgaria</Corpsdetexte> <Bullettext>15,0 </Bullettext> <Bullettext>10,0 </Bullettext> </Article> ` ``` This is what i want the output to be: ``` <LIST> <ITEM>12,00 </ITEM> <ITEM>10,00 </ITEM> <ITEM>8,00 </ITEM> </LIST> <P> <something>some text</something> </P> <P> <Corpsdetexte>Bulgaria</Corpsdetexte> </P> <LIST> <ITEM>15,0 </ITEM> <ITEM>10,0 </ITEM> </LIST> ``` Any ideas??
2010/01/14
[ "https://Stackoverflow.com/questions/2063619", "https://Stackoverflow.com", "https://Stackoverflow.com/users/250665/" ]
From your comment in response to Rubens Farias's answer (and really, that's something you should edit your question to include), it seems that you want a generic way to transform any group of adjacent `BulletText` elements into a list. That gets us to two questions: how do we find such groups, and having found them, how do we transform them into a list? To find a group, we need to look for all `BulletText` elements whose immediately preceding sibling *isn't* a `BulletText` element. Each one of those starts a group, and those are the elements that we're going to transform into lists. So the first thing we want to do is create an XPath expression that will find them: ``` BulletText[not(preceding-sibling::*[1][name()='BulletText'])] ``` If you look at the predicates in that XPath expression, it's doing just what I said we need to do: it matches a `BulletText` element if it's not the case that its first preceding sibling (`preceding-sibling::*[1]`) has a name of `BulletText`. Note that if the element *has* no preceding sibling, this expression will still match it. So now we can create a template that matches these start-of-group elements. What do we put inside this template? We're going to transform these elements into `LIST` elements, so the template's going to start out looking like: ``` <LIST> ... </LIST> ``` Easy enough. But how do we find the elements that are going to populate that list? There are two cases we have to deal with. The first is simple: if all of the following siblings are `BulletText` elements, we want to populate the list with this element and all of its following siblings. The second is harder. If there's a following sibling that's not a `BulletText` element, we want our list to be all of the children of the current element's parent, starting at the current element and ending before the stop element. Here is a case where we need to use the `count()` function to calculate the starting and ending indexes, and the `position()` function to find the position of each element. The completed template looks like this: ``` <xsl:template match="BulletText[not(preceding-sibling::*[1][name()='BulletText'])]"> <!-- find the element that we want to stop at --> <xsl:variable name="stop" select="./following-sibling::*[name() != 'BulletText'][1]"/> <LIST> <xsl:choose> <!-- first, the simple case: there's no element we have to stop at --> <xsl:when test="not($stop)"> <xsl:apply-templates select="." mode="item"/> <xsl:apply-templates select="./following-sibling::BulletText" mode="item"/> </xsl:when> <!-- transform all elements between the start and stop index into items --> <xsl:otherwise> <xsl:variable name="start_index" select="count(preceding-sibling::*) + 1"/> <xsl:variable name="stop_index" select="count($stop/preceding-sibling::*)"/> <xsl:apply-templates select="../*[position() &gt;= $start_index and position() &lt;= $stop_index]" mode="item"/> </xsl:otherwise> </xsl:choose> </LIST> </xsl:template> ``` You need two other templates. One converts `BulletText` elements into items - we use `mode` here so that we can apply it to `BulletText` elements without invoking the template we're currently using: ``` <xsl:template match="BulletText" mode="item"> <ITEM> <xsl:value-of select="."/> </ITEM> </xsl:template> ``` Then you also need a template that keeps `BulletText` elements that our first template *doesn't* match from generating any output (because if we're using the identity transform, they'll just get copied if we don't): ``` <xsl:template match='BulletText'/> ``` Because of the magic of XSLT's template precedence rules, any `BulletText` element that both templates match will be transformed by the first one, and this one will catch the rest. Just add those three templates to the identity transform and you're good to go.
I think you're looking for a [conditional deep-copy](http://www.dpawson.co.uk/xsl/sect2/N8367.html#d11679e58). Here's the code in the link above rewritten for your situation: ``` <?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:template match="@*|node()"> <xsl:copy> <xsl:apply-templates select="@*|node()" /> </xsl:copy> </xsl:template> <!-- nodes with Bullettext children --> <xsl:template match="*[Bullettext]"> <!-- for every child --> <xsl:copy> <xsl:for-each select="*"> <!-- if child is a Bullettext and it has a Bullettext before it, don't copy it (it has already been copied) --> <xsl:if test="not(local-name(.) = 'Bullettext' and local-name(./preceding-sibling::*[1]) = 'Bullettext')"> <xsl:choose> <xsl:when test="local-name(.) = 'Bullettext'"> <!-- copy all Bullettext children adjacent to this one and each other --> <LIST> <xsl:call-template name="get-all-adjacent-siblings"> <xsl:with-param name="sibling-before" select="." /> </xsl:call-template> </LIST> </xsl:when> <xsl:otherwise> <!-- copy non-Bullettext child --> <xsl:apply-templates select="." /> </xsl:otherwise> </xsl:choose> </xsl:if> </xsl:for-each> </xsl:copy> </xsl:template> <xsl:template name="get-all-adjacent-siblings"> <xsl:param name="sibling-before" /> <!-- return me --> <xsl:copy> <xsl:value-of select="$sibling-before" /> </xsl:copy> <!-- return my adjacent Bullettext siblings below me --> <xsl:if test="local-name($sibling-before/following-sibling::*[1]) = 'Bullettext'"> <xsl:call-template name="get-all-adjacent-siblings"> <xsl:with-param name="sibling-before" select="$sibling-before/following-sibling::*[1]" /> </xsl:call-template> </xsl:if> </xsl:template> </xsl:stylesheet> ``` The input I used was: ``` <?xml version="1.0" encoding="utf-8"?> <Articles> <Article> <Bullettext>10,00 </Bullettext> <Bullettext>8,00 </Bullettext> </Article> <Article> <something>some text</something> </Article> <Article> <Corpsdetexte>Bulgaria</Corpsdetexte> <deeper> <before>dogs</before> <Bullettext>15,0 </Bullettext> <Bullettext>10,0 </Bullettext> <middle>cats</middle> <Bullettext>25,0 </Bullettext> <Bullettext>20,0 </Bullettext> <after>cows</after> </deeper> </Article> </Articles> ``` And it gave me: ``` <?xml version="1.0" encoding="UTF-8"?> <Articles> <Article> <LIST> <Bullettext>10,00 </Bullettext> <Bullettext>8,00 </Bullettext> </LIST> </Article> <Article> <something>some text</something> </Article> <Article> <Corpsdetexte>Bulgaria</Corpsdetexte> <deeper> <before>dogs</before> <LIST> <Bullettext>15,0 </Bullettext> <Bullettext>10,0 </Bullettext> </LIST> <middle>cats</middle> <LIST> <Bullettext>25,0 </Bullettext> <Bullettext>20,0 </Bullettext> </LIST> <after>cows</after> </deeper> </Article> </Articles> ``` It's a bit messy if you want to do the other transformations like adding `<p></p>`s in the same stylesheet but if you do a two step transformation with two stylesheets, the first doing the conditional deep copy above and then the second doing your main transformation using the result of the first, you should be good to go.
2,063,619
I'm new in this XSLT-thing and I can't figure out how to this: This is a snippet from the xml i start with: ``` <Article> <Bullettext>10,00 </Bullettext> <Bullettext>8,00 </Bullettext> </Article> <Article> <something>some text</something> </Article> <Article> <Corpsdetexte>Bulgaria</Corpsdetexte> <Bullettext>15,0 </Bullettext> <Bullettext>10,0 </Bullettext> </Article> ` ``` This is what i want the output to be: ``` <LIST> <ITEM>12,00 </ITEM> <ITEM>10,00 </ITEM> <ITEM>8,00 </ITEM> </LIST> <P> <something>some text</something> </P> <P> <Corpsdetexte>Bulgaria</Corpsdetexte> </P> <LIST> <ITEM>15,0 </ITEM> <ITEM>10,0 </ITEM> </LIST> ``` Any ideas??
2010/01/14
[ "https://Stackoverflow.com/questions/2063619", "https://Stackoverflow.com", "https://Stackoverflow.com/users/250665/" ]
From your comment in response to Rubens Farias's answer (and really, that's something you should edit your question to include), it seems that you want a generic way to transform any group of adjacent `BulletText` elements into a list. That gets us to two questions: how do we find such groups, and having found them, how do we transform them into a list? To find a group, we need to look for all `BulletText` elements whose immediately preceding sibling *isn't* a `BulletText` element. Each one of those starts a group, and those are the elements that we're going to transform into lists. So the first thing we want to do is create an XPath expression that will find them: ``` BulletText[not(preceding-sibling::*[1][name()='BulletText'])] ``` If you look at the predicates in that XPath expression, it's doing just what I said we need to do: it matches a `BulletText` element if it's not the case that its first preceding sibling (`preceding-sibling::*[1]`) has a name of `BulletText`. Note that if the element *has* no preceding sibling, this expression will still match it. So now we can create a template that matches these start-of-group elements. What do we put inside this template? We're going to transform these elements into `LIST` elements, so the template's going to start out looking like: ``` <LIST> ... </LIST> ``` Easy enough. But how do we find the elements that are going to populate that list? There are two cases we have to deal with. The first is simple: if all of the following siblings are `BulletText` elements, we want to populate the list with this element and all of its following siblings. The second is harder. If there's a following sibling that's not a `BulletText` element, we want our list to be all of the children of the current element's parent, starting at the current element and ending before the stop element. Here is a case where we need to use the `count()` function to calculate the starting and ending indexes, and the `position()` function to find the position of each element. The completed template looks like this: ``` <xsl:template match="BulletText[not(preceding-sibling::*[1][name()='BulletText'])]"> <!-- find the element that we want to stop at --> <xsl:variable name="stop" select="./following-sibling::*[name() != 'BulletText'][1]"/> <LIST> <xsl:choose> <!-- first, the simple case: there's no element we have to stop at --> <xsl:when test="not($stop)"> <xsl:apply-templates select="." mode="item"/> <xsl:apply-templates select="./following-sibling::BulletText" mode="item"/> </xsl:when> <!-- transform all elements between the start and stop index into items --> <xsl:otherwise> <xsl:variable name="start_index" select="count(preceding-sibling::*) + 1"/> <xsl:variable name="stop_index" select="count($stop/preceding-sibling::*)"/> <xsl:apply-templates select="../*[position() &gt;= $start_index and position() &lt;= $stop_index]" mode="item"/> </xsl:otherwise> </xsl:choose> </LIST> </xsl:template> ``` You need two other templates. One converts `BulletText` elements into items - we use `mode` here so that we can apply it to `BulletText` elements without invoking the template we're currently using: ``` <xsl:template match="BulletText" mode="item"> <ITEM> <xsl:value-of select="."/> </ITEM> </xsl:template> ``` Then you also need a template that keeps `BulletText` elements that our first template *doesn't* match from generating any output (because if we're using the identity transform, they'll just get copied if we don't): ``` <xsl:template match='BulletText'/> ``` Because of the magic of XSLT's template precedence rules, any `BulletText` element that both templates match will be transformed by the first one, and this one will catch the rest. Just add those three templates to the identity transform and you're good to go.
Grouping Siblings with Three Templates -------------------------------------- Although there are currently several working answers to this question, you can actually group siblings very easily with three templates and the identity. First, you need a template that will just remove all of the nodes and set its priority, so that we can override it with another template. ``` <xsl:template match="Bullettext" priority="1"/> ``` Then, define a template that matches any node that is not preceded by itself, assigning it a higher priority. This template will inject the group and then start copying nodes in a different mode. ``` <xsl:template match="Bullettext[not(preceding-sibling::*[1][self::Bullettext])]" priority="2"> <LIST> <xsl:apply-templates select="." mode="bullet-list"/> </LIST> </xsl:template> ``` Finally, define a tail recursive template to deal with the items being grouped. ``` <xsl:template match="Bullettext" mode="bullet-list"> <ITEM> <xsl:apply-templates select="@*|node()"/> </ITEM> <xsl:apply-templates select="following-sibling::*[1][self::Bullettext]" mode="bullet-list"/> </xsl:template> ``` Here is a complete stylesheet that will group the Bullettext elements in the example: ``` <?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output indent="yes" /> <!-- Identity --> <xsl:template match="@*|node()"> <xsl:copy> <xsl:apply-templates select="@*|node()" /> </xsl:copy> </xsl:template> <!-- Removes the Bullettext elements in the default mode. --> <xsl:template match="Bullettext" priority="1" /> <!-- Creates the LIST elements around the removed Bullettext elements. --> <xsl:template match="Bullettext[not(preceding-sibling::*[1][self::Bullettext])]" priority="2"> <LIST> <xsl:apply-templates select="." mode="bullet-list" /> </LIST> </xsl:template> <!-- Converts sequential Bullettext elements into ITEM elements. --> <xsl:template match="Bullettext" mode="bullet-list"> <ITEM> <xsl:apply-templates select="@*|node()" /> </ITEM> <xsl:apply-templates select="following-sibling::*[1][self::Bullettext]" mode="bullet-list" /> </xsl:template> </xsl:stylesheet> ```
46,318,086
I am working on an web application which has a query form to give search criteria. Once the query criteria is filled out in the form and searched, a table loads below the search form. Now this table is not formed by usual *tr* and *td* tags but is made up of several script tags like- ``` <TABLE> <THEAD>...</THEAD> <TBODY> <SCRIPT> var colElm1 = document.createElement("SPAN"); colElm1.innerText = "ABCD"; rowElm1.appendChild(colElm1); </SCRIPT> <SCRIPT> var colElm1 = document.createElement("SPAN"); colElm1.innerText = "AB_CD123"; rowElm1.appendChild(colElm1); </SCRIPT> .... </TBODY> </TABLE> ``` Now my problem is that is there any way to get the "ABCD" and "AB\_CD123" using selenium and not using regex on the whole source code ?
2017/09/20
[ "https://Stackoverflow.com/questions/46318086", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8639262/" ]
RSA (or any other asymmetric encryption scheme) does not work that way. You always encrypt using the public key and decrypt using the private key. What you probably want is to apply a *digital signature* to your licence instead of encrypting it. Such a signature is created using the private key and can be verified in the client with just the public key. Using a signature works like this: 1. You build your licence file on the server (which contains the machine id and unique id as you said, probably some dates) 2. You calculate a signature for that file using your private key. 3. You send the licence plus the signature to the desktop app 4. The desktop app uses the public key to the server key it already has to *verify*, that the signature really signed the licence it received 5. If this signature verification succeeded, it can accept the values of the licence file for authentic and parse and use them
Example: let's say you have a license like this: ``` <license> <hardwareId>someValue</hardwareId> <serial>123456789</serial> <feature1 enabled="true" someOtherFeatureParameter="42"/> </license> ``` you can put this into a normal xml file, stored somewhere in a known path on the machine (your installation directory ... the users profile ... whatever) now while this is nice and shiny, storing all license related information, it does not protect you against a malicious user editing (or creating in the first place) said file, enabling features they didn't pay for (or even creating a license file they didn't pay for) ... what does this have to do with digital signatures? ... a digital signature is exactly that what makes tampering with the license a bit harder ... embed a public key into your application and place a signature in a second file (or put the signature together with the license into the xml file) the thing about a digital signature is: if you change even just one bit of the signed data, the signature becomes invalid so all your application has to do is to verify if the signature is valid, and only then accpet the information in the license file to create a signature, you need the private key that corresponds to the public key the signature will be verified with. Since you do not ship the private key with your application, the user does not have that... of course this system can be broken by replacing the embedded publik key with a new one, but that is a bit more effort than editing a text/xml file ...
46,318,086
I am working on an web application which has a query form to give search criteria. Once the query criteria is filled out in the form and searched, a table loads below the search form. Now this table is not formed by usual *tr* and *td* tags but is made up of several script tags like- ``` <TABLE> <THEAD>...</THEAD> <TBODY> <SCRIPT> var colElm1 = document.createElement("SPAN"); colElm1.innerText = "ABCD"; rowElm1.appendChild(colElm1); </SCRIPT> <SCRIPT> var colElm1 = document.createElement("SPAN"); colElm1.innerText = "AB_CD123"; rowElm1.appendChild(colElm1); </SCRIPT> .... </TBODY> </TABLE> ``` Now my problem is that is there any way to get the "ABCD" and "AB\_CD123" using selenium and not using regex on the whole source code ?
2017/09/20
[ "https://Stackoverflow.com/questions/46318086", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8639262/" ]
RSA (or any other asymmetric encryption scheme) does not work that way. You always encrypt using the public key and decrypt using the private key. What you probably want is to apply a *digital signature* to your licence instead of encrypting it. Such a signature is created using the private key and can be verified in the client with just the public key. Using a signature works like this: 1. You build your licence file on the server (which contains the machine id and unique id as you said, probably some dates) 2. You calculate a signature for that file using your private key. 3. You send the licence plus the signature to the desktop app 4. The desktop app uses the public key to the server key it already has to *verify*, that the signature really signed the licence it received 5. If this signature verification succeeded, it can accept the values of the licence file for authentic and parse and use them
The public key can only encrypt, you cant figure out the actual context of the files. However you can implement an encryption within the clients-application, and every clie,t makes his own private and public key. then the app send a request for the servers publickey, and sent its own publickey (possibly encrypted) to the server. now both can en-and decrypt the information only. You only have to make sure to implement simething to verify your server to the client. lg!
48,411,212
I require solving a large set of (independent) *Ax*=*b* linear problems. This cannot be parallelized (or more specifically, this is within each processor's responsibility anyway). The *Ax*=*b* sets are small (say 10x10 at most) but are dense (Usually all terms are non-zero) and both A matrices and RHS vectors are completely different and independent. What is the most efficient/practical way of solving a large set of small Ax=b problems using PETSc? I.e. how costly would it be to have a single *A* matrix and a single *b* vector to be modified all the time and solved for each system?
2018/01/23
[ "https://Stackoverflow.com/questions/48411212", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4182862/" ]
Try using `MERGE` instead of `INSERT`. `MERGE` allows you to output a column you didn't insert, such as an identifier on your temp table. Using this method, you can build another temporary table that maps your temp table to the inserted rows (named `@TempIdTable` in the sample below). First, give `#TempTable` its own primary key. I'll call it `TempId`. I'll also assume you have a column on `#TempTable` to store the returned primary key from `MyTable`, `ID`. ``` --Make a place to store the associated ID's DECLARE @TempIdTable TABLE ([TempId] INT NOT NULL ,[ID] INT NOT NULL) --Will only insert, as 1 never equals 0. MERGE INTO myTable USING #TempTable AS tt ON 1 = 0 WHEN NOT MATCHED THEN INSERT ([FirstName] ,[LastName]) VALUE (t.[FirstName] ,t.[LastName]) OUTPUT tt.[TempId], inserted.[ID] --Here's the magic INTO @TempIdTable --Associate the new primary keys with the temp table UPDATE #TempTable SET [ID] = t.[ID] FROM @TempIdTable t WHERE #TempTable.[TempId] = t.[TempId] ``` I was working on a similar issue and found this trick over here: [Is it possible to for SQL Output clause to return a column not being inserted?](https://stackoverflow.com/questions/10949730/is-it-possible-to-for-sql-output-clause-to-return-a-column-not-being-inserted#10950418) Here's the full code I used in my own testing. ``` CREATE TABLE [MQ] ([MESSAGEID] INT IDENTITY PRIMARY KEY ,[SUBJECT] NVARCHAR(255) NULL); CREATE TABLE [MR] ([MESSAGESEQUENCE] INT IDENTITY PRIMARY KEY ,[TO] NVARCHAR(255) NOT NULL ,[CC] NVARCHAR(255) NOT NULL ,[BCC] NVARCHAR(255) NOT NULL); CREATE TABLE #Messages ( [subject] nvarchar(255) NOT NULL ,[to] nvarchar(255) NOT NULL ,[cc] nvarchar(255) NULL ,[bcc] nvarchar(255) NULL ,[MESSAGEID] INT NULL ,[sortKey] INT IDENTITY PRIMARY KEY ); INSERT INTO #Messages VALUES ('Subject1','to1','cc1','bcc1', NULL) ,('Subject2','to2', NULL, NULL, NULL); SELECT * FROM #Messages; DECLARE @outputSort TABLE ( [sortKey] INT NOT NULL ,[MESSAGEID] INT NOT NULL ,[subject] NVARCHAR(255) ); MERGE INTO [MQ] USING #Messages M ON 1 = 0 WHEN NOT MATCHED THEN INSERT ([SUBJECT]) VALUES (M.[subject]) OUTPUT M.[SORTKEY] ,inserted.[MESSAGEID] ,inserted.[SUBJECT] INTO @outputSort; SELECT * FROM @outputSort; SELECT * FROM [MQ]; UPDATE #Messages SET MESSAGEID = O.[MESSAGEID] FROM @outputSort O WHERE #Messages.[sortKey] = O.[sortKey]; SELECT * FROM #Messages; DROP TABLE #Messages; ```
As you said, FirstName and LastName are not unique. This means you cannot use a `trigger` because there can be the same FirstName + LastName so you cannot join on them. But you can do the inverse thing: first `update` your temp table `ExternalID` (I suggest you to use `sequence` object and just do `update #t set ExternalID = next value for dbo.seq1;`) and then just insert your rows including `ExternalID` into `myTable`. To be able to insert into identity field you can use `set identity_insert myTable on` or you can re-design your destination table to contain no identity at all as now you use `sequence` for the same purpose.
48,411,212
I require solving a large set of (independent) *Ax*=*b* linear problems. This cannot be parallelized (or more specifically, this is within each processor's responsibility anyway). The *Ax*=*b* sets are small (say 10x10 at most) but are dense (Usually all terms are non-zero) and both A matrices and RHS vectors are completely different and independent. What is the most efficient/practical way of solving a large set of small Ax=b problems using PETSc? I.e. how costly would it be to have a single *A* matrix and a single *b* vector to be modified all the time and solved for each system?
2018/01/23
[ "https://Stackoverflow.com/questions/48411212", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4182862/" ]
Try using `MERGE` instead of `INSERT`. `MERGE` allows you to output a column you didn't insert, such as an identifier on your temp table. Using this method, you can build another temporary table that maps your temp table to the inserted rows (named `@TempIdTable` in the sample below). First, give `#TempTable` its own primary key. I'll call it `TempId`. I'll also assume you have a column on `#TempTable` to store the returned primary key from `MyTable`, `ID`. ``` --Make a place to store the associated ID's DECLARE @TempIdTable TABLE ([TempId] INT NOT NULL ,[ID] INT NOT NULL) --Will only insert, as 1 never equals 0. MERGE INTO myTable USING #TempTable AS tt ON 1 = 0 WHEN NOT MATCHED THEN INSERT ([FirstName] ,[LastName]) VALUE (t.[FirstName] ,t.[LastName]) OUTPUT tt.[TempId], inserted.[ID] --Here's the magic INTO @TempIdTable --Associate the new primary keys with the temp table UPDATE #TempTable SET [ID] = t.[ID] FROM @TempIdTable t WHERE #TempTable.[TempId] = t.[TempId] ``` I was working on a similar issue and found this trick over here: [Is it possible to for SQL Output clause to return a column not being inserted?](https://stackoverflow.com/questions/10949730/is-it-possible-to-for-sql-output-clause-to-return-a-column-not-being-inserted#10950418) Here's the full code I used in my own testing. ``` CREATE TABLE [MQ] ([MESSAGEID] INT IDENTITY PRIMARY KEY ,[SUBJECT] NVARCHAR(255) NULL); CREATE TABLE [MR] ([MESSAGESEQUENCE] INT IDENTITY PRIMARY KEY ,[TO] NVARCHAR(255) NOT NULL ,[CC] NVARCHAR(255) NOT NULL ,[BCC] NVARCHAR(255) NOT NULL); CREATE TABLE #Messages ( [subject] nvarchar(255) NOT NULL ,[to] nvarchar(255) NOT NULL ,[cc] nvarchar(255) NULL ,[bcc] nvarchar(255) NULL ,[MESSAGEID] INT NULL ,[sortKey] INT IDENTITY PRIMARY KEY ); INSERT INTO #Messages VALUES ('Subject1','to1','cc1','bcc1', NULL) ,('Subject2','to2', NULL, NULL, NULL); SELECT * FROM #Messages; DECLARE @outputSort TABLE ( [sortKey] INT NOT NULL ,[MESSAGEID] INT NOT NULL ,[subject] NVARCHAR(255) ); MERGE INTO [MQ] USING #Messages M ON 1 = 0 WHEN NOT MATCHED THEN INSERT ([SUBJECT]) VALUES (M.[subject]) OUTPUT M.[SORTKEY] ,inserted.[MESSAGEID] ,inserted.[SUBJECT] INTO @outputSort; SELECT * FROM @outputSort; SELECT * FROM [MQ]; UPDATE #Messages SET MESSAGEID = O.[MESSAGEID] FROM @outputSort O WHERE #Messages.[sortKey] = O.[sortKey]; SELECT * FROM #Messages; DROP TABLE #Messages; ```
We need a unique column for able to make the comparison at the update operation after the insert. That's why we are using ExternalID column temporarily. ExternalID updated by row\_nubmber. ``` ;WITH CTE AS ( SELECT *, RN = ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) FROM @TempTable ) UPDATE CTE SET ExternalID = RN ``` We are keeping the output of the insert operation in a temp table. The trick is `order by` with ExternalID, it will help us for making the unique row number for same first and last name ``` DECLARE @output TABLE ( ID INT, FirstName VARCHAR(10), LastName VARCHAR(10)) Insert into @myTable OUTPUT inserted.ID, inserted.FirstName, inserted.LastName INTO @output(ID, FirstName, LastName) select FirstName, LastName from @TempTable T order by ExternalID ``` For replacing the ExternalID column with inserted id value, we are making comparing with first name, last name and row number. ``` ;WITH TMP_T AS( SELECT *, RN = ROW_NUMBER() OVER(PARTITION BY FirstName, LastName ORDER BY ExternalID) FROM @TempTable ) ,OUT_T AS( SELECT *, RN = ROW_NUMBER() OVER(PARTITION BY FirstName, LastName ORDER BY ID) FROM @output ) UPDATE TMP_T SET ExternalID = OUT_T.ID FROM TMP_T INNER JOIN OUT_T ON TMP_T.FirstName = OUT_T.FirstName AND TMP_T.LastName = OUT_T.LastName AND TMP_T.RN = OUT_T.RN ``` Sample Data: ``` DECLARE @TempTable TABLE ( FirstName VARCHAR(10), LastName VARCHAR(10), DOB VARCHAR(10), Sex VARCHAR (10), Age VARCHAR(10), ExternalID INT) INSERT INTO @TempTable VALUES ('Serkan1', 'Arslan1', 'A','M','1',NULL), ('Serkan2', 'Arslan2', 'B','M','1',NULL), ('Serkan3', 'Arslan', 'C','M','1',NULL), ('Serkan3', 'Arslan', 'D','M','1',NULL) DECLARE @myTable TABLE ( ID INT identity(100,1), -- started from 100 for see the difference FirstName VARCHAR(10), LastName VARCHAR(10)) ``` Result: MyTable ``` ID FirstName LastName ----------- ---------- ---------- 100 Serkan1 Arslan1 101 Serkan2 Arslan2 102 Serkan3 Arslan 103 Serkan3 Arslan ``` TempTable ``` FirstName LastName DOB Sex Age ExternalID ---------- ---------- ---------- ---------- ---------- ----------- Serkan1 Arslan1 A M 1 100 Serkan2 Arslan2 B M 1 101 Serkan3 Arslan C M 1 102 Serkan3 Arslan D M 1 103 ```
48,411,212
I require solving a large set of (independent) *Ax*=*b* linear problems. This cannot be parallelized (or more specifically, this is within each processor's responsibility anyway). The *Ax*=*b* sets are small (say 10x10 at most) but are dense (Usually all terms are non-zero) and both A matrices and RHS vectors are completely different and independent. What is the most efficient/practical way of solving a large set of small Ax=b problems using PETSc? I.e. how costly would it be to have a single *A* matrix and a single *b* vector to be modified all the time and solved for each system?
2018/01/23
[ "https://Stackoverflow.com/questions/48411212", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4182862/" ]
Try using `MERGE` instead of `INSERT`. `MERGE` allows you to output a column you didn't insert, such as an identifier on your temp table. Using this method, you can build another temporary table that maps your temp table to the inserted rows (named `@TempIdTable` in the sample below). First, give `#TempTable` its own primary key. I'll call it `TempId`. I'll also assume you have a column on `#TempTable` to store the returned primary key from `MyTable`, `ID`. ``` --Make a place to store the associated ID's DECLARE @TempIdTable TABLE ([TempId] INT NOT NULL ,[ID] INT NOT NULL) --Will only insert, as 1 never equals 0. MERGE INTO myTable USING #TempTable AS tt ON 1 = 0 WHEN NOT MATCHED THEN INSERT ([FirstName] ,[LastName]) VALUE (t.[FirstName] ,t.[LastName]) OUTPUT tt.[TempId], inserted.[ID] --Here's the magic INTO @TempIdTable --Associate the new primary keys with the temp table UPDATE #TempTable SET [ID] = t.[ID] FROM @TempIdTable t WHERE #TempTable.[TempId] = t.[TempId] ``` I was working on a similar issue and found this trick over here: [Is it possible to for SQL Output clause to return a column not being inserted?](https://stackoverflow.com/questions/10949730/is-it-possible-to-for-sql-output-clause-to-return-a-column-not-being-inserted#10950418) Here's the full code I used in my own testing. ``` CREATE TABLE [MQ] ([MESSAGEID] INT IDENTITY PRIMARY KEY ,[SUBJECT] NVARCHAR(255) NULL); CREATE TABLE [MR] ([MESSAGESEQUENCE] INT IDENTITY PRIMARY KEY ,[TO] NVARCHAR(255) NOT NULL ,[CC] NVARCHAR(255) NOT NULL ,[BCC] NVARCHAR(255) NOT NULL); CREATE TABLE #Messages ( [subject] nvarchar(255) NOT NULL ,[to] nvarchar(255) NOT NULL ,[cc] nvarchar(255) NULL ,[bcc] nvarchar(255) NULL ,[MESSAGEID] INT NULL ,[sortKey] INT IDENTITY PRIMARY KEY ); INSERT INTO #Messages VALUES ('Subject1','to1','cc1','bcc1', NULL) ,('Subject2','to2', NULL, NULL, NULL); SELECT * FROM #Messages; DECLARE @outputSort TABLE ( [sortKey] INT NOT NULL ,[MESSAGEID] INT NOT NULL ,[subject] NVARCHAR(255) ); MERGE INTO [MQ] USING #Messages M ON 1 = 0 WHEN NOT MATCHED THEN INSERT ([SUBJECT]) VALUES (M.[subject]) OUTPUT M.[SORTKEY] ,inserted.[MESSAGEID] ,inserted.[SUBJECT] INTO @outputSort; SELECT * FROM @outputSort; SELECT * FROM [MQ]; UPDATE #Messages SET MESSAGEID = O.[MESSAGEID] FROM @outputSort O WHERE #Messages.[sortKey] = O.[sortKey]; SELECT * FROM #Messages; DROP TABLE #Messages; ```
One way to do this is by duplicating the data into a second temp table like so: ``` SELECT * INTO #TEMPTABLE FROM (VALUES (1, 'Adam'), (2, 'Kate'), (3, 'Jess')) AS X (Id, Name) SELECT TOP 0 CAST(NULL AS INT) AS IdentityValue, * INTO #NEWTEMPTABLE FROM #TEMPTABLE CREATE TABLE #TABLEFORINSERT ( IdentityColumn INT IDENTITY(1,1), Id INT, Name VARCHAR(255) ) INSERT INTO #TABLEFORINSERT (Id, Name) OUTPUT INSERTED.IdentityColumn, INSERTED.Id, Inserted.Name INTO #NEWTEMPTABLE SELECT Id, Name FROM #TEMPTABLE --New temp table with identity values SELECT * FROM #NEWTEMPTABLE ```
26,345,318
Building my first web-app and want to understand SQL injection better (<https://github.com/astaxie/build-web-application-with-golang/blob/master/en/eBook/09.4.md>). How much protection against SQL injection do I get from just always using the 'database/sql' library and constructing queries using '?' instead of concatting strings? What kind of SQL injection attacks will I still have to worry about in that case?
2014/10/13
[ "https://Stackoverflow.com/questions/26345318", "https://Stackoverflow.com", "https://Stackoverflow.com/users/830610/" ]
As long as you're using [Prepare](http://golang.org/pkg/database/sql/#DB.Prepare) or [Query](http://golang.org/pkg/database/sql/#DB.Query), you're safe. ``` // this is safe db.Query("SELECT name FROM users WHERE age=?", req.FormValue("age")) // this allows sql injection. db.Query("SELECT name FROM users WHERE age=" + req.FormValue("age")) ```
I agree with @Oneonone's answer. If you are retrieving data, do something like: ``` db.Query("SELECT name FROM users WHERE age=?", req.FormValue("age")) ``` If you have to insert a lot of data safely, using the same query, this is where Prepare comes handy. you can do something like this: ``` tx, err := db.Begin() if err != nil { return nil,err } stmt, err := tx.Prepare("INSERT INTO users VALUES (?, ?)") if err != nil { tx.Rollback() return nil,err } defer for i := 0; i < 10; i++ { _, err = stmt.Exec(i, "dummy") if err != nil { tx.Rollback() return nil,err } } err = tx.Commit() if err != nil { stmt.Close() tx.Rollback() return nil,err } stmt.Close() return someValue, nil ``` ref: <https://stackoverflow.com/a/46476451/5466534>
72,107,707
I'm trying to update a boolean value onclick without any luck. ```js const myDropdownMenu = document.getElementById("dropdownMenu"); const openNav = document.getElementById("openNav"); const closeNav = document.getElementById("closeNav"); let mobileMenu = false; function toggleMenu() { mobileMenu = !mobileMenu; } if (mobileMenu) { myDropdownMenu.style.display = "flex"; closeNav.style.display = "flex"; openNav.style.display = "none"; } else { myDropdownMenu.style.display = "none"; openNav.style.display = "flex"; closeNav.style.display = "none"; } ``` ```html <div> <a href="index.html"> <h1>CAVVD</h1> </a> <div id="mobileNav" class="mobileNavigation"> <button id="openNav" onclick="toggleMenu();"> Open </button> <button id="closeNav" onclick="toggleMenu();"> Close </button> <div id="dropdownMenu"> <a href="index.html#sobreNosotros">Sobre Nosotros</a> <a href="index.html#reuniones">Reuniones</a> <a href="ForodeConsultas.html">Foro de Consultas</a> <a href="index.html#HaceteVoluntario">Hacete Voluntario</a> <a href="Fotos.html">Fotos</a> <a href="index.html#contacto">Contacto</a> <a class="Dona" a href="index.html#Dona!"> Doná!</a> </div> </div> </div> ``` Everything is working except the `let mobileMenu`, that is not updating with the `toggleMenu()` function. But if I return a simple `console.log` or `alert`, it works. Can anybody help me? thanks
2022/05/04
[ "https://Stackoverflow.com/questions/72107707", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19029622/" ]
Are you sure that you add `avatar1.png` in `assets/images` folder and also add below line in `pubspec.yaml` ``` flutter: assets: - assets/images/ ```
Maybe it's because the size of the image
72,107,707
I'm trying to update a boolean value onclick without any luck. ```js const myDropdownMenu = document.getElementById("dropdownMenu"); const openNav = document.getElementById("openNav"); const closeNav = document.getElementById("closeNav"); let mobileMenu = false; function toggleMenu() { mobileMenu = !mobileMenu; } if (mobileMenu) { myDropdownMenu.style.display = "flex"; closeNav.style.display = "flex"; openNav.style.display = "none"; } else { myDropdownMenu.style.display = "none"; openNav.style.display = "flex"; closeNav.style.display = "none"; } ``` ```html <div> <a href="index.html"> <h1>CAVVD</h1> </a> <div id="mobileNav" class="mobileNavigation"> <button id="openNav" onclick="toggleMenu();"> Open </button> <button id="closeNav" onclick="toggleMenu();"> Close </button> <div id="dropdownMenu"> <a href="index.html#sobreNosotros">Sobre Nosotros</a> <a href="index.html#reuniones">Reuniones</a> <a href="ForodeConsultas.html">Foro de Consultas</a> <a href="index.html#HaceteVoluntario">Hacete Voluntario</a> <a href="Fotos.html">Fotos</a> <a href="index.html#contacto">Contacto</a> <a class="Dona" a href="index.html#Dona!"> Doná!</a> </div> </div> </div> ``` Everything is working except the `let mobileMenu`, that is not updating with the `toggleMenu()` function. But if I return a simple `console.log` or `alert`, it works. Can anybody help me? thanks
2022/05/04
[ "https://Stackoverflow.com/questions/72107707", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19029622/" ]
I have a similar issue and this is how I solved it `icon: Image.assets('images/avatar1.png')`
Maybe it's because the size of the image
72,107,707
I'm trying to update a boolean value onclick without any luck. ```js const myDropdownMenu = document.getElementById("dropdownMenu"); const openNav = document.getElementById("openNav"); const closeNav = document.getElementById("closeNav"); let mobileMenu = false; function toggleMenu() { mobileMenu = !mobileMenu; } if (mobileMenu) { myDropdownMenu.style.display = "flex"; closeNav.style.display = "flex"; openNav.style.display = "none"; } else { myDropdownMenu.style.display = "none"; openNav.style.display = "flex"; closeNav.style.display = "none"; } ``` ```html <div> <a href="index.html"> <h1>CAVVD</h1> </a> <div id="mobileNav" class="mobileNavigation"> <button id="openNav" onclick="toggleMenu();"> Open </button> <button id="closeNav" onclick="toggleMenu();"> Close </button> <div id="dropdownMenu"> <a href="index.html#sobreNosotros">Sobre Nosotros</a> <a href="index.html#reuniones">Reuniones</a> <a href="ForodeConsultas.html">Foro de Consultas</a> <a href="index.html#HaceteVoluntario">Hacete Voluntario</a> <a href="Fotos.html">Fotos</a> <a href="index.html#contacto">Contacto</a> <a class="Dona" a href="index.html#Dona!"> Doná!</a> </div> </div> </div> ``` Everything is working except the `let mobileMenu`, that is not updating with the `toggleMenu()` function. But if I return a simple `console.log` or `alert`, it works. Can anybody help me? thanks
2022/05/04
[ "https://Stackoverflow.com/questions/72107707", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19029622/" ]
Are you sure that you add `avatar1.png` in `assets/images` folder and also add below line in `pubspec.yaml` ``` flutter: assets: - assets/images/ ```
I have a similar issue and this is how I solved it `icon: Image.assets('images/avatar1.png')`