INSTRUCTION
stringlengths
25
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
reverse engineering simple encryption algorithm For a company working with a legacy system I'm trying to reverse engineer an old encryption method they use. The sourcecode for this software is missing or so I've been told. (or maybe they don't want me to see the complete workings of the system). Anyway the system uses a UNIQUE identifier and some other information to create a key. This key is used to encrypt some data. I need to reverse engineer this algorithm. (I may be in waaay over my head here but I'm gonna try). I am in posession of the information used to create the key, and the encrypted AND unencrypted data. So my best bet was to use a "Know Plaintext attack". But I'm looking for some tips or sites with more information on how to proceed. I know this might be an impossible task, but hey it's nice to try, right?
Your task is not impossible - just improbable. If you're in possession of the key and the plaintext then I'd suggest running them through as many standard algorithms as you can. It's very likely that whoever implemented the system used a common implementation of a standard algorithm. You might fall short, since any sufficiently modern cipher should not be susceptible to a known plaintext attack: <
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "encryption" }
How to create Non-optional stored properties for UIViewController Custom Subclass When subclassing `UIViewController` ( and other similar classes ) we do not have to deal with any initialization, so if I create a stored property that is not an optional, Xcode will complain that there are no initializer. **So how can I create a non-optional store property in these classes? or should I?**
You have 2 options: * initialize it inline var myProp = MyClass() * declare it as implicitly unwrapped optional: var myProp: MyClass! and initialize it anywhere in the view controller - usually in `viewDidLoad`. This is the pattern commonly used for outlets, and one of the few cases where I tolerate implicitly unwrapped
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 3, "tags": "swift, option type" }
how to use plain php variables in to $_SESSION[] variable? I'm a newbie to PHP. I'm having a problem with assigning normal variable's value to session variable. Supppose I've a variable `$abc=28;` and I want to assign this variable to `$_SESSION[]` array then how to achieve this? Thanks in advance.
assign value to session: session_start(); $_SESSION['session_name']= $abc; retrive session value: echo $_SESSION['session_name'];
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -2, "tags": "php, session, session variables" }
react-native-share method shareSingle opening Play Store in Android 11 When I use the following method it's should open the Whatsapp for share the message, but it open the Google Play in the page of the Whatsapp... Share.shareSingle({ title: 'Title Test', message: 'Message Test', social: Share.Social.WHATSAPP, }) .then(res => console.log(res)) .catch(err => { console.log(err); }); In then console return: `{"message": null, "success": true}` I'm using... React Native: 0.64.0 React Native Share: 6.2.3 Android 11 When I use the example of the React Native Share it's work success, but I don't understand why don't work in my application!
I solve this problem! In the Android 11 some information about other apps are "blocked", using the method `Share.isPackageInstalled` I realized that return not installed, then to "unblock" this we need use `<queries>` in `AndroidManifest.xml` for more details read here. Implement queries in AndroidManifest
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "android, reactjs, react native, google play, react native share" }
Pull all jpg's from a folder into a PHP array? I want to simply pull all the JPG files from a specific folder (on MY server) into an array. I figure it would look something like this. My logic here is that I'd have a folder with images I want in a gallery so I could just upload images with an FTP and they would just show up. Is this a good idea? $dir = 'www.example.com/folder1/'; $images_array = SOMEFUNCTION($dir); foreach ($images_array) as $v){ echo '<img src="'.$dir.$v.'" />"; } Thanks for the help!
glob() would work well here: $images_array = glob($dir.'*.jpg'); As Zarel commented, you'd have to do a string replacement on the files in the list, as `glob()` will give you the file path in the system, which won't be a direct URL. Chop off the directory prefix and replace it with a URL prefix using `str_replace()` when you're outputting links.
stackexchange-stackoverflow
{ "answer_score": 11, "question_score": 4, "tags": "php" }
Kotlin - What happens when a range is created using .. or how it performs comparations? I recently noticed a code refactor from: if (date < minDate || date > maxDate) to if (date !in minDate..maxDate) to which my main worry was that using range would create an "array" or some list of **all the milliseconds** between `minDate` and `maxDate` I tried researching some of the kotlin internals but couldn't get a final answer on what would happen on that case. Supposedly: > In Kotlin `in` checks are translated to the corresponding `contains` calls
No, it does not create an array of every possible value (because an array would be inefficient for that, even if we did need to store every value, which we don't). This is the source for the `ClosedRange` interface, which the `..` range operator translates into (comments removed): public interface ClosedRange<T: Comparable<T>> { public val start: T public val endInclusive: T public fun isEmpty(): Boolean = start > endInclusive public operator fun contains(value: T): Boolean = value >= start && value <= endInclusive } As you can see the type it ranges over (`T`) must implement `Comparable<T>`. This allows the implementation to do a straight comparison of the `value` and the `start` and `endInclusive` of the range. You can see this in the implementation of `contains(value: T)`.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "kotlin, range, conditional statements, long integer" }
Как в git удалить папки только из удалённого репозитория? Я добавил проект в удалённый репозиторий, потом написал в .gitignore игнорировать папку `.vs/` Но на сервере эта папка присутствует. Как мне обновить данные с учётом .gitignore?
1. Удалить папку из `.gitignore` 2. Удалить/переместить за пределы репозитория папку `.vs` 3. Закоммитить и запушить удаление этой папки 4. Добавить её обратно в `.gitignore` 5. Переместить папку обратно на свое место/запустить Visual Studio, чтобы её создало заново
stackexchange-ru_stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "git" }
How is the divinity of Jesus defended in light of Philippians 2:9 ("God exalted him") and Matthew 28:18? > **Philippians 2:9** > Therefore God exalted him to the highest place and gave him the name that is above every name > > **Matthew 28:18** > Then Jesus came to them and said, "All authority in heaven and on earth has been given to me." In the first of the verses mentioned above, Scripture talks about God exalted Jesus, and the second verse talks about Jesus gaining all authority on heaven and on Earth. If Jesus is God, why would he need to be exalted and given authority, especially considering that exaltation and authority are qualities already possessed by God?
Paul says of the Son of God, that 'being in the form of God, he thought it not robbery to be equal with God'[Philippians 2:6 KJV] . He is equal to God, in his eternal Being. The two texts you mention regard the Son of God being exalted _in humanity_. That is, after incarnation and after his sufferings and death, God exalted Jesus Christ to his own right hand - in humanity. The first humanity failed. For all have sinned and come short of the glory of God, Romans 3:23. But Jesus Christ, in humanity, did - always - the will of the Father, John 8:29. Thus has God exalted him, in humanity, to his own throne, Revelation 3:21.
stackexchange-christianity
{ "answer_score": 2, "question_score": 9, "tags": "exegesis, nature of god, christology, gospel of matthew, philippians" }
Find by ID in KnockOutJS Given the following, how do I get id 10 back out? function ChildListViewModel() { var self = this; self.children = ko.observableArray([]); self.children.push({id:20,name:"Jake"}); self.children.push({id:10,name:"Jake"}); self.find = function(id) { console.log(self.children().length); setTimeout(function(){console.log(self.children().length);}, 500); found = ko.utils.arrayFirst(self.children(), function(child) { return child.id() === id; }); console.log(found); return found; } } I want to do something like ChildVM.find(10); All attempts using `ko.utils.arrayFirst` and `ko.utils.arrayForEach` have failed me. **EDIT** This now works, see selected answers. Issues around loading order and AJAX meant this was not working as it should do.
return ko.utils.arrayFirst(self.children(), function(child) { return child.id === id; }); Just remember to use `self.children()` to get to the underlying array.
stackexchange-stackoverflow
{ "answer_score": 13, "question_score": 5, "tags": "knockout.js" }
Error in the test before installing Fedora to Mac (next to OSX) I'm trying to install Fedora 29 next to OSX on my macbook air. I downloaded the image and verified the checksum. Then I formatted usb to OSX Extended Journaled file system, and created bootable usb using diskutil unmountDisk /dev/disk2s2 sudo dd bs=1m if=./Fedora-Workstation-Live-x86_64-29-1.2.iso of=/dev/rdisk2 However, when I start my mac from the USB with the option testing & installing Fedora, I get the following error ![enter image description here]( This is not the first time that I'm installing Fedora to my mac, but I was getting the same error before, but still the media allows me to install it if I directly try to install it without testing it, so what is wrong ? why am I getting this error ? **Edit:** As I've stated, the checksum is OK grep '^SHA256' *-CHECKSUM | awk -F '[()=]' '{ print $4 " " $2 }' | shasum -a 256 -c Fedora-Workstation-Live-x86_64-29-1.2.iso: OK
This solved my problem; > You are encountering this bug because of the way OSX handles USB devices. You run the dd command, which wipes the drive and does all it's fun stuff. Now, what Fedora is looking for is the drive to just be as is once it finishes writing it. Unfortunately, OSX finishes the dd command and then immediately automounts the drive. This, of course, triggers a whole bunch of system indexing tools, writing countless amounts of hidden .whatever files. This, in turn, changes the drive as the dd command saw it. Therefore, the data sum that the Fedora media checker is expecting is not the same, as the drive's contents have been changed. > > Truthfully, you are safe to just go to town without verifying the drive. Either that, or install Disk Arbitrator to block drive automounting and then run dd again....will work without a hitch. Taken from here: <
stackexchange-superuser
{ "answer_score": 1, "question_score": 2, "tags": "linux, mac, usb, installation, fedora" }
What does 'HN' mean in HN50? What does the 'HN' stand for in 'HN50'? HN50 is a type of linear polarizer which reduces the power of the input by 50%
There are a few different types of polarizer materials. The wikipedia page on Polaroid) sheets names a few, but the most common is the "H" sheet. The "H" designation comes from that. The "N" indicates neutral color extinction. You can find "HR" sheets which block higher frequencies (R for red) and can be used for IR work. The number is the percentage of unpolarized light to pass through the filter.
stackexchange-physics
{ "answer_score": 3, "question_score": 0, "tags": "optics, terminology, notation, polarization" }
What would make working with DBAs easier? Inspired by a similar question specifically about developers, I would like to know how system administrators work with Database Administrators better. In my 10 years experience as a system administrator, I've worked with a variety of DBAs. I've seen a lot of conflict on both sides, most often due to disagreements about who owns what, especially regarding security. So the question is: How do you come to compromise when disagreeing with DBAs?
Be ready to explain WHY you do something and listen to WHY they do something. It really helps is both parties can back up a few steps and concentrate less on how they currently (or expect to) do something and focus on what the overall purpose is. If the DBA is focusing on getting program X to talk to the database when the sysadmin doesn't allow program x to run on "his" network no one is going to leave the room happy. If on the other hand the DBA needs to accomplish something that can be done with program X, but the sysadmin knows of a security flaw in program X. The DBA can discuss what he's trying to accomplish. The sysadmin can share the information about the security issue. Together they can look for a better way to accomplish the goal (or find a fix to the security issue). When it's over, the job will be done and both parties have learned something.
stackexchange-serverfault
{ "answer_score": 5, "question_score": 3, "tags": "untagged" }
Node.js Express.js | Automatically render handelbar templates from views/static folder I have got the following code to automatically load my handelbar templates from the views/static folder without having to manually setup a route for each page. app.get("/:template", function(req,res){ var template = req.params.template; // Is this safe? res.render("static/" + template, function(err, html) { if (err) { res.send(404, 'Sorry cant find that!'); } else { res.send(html); } }); }); It works fine, however I am worried that this potentially exposes my app to security problems. Any suggestions how I could do this better. I am using Express. Thanks so much for your help.
I think it's pretty safe. Usually, you have to worry about paths being passed that contain stuff like `../` (to go back a directory level), but those won't match your route. Also, the route you declare will stop matching at a `/`, so requests like `/foo/../bar` won't match either. An issue that _may_ occur is when the `static` directory contains files that you don't want to expose: a request for `/secret.js` will at least _try_ to render a file called `static/secret.js`.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "javascript, node.js, express, routes" }
When an SSD finally reach its end of life, can you still read its data? For "end of life" I mean when some of the SSD cells won't erase anymore, and the S.O. starts complaining about write failures. When this finally happens, will I still be able to safely copy all of the data without any errors? And if I don't replace it soon, will it ever stop working? (for reads only)
Firstly, it's a bit of a myth that SSDs will wear out, especially for typical desktop use. But anyway: From another superuser question: > In theory, it is possible to read data even after all program/erase (p/e) cycles have been used up. In fact, the JEDEC specifies that data on consumer-grade SSDs should be readable for one year after all p/e cycles have been exhausted. So the likelihood of losing data due to the drive reaching the end of its lifetime is small; it's more likely that you'll have replaced or upgraded your system by then. And here: > Second, when an SSD is allowed to run right to the end of its useful life, most controllers put the SSD into a **“Read-Only” state** that allows the operator to remove the SSD, copy its contents onto another device, then re-start operations in the shortest amount of time. So you can't write on it, but you will be able to copy its contents to your next SSD/HDD(for a reasonable amount of time).
stackexchange-superuser
{ "answer_score": 5, "question_score": 3, "tags": "ssd, data recovery" }
rapid miner: how to add a 'label' attribute to a dataset? I want to apply a decision tree learning algorithm to a dataset I have imported from a CSV. The problem is that the "tra" input of the Decision Tree block is still red, stating "Input example set must have special attribute 'label'.". How do I add that label? What is it? I have been playing around with it for some time without results. Any help appreciated. ADDENDUM: the column's titles have been correctly inferred, so I have no clue on what the 'label' is.
Label is the attribute that represents the target class for classification. "Set Role" operator can set an attribute as label, but you can do that when importing the data - most import operators can be configured to set the role of attributes. "Read CSV" is one of them.
stackexchange-stackoverflow
{ "answer_score": 12, "question_score": 8, "tags": "machine learning, data mining, decision tree, rapidminer" }
Get column names with distinct value greater than specified values python **Dataframe X:** A B C D V1 V2 V3 V4 V1 V3 V4 V5 V1 V4 V5 V5 V1 V5 V9 V5 V1 V2 V3 V4 V1 V10 V11 V12 V1 V10 V6 V8 V1 V12 V7 V8 Here Col A has 1 unique value, Col B has 6 unique values, Col C has 7 unique values, Col D has 4 unique values. **I need a list of all columns where unique values > 4 say.** X.columns[(X.nunique() > 4).any()] I expect to get only col B and Col C here, but I get all columns. How to achieve desired output.
You are really close, only remove `.any` for boolean mask: c = X.columns[(X.nunique() > 4)] print (c) Index(['B', 'C'], dtype='object') If need select columns use `DataFrame.loc`: df = X.loc[:, (X.nunique() > 4)] print (df) B C 0 V2 V3 1 V3 V4 2 V4 V5 3 V5 V9 4 V2 V3 5 V10 V11 6 V10 V6 7 V12 V7
stackexchange-stackoverflow
{ "answer_score": 7, "question_score": 6, "tags": "python, pandas" }
For some given $3\times3$ matrix $A^{-1}$ and $3\times2$ matrix $B$, solve $AC=B$ for $C$ > Let $A^{-1}$ = $\begin{pmatrix} 1 &2 &1 \\\ 0 & 3 & 1\\\ 4 & 1 & 2 \end{pmatrix}$. Find matrix $C$ such that $AC = \begin{pmatrix} 1 &2\\\ 0 & 1\\\ 4 & 1 \end{pmatrix}$. How do I do this problem? The only thing I could think of doing finding $A$, which is $(A^{-1})^{-1}$ $A = \begin{pmatrix} 5 &-3 &-1 \\\ 4 & -2&-1 \\\ -12 & 7& 3 \end{pmatrix}$ I know $C = 3 \times 2$, since $AC = 3 \times 2$. So, \begin{pmatrix} 5 &-3 &-1 \\\ 4 & -2&-1 \\\ -12 & 7& 3 \end{pmatrix} times \begin{pmatrix} a& b\\\ c & d\\\ e & f \end{pmatrix} is $AC$. How do I proceed from here? This seems very long. Is there an easier way?
$A^{-1} = \begin{pmatrix} 5 &-3 &-1 \\\ 4 & -2&-1 \\\ -12 & 7& 3 \end{pmatrix}$ Now $$AC= \begin{pmatrix} 1 &2\\\ 0 & 1\\\ 4 & 1 \end{pmatrix}\implies C=A^{-1} \begin{pmatrix} 1 &2\\\ 0 & 1\\\ 4 & 1 \end{pmatrix} =\begin{pmatrix} 5 &5\\\ 4 & 4\\\ 12 & 11 \end{pmatrix}$$
stackexchange-math
{ "answer_score": 0, "question_score": 0, "tags": "linear algebra, matrices, matrix equations" }
librosa does not normalize wave file between [-1, 1] In passing a file via the use: librosa_audio, librosa_sample_rate = librosa.load(filename) The output produces an audio file such that: `Librosa audio file min~max range: -1.2105224 to 1.2942806` The file that I am working on was obtained from < and had a bit depth of 24. I down sampled to 16 and also up sampled to 32 to work with librosa. Both of these files produced the same min-max range after going through librosa. Why does this happen? Is there a way to parse the wav file to Librosa such that the data will fall between [-1,1]? Here is a link to the files: <
The behaviour you are observing stems directly from resampling to `22050 Hz` that librosa load does by default: librosa.core.load(path, sr=22050) Resampling process always affects the audio, hence you see values that are not normalized. You have to do this yourself. More likely, you wanted to read the audio with the native sampling rate, in which case you should have passed `None` to `sr` like this: librosa.core.load(path, sr=None) Example based on the audio sample you have provided: In [4]: y, sr = librosa.load('201-AWCKARAK47Close0116BIT.wav', sr=None) In [5]: y.max() Out[5]: 0.9773865 In [6]: y.min() Out[6]: -0.8358917
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 3, "tags": "python, audio, wav, librosa" }
how to create month->day upload path directories when processing upload submit what is the simple way to create folders and sub-folders as upload path? based on witch day it is example: -files -2012 //year -01 //month +01 //day +02 +03 . . . +29 +30 +02 //month +03 +04 +05 +06 +07 +2013 . . . is there any class or function to do this making directories?
You can use `mkdir()`. It has an option to create folders recursively. Then just build a path using your desired date, and be sure to add `true` to the function. Meaning something like : mkdir("/2012/5/25", 0755, true); To build your date path you need to use the PHP method `date()`, for further reading and examples read the documentation.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "php, directory" }
In Java8 functional style, how can i map the values to already existing key value pair I have a map: Map<String, List<Object>> dataMap; Now i want to add new key value pairs to the map like below: if(dataMap.contains(key)) { List<Object> list = dataMap.get(key); list.add(someNewObject); dataMap.put(key, list); } else { List<Object> list = new ArrayList(); list.add(someNewObject) dataMap.put(key, list); } How can i do this with Java8 functional style?
You can use `computeIfAbsent`. If the mapping is not present, just create one by associating the key with a new empty list, and then add the value into it. dataMap.computeIfAbsent(key, k -> new ArrayList<>()).add(someNewObject); As the documentation states, it returns the current (existing or computed) value associated with the specified key so you can chain the call with `ArrayList#add`. Of course this assume that the values in the original map are not fixed-size lists (I don't know how you filled it)... By the way, if you have access to the original data source, I would grab the stream from it and use `Collectors.groupingBy` directly.
stackexchange-stackoverflow
{ "answer_score": 32, "question_score": 21, "tags": "java, dictionary, java 8" }
How to move a StreamBlock between apps I'm refactoring some code and I wish to move a custom StreamBlock (or StructBlock) from one django app to another. This seems like it would be **much** simpler than migrating tables between apps. 1. Move the block declarations to the new app 2. Update any dependencies to point to new module 3. Update old migration files (imports, etc) to point to new app 4. ... PROFIT Is this really all we need to do? Are there any deployment risks, here - or is this really a **pure python** change.
Assuming the block declaration itself doesn't change, and all StreamFields referencing it are updated to point to it in its new location - yes, it's a pure Python change. You don't even need to update migrations, because migrations are set up to include their own frozen copy of `StreamBlock` / `StructBlock` definitions as they existed at the time of creation, rather than pointing to the definition within your app code.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 2, "tags": "wagtail, wagtail streamfield" }
How do I configure two IP addresses on a specific vlan I'm not sure about the syntax here: what comes first in `/etc/network/interfaces` interface names, VLAN or alias? What I want is to setup two different subnets on the same VLAN (temporarily). It will look something like below, where there's a 10.20.100.100/24 and 10.20.200.200/24 on the same VLAN (id 33): iface eth0:1.33 inet static address 10.20.100.100 netmask 255.255.255.0 iface eth0:2.33 inet static address 10.20.200.200 netmask 255.255.255.0 I expected the Debian Wiki to answer this but it did not: <
I don't know when and what changed, but you can now define virtual interfaces on vlans: auto eth0.10 iface eth0.10 inet static address 192.168.1.61 netmask 255.255.255.0 gateway 192.168.1.11 auto eth0.10:1 iface eth0.10:1 inet static address 10.20.100.100 netmask 255.255.255.0 auto eth0.10:2 iface eth0.10:2 inet static address 10.20.100.200 netmask 255.255.255.0 Think of vlan interfaces as physical interfaces. You add virtual interfaces to the "physical" interface.
stackexchange-askubuntu
{ "answer_score": 4, "question_score": 4, "tags": "networking" }
How can I convert a JavaScript for-loop to CoffeeScript? for (i = 0; i < 10; i++) { doStuff(); } That's the JavaScript code that I Want to convert to CoffeeScript.
doStuff() for i in [0 .. 9] This is explained on the introduction page: < **Edit/Update by JP:** The exact translation is: doStuff() for i in [0...10] You need to be careful with the ".." vs "...", for example: count = 0 doStuff() for i in [0..count] #still executes once! So you think, no problem... I'll just loop until count-1! count = 0 doStuff() for i in [0..count-1] #executes twice!! '0' and then '-1' Literal translation of: for (var i = 0; i < someCount; ++i) doStuff() is for i in [0...someCount] doStuff()
stackexchange-stackoverflow
{ "answer_score": 115, "question_score": 73, "tags": "for loop, coffeescript" }
Accessing private members Is it appropriate to access a class' private members by casting it to a void pointer and then to a struct? I don't think I have permissions to modify the class that contains the data members that I need to access. I don't want to take a risk accessing the data members in an indirect way if it is not ethical. EDIT: Had to edit this further... I am pretty sure the class wouldn't be modified, so it's ok to that extent... my only concern is, if the person who coded that class gets to know of this, it might not go down well with him :(.
"Never say never". I'm sure somewhere in the universe, there's a situation that will force you to have to do this... But I certainly would cringe if I had to do it. You truly need get lots of opinions on your situation before pulling the trigger. Can you describe your specific situation and maybe we could see if it makes sense or what better alternatives might exist? In response to comment/question-- Define "permissions" -- institutional permission? That sounds like not a programming problem, but something to talk to whoever is asserting said permission. Maybe this is more of a political issue than a technical one? Again, I think we need more specifics--even if it was somewhat about the politics of the situation. That may or may not be deemed out of scope for the website, however.
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 9, "tags": "c++, private members" }
How could duplicate rows be created with the schema In Rail, I have this schema (for a join table between car and user habtm) create_table "cars_users", :id => false, :force => true do |t| t.integer "user_id" t.integer "car_id" end add_index "cars_users", ["car_id", "user_id"], :name => "index_cars_users_on_car_id_and_user_id" add_index "cars_users", ["user_id", "car_id"], :name => "index_cars_users_on_user_id_and_car_id" but due to some bug, I have duplicate rows in this table. shouldn't the `index` handle that?
Try: add_index :cars_users, [ :user_id, :car_id ], :unique => true, :name => 'by_user_and_car' it will raise an exception but you can add your own validation class User < ActiveRecord::Base has_and_belongs_to_many :cars, :before_add => :validates_car def validates_car(car) errors.add(:car, "already created" ) if self.cars.include? car end end
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "ruby on rails 3, indexing, schema, duplicates" }
List difference in scheme. Who can help me with a code that returns the difference the difference in two different lists i.e the set in A and not in B. like (set-difference '(1 2 4 5 6) '(4 5 6 2 8) is 1. This is was an in-class lab assessment and I wanted to know it would had been done. I know it deals with the aspect of linear time, but I don't really know how to implement that in scheme.
Try this: (define (set-difference s1 s2) (cond ((null? s1) '()) ((not (member (car s1) s2)) (cons (car s1) (set-difference (cdr s1) s2))) (else (set-difference (cdr s1) s2))))
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "scheme" }
how can i find the files imported in a java class? I don't get to see the source code but the .class file. Can I still find out the files that are imported?
Keep in mind that imports are simply a convenience mechanism that lets the Java developer refer to a class using it's simple name (`Date`) rather than it's Fully Qualified Name (FQN - `java.util.Date` or `java.sql.Date`). So if you run the `.class` file through a decompiler, you'll likely see references using the FQN and possibly no import statements.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 0, "tags": "java" }
How to replace a number of random characters with sql in a string? My code is (not working): update wp_posts set post_excerpt = replace(post_excerpt, ' ''); Where the **************** is 16 random letters (big and small). I'd like to remove it from everywhere. Thank you very much! Edit: I found a nice app that can do this: < :) Thanks for the help!
Something like this ought to do it, just replace @strg with whatever you are referencing the string by (column/variable name). '<img src=" + (RIGHT(@strg,LEN(@strg)-(CHARINDEX('url=http',@strg)+10))) + '>'
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -1, "tags": "mysql, sql, phpmyadmin" }
Two LEDs connected in series don't work I'm _**very**_ new to electrical engineering and I ran into a strange issue while trying to connect two LEDs in series today. Both my blue and white LEDs work separately, but when I try to connect them together, they do not work (see pictures). Is there something I'm doing wrong? (I did try changing the orientation of the LEDs to make sure my cathodes and anodes are connected to where they're supposed to be) ![Two LEDs in series not working]( ![White LED working]( ![Blue LED working](
The LEDs both need about 3V to work, so together in series they need about 6V to work, but the IO pin only gives out 3.3V. So there is no way the LEDs could work in series. Also do not connect LEDs to IO pins without series resistors to limit the current, current might be too high and the MCU or LED could be damaged permanently.
stackexchange-electronics
{ "answer_score": 39, "question_score": 8, "tags": "led, stm32, series" }
How does a thermal temperature gun work? I once worked as a kitchen porter over a winter season. We had fun with thermal temperature guns (like these) which I learned can be used for measuring the temperature of something a reasonable distance away (aside from the obvious use of laser tag), which to my mind is pretty impressive. How do they work?
They basically measure the intensity of the infrared blackbody radiation in some wavelength region and calculate the temperature needed to give that intensity according to Planck's law.
stackexchange-physics
{ "answer_score": 2, "question_score": 1, "tags": "thermodynamics" }
Is there a javascript lib to design an IVR diagram with JSON output i need a javascript plugin can design an dynamic IVR diagram and in output can get object for pass to server side. i found mxgraph but not for IVR.
Here is a sample IVR app: < Call `diagram.model.toJson()` to save it as JSON-formatted text.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -1, "tags": "javascript, diagram, ivr" }
Which world-renowned fictional hero was the first to wear a skintight costume and a mask with no visible pupils? It had to start somewhere. Which world-renowned fictional hero is credited as being the first to wear a skintight costume and a mask with no visible pupils?
It appears that the first hero to fit your description would be The Phantom who first appeared in newspaper strips on February 17, 1936. !Phantom 2-24-36 We have both the skintight costume and the mask with no visible pupils. The Phantom has been published in comic book form in the United States, Sweden Finland, Norway, England, Mexico, Israel, Spain, Poland, Russia, Denmark, Hungary, Germany, Turkey, New Zealand, Australia, Turkey, Iceland, South America, France, Thailand, Singapore, Netherlands, Chile, Greece, Yugoslavia, Fiji, Venezuela, and Italy so I think that gives him the world renown status you were also looking for. There is a really good story about the origin of the character at Comicology.
stackexchange-scifi
{ "answer_score": 21, "question_score": 15, "tags": "history of, character identification, costume" }
Not able to set list item activated in Master/Detail Fragment ICS 4.0 I am trying to develop application with Master/ Detail (Fragment) layout but I am facing a weird issue that is when i added my own listview adapter then the activation of the listview items on click/select stopped working. The code provided in default with dummy data was setListAdapter(new ArrayAdapter<DummyContent.DummyItem>( getActivity(), android.R.layout.simple_list_item_activated_1, android.R.id.text1, DummyContent.ITEMS)); the code that I replaced is CMyListAdapter adapter = new CMyListAdapter(getActivity(), CMyContent.getSampleMyContentList()); setListAdapter(adapter); Now, when i click the the listview item, it highlights and doesn't remain persistent.
If you are using a custom layout make sure you are settings the right background drawable: android:background="?android:attr/activatedBackgroundIndicator" In case you want to customize indicator's style you have to define your own `StateListDrawable` xml: <?xml version="1.0" encoding="utf-8"?> <selector xmlns:android=" android:exitFadeDuration="@android:integer/config_mediumAnimTime"> <item android:drawable="@color/red" android:state_pressed="true"/> <item android:drawable="@color/blue" android:state_selected="true"/> <item android:drawable="@color/green" android:state_activated="true"/> </selector> and assign it as your row layout background.
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 0, "tags": "android, android layout, android fragments, android listfragment" }
Complex number vector prove Prove that, where $z$ denotes complex numbers: a.) $|z_1 - z_2| \le |z_1| +|z_2|$ b.) $||z_1| - |z_2|| \le |z_1 +z_2|$ For a. the book answer gives: $|z_1 -z_2| = |z_1 + (-z_2)| \le |z_1| +|-z_2| =|z_1| +|z_2|$, but that proof isn't helpful at all, to me, because it doesn't explain anything. How can I prove this using a clear explaination instead of the way the book did?
Using Mejrdad's hint, for example: $$z_k:=x_k+y_ki\,\,\,,\,,k=1,2\,\,,\,x_k,y_k\in\Bbb R\Longrightarrow$$ $$ \begin{align*}(1)&\;\;\;\;\;\;|z_1-z_2|=|(x_1-x_2)+(y_1-y_2)i|=\sqrt{(x_1-x_2)^2+(y_1-y_2)^2}\\\ (2)&\;\;\;\;\;\;|z_1|+|z_2|=\sqrt{x_1^2+y_1^2}+\sqrt{x_2^2+y_2^2}\end{align*}$$ So squaring both equations above: $$x_1^2+y_1^2+x_2^2+y_2^2-2(x_1x_2+y_1y_2)\leq x_1^2+y_1^2+x_2^2+y_2^2+2\sqrt{(x_1^2+y_1^2)(x_2^2+y_2^2)}\Longleftrightarrow$$ $$-x_1x_2-y_1y_2\leq\sqrt{(x_1^2+y_1^2)(x_2^2+y_2^2)}\stackrel{\text{squaring}}\Longleftrightarrow$$ $$ x_1^2x_2^2+y_1^2y_2^2+2x_1x_2y_1y_2\leq x_1^2x_2^2+y_1^2y_2^2+x_1^2y_2^2+x_2^2y_1^2\Longleftrightarrow$$ $$(x_1y_2-x_2y_1)^2\geq 0$$ And since the last inequality is trivial we get what we want going backwards( Why is it possible to argue that way?)
stackexchange-math
{ "answer_score": 2, "question_score": 1, "tags": "complex numbers" }
Typescript Error Object is of type 'unknown' New to Typescript and can't figure this error I am getting. I am using final form and pushing items into an array. I can console.log the values and see the array and the items in the array. But when I pass this to my child component I keep getting the error: `Object is of type 'unknown` Parent Component <Form onSubmit={onFormSubmit} initialValues={{ items: [{ item: '' }, { item: '' }]}} mutators={{ ...arrayMutators }} > <List values={values} /> //no TS error Child Component //List.tsx <Button disabled={values.items.length === 10}>Add item</Button> //TS error for values.items (Object is of type 'unknown') Type Declaration: values: Record<string, unknown>;
if `values` types are `unknown`, you can't use `items.length` at the `List` component, because `items` is `undefined` under the hood.
stackexchange-stackoverflow
{ "answer_score": -1, "question_score": 3, "tags": "reactjs, typescript, react final form" }
Where can I find a good comparison of available custom ROMs? I'm looking for a good comparison of custom ROMs' features and quality. I would prefer a comparison that is actively maintained.
The Android Release Matrix at AndroidSpin is pretty comprehensive. There is also the PDAdb.net Rom Respository, although I don't think it's as user friendsly as the AndroidSpin db. Last (and least relevant to your question) is theunlockr's list of Android Roms (I just thought it was worth mentioning).
stackexchange-android
{ "answer_score": 6, "question_score": 12, "tags": "custom roms" }
How can I stop these buttons overlapping? I've only know the very basics of HTML and CSS for the last 3 days, so I'm sure that this is a very basic question (which will likely require a simple answer). I've tried making a website about mathematics as a revision exercise (www.mathematicool.net). On a full width browser, the buttons on the homepage look okay. However, as the browser becomes narrower, and the buttons become spread over multiple rows, they seem to overlap in the vertical direction. In the CSS for this page, I've tried adding `padding-top` and `padding-bottom` to the `.button` class, but this just stretches the buttons, rather than spreading them out. I've also tried using `margin-top` and `margin-bottom`, but neither of these seem to do anything. What do I need to do?
Additionally, you can use media queries to add CSS specific to the current size of the browser window that the page is in. ` I looked into your website `www.mathematicool.net`. And this should work nicely: @media (max-width: 700px) { .button { display: block; margin: 5px; } } Makes it look like: ![mathematicool example](
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 2, "tags": "html, css, css position" }
Find the probability density of $N$, the customer of customers arriving at $T$, the service time of a specific customer. The number of clients arriving at a service at time $t$ is distributed Poisson with mean $\beta t$. The service time $T$ is distributed exponentially with parameter $\alpha$, that is, $E[T] =\frac{1}{\alpha}$ Find the probability density of $N$, the customer of customers arriving at $T$, the service time of a specific customer. My try: We know that $$f_N(n)= \int_{0}^{\infty} f(n\mid t)\cdot f_T(t)\,dt$$ $$= \int_{0}^{\infty} \alpha e^{-\alpha t}\frac{e^{-\beta t}(\beta t)^n}{n!}dt$$ I´m stuck with the algebra here. I know that I must add constants to the integral so we can form a "nucleus" of a know probability density. Any suggestions would be great!
Rewriting your integral (I did a little edit because it is $e^{-\beta t}$) you get $$\frac{\alpha \beta^n}{n!(\alpha+\beta)^{n+1}}\int_0^{+\infty}[(\alpha+\beta)t]^ne^{-(\alpha+\beta)t}d[(\alpha+\beta)t]=\frac{\alpha \beta^n}{n!(\alpha+\beta)^{n+1}}n!=\frac{\alpha \beta^n}{(\alpha+\beta)^{n+1}}$$ this because now the integral is in the form $$\int_0^{+\infty}x^{\alpha}e^{-x}dx=\Gamma(\alpha+1)=\alpha!$$ Concluding: the requested density is $$f_N(n)=\frac{\alpha \beta^n}{(\alpha+\beta)^{n+1}}$$ $n=0,1,2,...$
stackexchange-math
{ "answer_score": 1, "question_score": 0, "tags": "probability, probability distributions, conditional probability, density function" }
Получить строку между определенными символами Есть, к примеру, некая строка, например `my::name::space` из которой мне нужно получить три строки разделенные `::`. Как это сделать с помощью регулярных выражений в `c++`? Подобрал такую конструкцию как: (?<=::)(.+)(?=::) Но сдесь сразу несколько проблем: 1) При запуске вылетает `core dump` из-за `?<=`. Так если заменяю на `?=` то все работает (хотя и не верно, выводит первые `::`). 2) Такая конструкция не выведет первую и последнюю строку. Как добавить условие на начало/завершение строки (вроде `?=::|$` \- только это не работает)
Можно попробовать так (?:::)(\w+)(?:::)|^(\w+)|(\w+)$ 1. либо слово, окружённое `::` (при этом :: в незахватывающих группах) 2. либо слово с начала 3. либо слово с конца
stackexchange-ru_stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "c++, регулярные выражения" }
missing return in a function expected to return 'Double' | What to do? Following code: protocol ExampleProtocol { var simpleDescription: String { get } var absoluteValue: Double { get } mutating func adjust() } extension Double: ExampleProtocol { var simpleDescription: String { return "The number \(self)" } var absoluteValue: Double { if self < 0 { return self * -1 } else if self > 0 { return self } } mutating func adjust() { self += 42 } } When trying to execute it with either simpleDescription or absoluteValue (e.g. print(10.simpleDescription), I just get this error: > missing return in a function expected to return 'Double' The absoluteValue "function" returns itself, so the Double value, so why is it saying it's missing one?
The issue is that your `if` statement is missing an `else` block, the return value is not defined for the case when `self == 0`. You can simply change the `else if` branch to `else`, because you also want to return `self` for `0`. var absoluteValue: Double { if self < 0 { return self * -1 } else { return self } } You can also write this as a oneliner using the ternary operator: var absoluteValue: Double { return self < 0 ? self * -1 : self }
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "swift, return" }
How to convert from left-handed coordinate system to right-handed? I need to convert coordinates and rotations from left-handed coordinate system (used by Unity) to right-handed (used by camera calib. toolbox in MATLAB\Octave) ![enter image description here]( ![enter image description here]( While converting point coordinates may be easy, I cannot say the same for rotations. I need rotations in form of 3x3 rotation matrices, not quaternions. For each object I have $ t_{left} = \begin{bmatrix} x \\\ y \\\ z \end{bmatrix} $ and $ R_{left} = \begin{bmatrix} r11 & r12 & r13 \\\ r21 & r22 & r23 \\\ r31 & r32 & r33 \end{bmatrix} $ defined in coordinate frame from the left image. Which transformation should I apply to get $ t_{right} $ and $ R_{right} $ in the right coordinate frame?
Finally I managed to solve this by saving all data in Euler angles in Unity and converting it to Matlab/Octave coordinate system. $R_X = rotX(-a_x);$ $R_Y = rotY(-a_y);$ $R_Z = rotZ(-a_z);$ $R = R_Z*R_X*R_Y;$ $coords = [x; z; y];$ The code is here: < You will need Camera Calibration Toolbox by Jean-Yves Bouguet to get it working. Thanks to everyone for help!
stackexchange-math
{ "answer_score": 0, "question_score": 0, "tags": "euclidean geometry, coordinate systems, transformation" }
How many one-to-one functions are there from a set of $4$ elements to a set of $8$ elements? Problem: Suppose that we have two finite sets $A$ and $B$ such that $A$ has $4$ elements in in and $B$ has $8$ elements in it. How many one-to-one functions are there between $A$ and $B$? Answer: Let $c$ be the count we seek. The first element of $A$ can be mapped to one of $8$ places. The second element of $A$ can be mapped to one of $7$ places, etc. Hence we have: $$ c = 8(7)(6)(5) $$ $$ c = 1680 $$ Is my solution right?
Correct. More generally, the number of injective functions from $A$ to $B$ where $|B|=m\geq n=|A|$ is $$m(m-1)...(m-n+1)=\frac{m!}{(m-n)!}$$
stackexchange-math
{ "answer_score": 2, "question_score": 0, "tags": "combinatorics, solution verification" }
push big view style Quisiera que los mensajes push tengan varias lineas pero no consigo que salga este es el codigo que uso. NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this) .setSmallIcon(R.mipmap.ic_launcher) .setContentTitle(messageBody) .setAutoCancel(true) .setSound(defaultSoundUri) .setStyle(new NotificationCompat.BigTextStyle().bigText(messageBody));
creo que hay un mal entendido, estas creando una notificación **BigTextStyle** por lo tanto tu notificación, se muestra en multilineas. Cuando la recibes se debe mostrar de esta forma, el titulo y una linea de la descripción: ![introducir la descripción de la imagen aquí]( y cuando la expandes ya puedes ver la información en varias lineas: ![introducir la descripción de la imagen aquí]( Lo mismo sucede con la notificación **BigPictureStyle**, se muestra el título y una sola línea: ![introducir la descripción de la imagen aquí]( Al expandirla puedes ver el detalle y completamente la foto: ![introducir la descripción de la imagen aquí](
stackexchange-es_stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "android, android studio" }
ESXi configuration I just bought a dedicated server on online.net I have a public and a private ip. I installed esxi from their panel and I can connect successfully with my vsphere client. The problem is this: I want to create some instances and I want to give them different private ips. I also want to create some NAT rules to forward all users coming to my public ip port 80 to a specific instance. How can I do that? Thanks
VMware ESXi is not a firewall or a router. Either ask your provider if they can give you a firewall/NAT service with the ESXi host behind it, or do the work yourself. In basic terms: ESXi must have a dedicated IP address for management features. If your only choice is to expose the ESXi management directly to the internet then you'll need a second IP address. Once you have the second IP address you can create a new port group with a different VLAN. This will be your internal network. Set up a new VM with two network cards, one internet-facing and one facing to the internal network. Install whatever OS you want as a firewall/router, and go from there.
stackexchange-serverfault
{ "answer_score": 3, "question_score": 0, "tags": "vmware esxi, vmware vsphere" }
Mongodb atomic schema-planning My program has users and groups. Use-case: Users have credits they can give to the groups. I want no credits to be lost. The problem with RDBMS-like schema is the atomicity of Mongo is document-level. I reduce the credits of the user and then increase the credits of the group. If the application crashes between the two the credits, that are sent, become lost. (If I replace the two actions credits can appear without being withdrawn from the user.) One solution could be using of a collection called transactions. Then the credits of the user can be calculated from the send credits of the user subtracted from the credits of the user. The credits of the group can be calculated as the sum of the sent credits. The problem is if the database grows the sum will take a while. Can you give me any acceptable, scalable and robust solution for this with NoSQL? (I know it is really easy in RDBMS)
**Two phase commits in MongoDB** You can perform multi-document updates or multi-document transactions using a two phase commit approach. > Using two-phase commit ensures that data is consistent and, in case of an error, the state that preceded the transaction is recoverable. During the procedure, however, documents can represent pending data and states. For more details about **Two phase commits** you can refer to the docs here > **NOTE** > Because only single-document operations are atomic with MongoDB, two-phase commits can only offer transaction-like semantics. It is possible for applications to return intermediate data at intermediate points during the two-phase commit or rollback.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "database, mongodb, database design, nosql, database normalization" }
Cakephp: Access data in add function I'm using the CakePHP blog example: function add() { if (!empty($this->data)) { if ($this->Post->saveAll($this->data)) { $this->Session->setFlash('Your post has been saved.'); $this->redirect(array('action' => 'index')); } }} I want to modify it in a way that the user is redirected to the post after adding it: But this doesn't work: $this->redirect(array('action' => 'view', $this->Post->id))); What is the correct way to read the model's data after creation?
As metrobalderas says, break up the save. if ($this->Post->save($this->data)) { unset($this->data['Post']; // So that we don't add another $this->Post->saveAll($this->data); $this->redirect(array('action' => 'view', $this->Post->id))); }
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "cakephp" }
Test whether two categorical questions are statistically different? I have two questions (Q1, Q2) and they can be answered with either Yes or No. I want to test if there is a significant difference between the answers to Q1 and Q2, because the questions are related to each other: Q1 Do you current fulfill X tasks? Q2 Are you interested in X tasks? | Current? | Interest? ---|---|--- Yes | 10 | 15 No | 20 | 15 I thought that I could use a Chi-squared test but I am not sure?
Yes, you can arrange the counts for the two categories as you have above and test the hypothesis of independence with Pearson's chi-squared test of independence. In R, as follows: mat <- matrix(data = c(10, 20, 15, 15), nrow = 2) chisq.test(mat, correct = FALSE) This produces a p-value of ~0.19, so there's not sufficient evidence to reject the null hypothesis.
stackexchange-stats
{ "answer_score": 1, "question_score": 1, "tags": "categorical data, chi squared test, contingency tables" }
hyper-v dynamic expanding vs fixed disk In the "old times" it was not recommended to use dynamic expanding disks in hyper-v. This create the issue of using very much disk space on the hyper-v host. (because we need allocate the space for the virtual disks) I cannot find too much information about what is recommended today for windows server 2019. What is recommended in 2021? Fixed disk size or dynamic expanding? Extra information: The virtual server does not handle any big files. Only work with small size files (few kb, but many hundre thousands of them) if there is really no good reason for choosing fixed size, i want to convert all disks to dynamix expanding disks.
The main problems with dynamically expanding disks are fragmentation and overcommitment. Fragmentation is really not an issue anymore with modern storage, especially SSDs which don't care at all where data is physically located; unless you are storing your VHDs on local mechanical disks, this should not be a concern. Overcommitment can still be a problem, though; if a volume gets accidentally filled up and doesn't have enough free space when a dynamic VHD needs to expand, the VHD will get damaged and the associated VM will likely crash, possibly along with other ones stored on the same volume.
stackexchange-serverfault
{ "answer_score": 0, "question_score": 1, "tags": "hyper v, virtual disk, hyper v server 2019" }
Why glucose and other similar carbohydrates are oxidised fully by HIO4? $\ce{HIO4_{(aq)}}$ requires the vicinal diols to have syn configuration, as it forms a cyclic periodate ester. ![enter image description here]( But glucose does not have syn configuration at **C3** , and if you consider cyclic forms of glucose it shouldn't oxidise fully at all because alternate hydroxy groups with **anti configuration** will be unreactive. But it still gets oxidised by $\ce{HIO4}$ to give 5 molecules of methanoic acid, $\ce{HCOOH}$, and one molecule of formaldehyde, $\ce{HCHO}$. ![enter image description here](
Glucose can react with $\ce{HIO4}$, which can be understood easily by looking at chair conformation of glucose. Here is example of a diol, for more information looks at this answer < ![enter image description here](
stackexchange-chemistry
{ "answer_score": 0, "question_score": 2, "tags": "stereochemistry, carbohydrates, organic oxidation" }
Javascript get array by name of a string I'm having a total of 5 arrays. Name of the array will be selected by the user, based on the users selection we need to perform actions. var p1s1 = ['5', '1', '6']; var p1s2 = ['2', '4', '7']; var p1s3 = ['9', '5', '2']; var p1s4 = ['2', '5', '8']; var p1s5 = ['7', '4', '2']; when user selects a dropdown it will have value p1s3. So i need to pick this particular array and perform operations over this. Could anyone please suggest in this regard. Thanks
Use object instead: var obj = { p1s1: ['5', '1', '6'], p1s2: ['2', '4', '7'], p1s3: ['9', '5', '2'], p1s4: ['2', '5', '8'], p1s5: ['7', '4', '2'] } Then access array this way: obj[selected_value_from_dropdown]
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": -1, "tags": "javascript, arrays" }
Is it okay to write funny rejection messages for Community suggested review audits? Has anyone else taken to writing a special custom message for the Suggested Edits by the Community user? > **Why are you rejecting this edit:** > > * Because the Community is testing me! > * I don't wanna be scolded for accepting it. > * I don't trust robot edits. > Is there an issue with leaving small humorous messages? _**IF**_ the post turns out to be a real, bad edit, it's still been rejected, just not for the ideal reason.
Meh. As I said in my comments on Servy's answer, the reason you write doesn't show up on the site **_anywhere_** , so I really see no harm in doing so. I used to write custom rejection reasons... usually asking the Community user questions (how his day was, what he had for tea, plans for the weekend etc.). After several weeks of getting ignored however, I directed my efforts elsewhere, and now just use the "Vandalism" rejection reason.
stackexchange-meta
{ "answer_score": 8, "question_score": 9, "tags": "discussion, community user" }
How to use front camera in Xing QR Code scanner libary on android I wish to know how can I use front camera with Xing library on android to scan 2D Qr code . I mean what what code is required ? Thanks a lot Vishal
In short, You'll have to fork the source and replace all camera related code with code that uses the front camera. If you are asking each and every instance where this needs to be done, then it is beyond the scope of StackOverflow. Here is a thread that tells you how to use a front camera: Android front camera The rest you will have to do yourself and you can always come back if you have more specific problems.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -2, "tags": "java, android" }
Window Navigation using <Window> tag only Is it possible to go to next window or go back to a window using just `<window>` tag. I searched through internet and didn't find it anywhere. Whenever navigation is needed, I found `<Window.Navigation>` is in use. But using but this browser like tab on top I want window to navigate when I click m Ok or cancel button on my `<Window>`. P.S. I am new to WPF. So I don't know much about it.
If NavigationWindow would work for you except for the navigation tab on top, the simplest thing to do is set ShowsNavigationUI=false. Alternatively (a bigger hammer, but more flexible) you can replace the Template on your window and that will also remove it.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "c#, wpf, wpf controls" }
should I save nsuserdefaults to my custom class? I am saving user info into `NSUserDefaults` with key ' **userInfo** ' right now. and when app is launched, I check if 'userInfo' exists and switch the flow. It works very well, but is it a bad habit to directly access to `NSUserDefaults` each time I need user's info ? Is it better to save user info when app is launced to my custom class? If so, can you tell me the reason?
Access NSUserDefaults when you need them. If you save the user data in your class - I assume you mean in memory - you are blocking valuable memory. Depending on the size of your user data that might be an issue. On the other hand NSUserDefaults access is fast and inexpensive.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "objective c, cocoa touch, nsuserdefaults" }
Would a human touching an angel cause an impact? Like the title says, but let me clear up the question a bit. If a human (lilin) comes into contact with any of the 13 angels (adam), would an impact start? From my understanding, it would, as the angels are Adam's children, and humans are Lilith's children. If something like this can happen, then touching an Evangelion born from Adam would cause an impact, right? Is this explained anywhere in the manga, anime or movies? I can't seem to remember anything relating to this topic.
No, nothing would happen. This can be seen with Eva Unit 01’s (a Lilith-based lifeform) fusion with material from the Fourteenth Angel (Adam-based lifeform). Same thing with Kaworu (albeit in a Lilin body, touching Shinji). Same thing with the Adam embryo (albeit missing the soul) on Gendo's hand. It was implied that simple contact doesn’t result in an impact. What happened in the Contact Experiment with Adam, aka the Second Impact, is unclear, along with who the donor of the DNA for Kaworu Lilin body is from (Rei's is Shinji's mother).
stackexchange-anime
{ "answer_score": 4, "question_score": 5, "tags": "neon genesis evangelion" }
How to unlock windows 8/8.1/10 from another PC programmatically? I am trying to setup a client-server application where the server can unlock client PCs from their windows login screen. The server can also logout or lock the clients as well but unlocking the client PCs from the login screen seems to be more difficult. I have read about credential provider but I don't understand yet if credential providers will also allow another PC from sending a signal to another PC (client PC) telling them to unlock. I know C# well but not C++... but I am willing to learn if needed. I would really appreciate your help guys.. Thanks
You can write your own Credential Provider library (C++ only) and control it remotely somehow. Or use LogonExpert remotely (via PsExec or your own means).
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "c#, windows" }
Label not updating in kivy self.create_pass_input = TextInput(text='', multiline=False) self.add_details.add_widget(self.create_pass_input) self.add_details.add_widget(Label(text="Strong password's prevent hacking")) self.password_tracker = Label() if len(self.create_pass_input.text) < 5: self.password_tracker.text = 'Weak' else: self.password_tracker.text = 'Strong' self.add_details.add_widget(self.password_tracker) I am trying to update the Label called 'self.password_tracker' as the text within the textinput called 'self.create_pass_input' changes but get no update if possible could answers be given in python language ![kivy screenshot](
You can modify the section of the code you mentioned like below: def on_text(instance, value): if len(self.create_pass_input.text) < 5: self.password_tracker.text = 'Weak' else: self.password_tracker.text = 'Strong' self.create_pass_input = TextInput(text='', multiline=False) self.create_pass_input.bind(text=on_text) self.add_details.add_widget(self.create_pass_input) self.add_details.add_widget(Label(text="Strong password's prevent hacking")) self.password_tracker = Label() self.add_details.add_widget(self.password_tracker) This will ensure triggering `on_text` method whenever the text of the `TextInput` changes.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "python, kivy, label, textinput" }
CSS position relative button I have a problem about layout , you can see the website menu hide by the button [ i have set the button to position:relative ,if i don't set to position relative that will all right,why? Thanks
Try positioning and set `z-index` for the `#header` It worked on fiddle that you gave... !enter image description here
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -3, "tags": "css" }
select max of date with query I want to select max of date in hibernate but I get this error: > java.sql.SQLSyntaxErrorException: ORA-00932: inconsistent datatypes: expected TIMESTAMP got NUMBER The query is : select coalesce(max (rc.dateTransactionReceipt),0 ) from MAMReceiptTransactions rc where rc.mamItems.id =m.id ) as lastDateOfCharge and the database is oracle. Type of this field in database is TIMESTAMP(6)
Trying to get `0` when timestamp doesn't make sense apart from being syntactically incorrect (The datatypes of the coalesce parameters must be compatible). Null itself sounds reasonable. select max(rc.dateTransaction) from your_table rc If you want to have a default timestamp returned, you can use that in the coalesce instead. Perhaps you want current timestamp returned in case the above returns null. select coalesce(max(rc.dateTransaction), systimestamp) from your_table rc;
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "java, sql, oracle, hibernate, timestamp" }
Translation of "how often" questions What is the most idiomatic translation of "how often" into Spanish in questions like: * How often do the buses stop here? * How often does it rain in November? * How often do you get headaches? * How often do flights get cancelled at this airport? The dictionary translation is _con que frecuencia_ , but is that the only way to translate "how often"? Are questions like this in Spanish usually structured like their English equivalents, or are questions reworded to avoid the sense of "how often"?
> Con qué frecuencia... is just right. Some alternative rewordings: > ¿Cada cuántos minutos pasa el bus? > > ¿Cada cuánto (tiempo) pasa el bus? > > ¿Cómo son de frecuentes tus jaquecas? (or more correct: "¿Qué tan frecuentes son tus jaquecas?") > > ¿Cuál es la frecuencia de lluvias durante noviembre? > > ¿Cuán frecuentemente se cancelan los vuelos...? (slightly ugly)
stackexchange-spanish
{ "answer_score": 8, "question_score": 5, "tags": "traducción, selección de palabras, preguntas, palabras interrogativas" }
Right clicking bookmarks in firefox in osx doesn't work I have a macbook pro 13" that I got just last week and iv noticed that I can't rightclick bookmarks in the bookmarks toolbar or the bookmarks menu. Doing so in the bookmarks organizer works just fine and the same goes for every other app on my system. After googling around this seems to be a common problem (mozilla support post) but I suspect that there is some fix or workaround out there, I just can't find it. How do I solve this? Edit: Just realised that it works for single bookmarks in the toolbar menu but not when bookmarks are in folders.
I don't think this works in Mac OS X for Mozilla based (Gecko/XUL) browsers. See bug 300710. This has been around for some time, I think I remember confirming this myself when I worked on Netscape 7, Mozilla/Seamonkey. (I was on the QA team for some of those releases). In Camino and Safari, the right click on a menu-of-toolbar-bookmarks gets mapped to a mouseclick.
stackexchange-superuser
{ "answer_score": 3, "question_score": 6, "tags": "mac, firefox, mouse" }
Data Access Layer returning BusinessObjects Currently I'm researching the best design pattern to implement for a windows form application using VS2010 in VB. I'm getting a bit confused with some design patterns. I understand that the DAL should return objects and not datareaders, datasets etc. but... if I have two functions in my DAL: GetProductById & GetAllProducts These two functions would return a Product object and a collection of Product objects respectivley. Would Product not be a BOL object? If I add CRUD into this object then it can no longer belong to the BOL do you have two versions of the object, one for DAL & one for BLL without the database methods? I know there are similar posts on here but they have only served to confuse me further, is it possible someone could just explain in simple terms how DAL objects interact and differ from BOL objects. Thanks.
the scenario you've described is just fine- your DAL _should_ return business objects (or, to use MVC terminology- model objects). the model objects are a different 'layer', with which both the controller layer and the DA layer interact. your CRUD methods can also go into the DAL (SaveProduct() or DeleteProduct() etc.)
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "design patterns, data access layer, business objects" }
What's the purpose of adding って here? ![enter image description here]( Wouldn't be exactly the same?
There is a subsidiary verb (-). To break down: * **** : "to accompany/take" * **** : the te-form of * **** : (-) added * **** : the contracted version of ; see this chart * **** : the te-form of ; the te-form is not because still conjugates irregularly like or would make no sense in this context. (-) is a **very** important subsidiary verb, and failing to add it would make the sentence sound awfully wrong. Whenever you want to say "to take [someone] (to somewhere)", you need either , , or keigo equivalents of them.
stackexchange-japanese
{ "answer_score": 5, "question_score": 4, "tags": "grammar, subsidiary verbs" }
$A$ be a $5\times 5$ real matrix $\ni$ each row sum is $1$, then each row sum of the matrix $A^3$? $A$ be a $5\times 5$ real matrix $\ni$ each row sum is $1$, then I need to know the sum of all entries the matrix $A^3$ Well, I have no clue. One thing I realise that the matrix will have $1$ as an eigen value with corresponding eigen vector $(1,\dots,1)^t$ Thanks. Here row sum I mean $a_{11}+\dots+a_{15}=1$
Since $A (1,\ldots,1)^t = (1,\ldots,1)^t$ we also have $A^n (1,\ldots,1)^t = (1,\ldots,1)^t$. But the elements of $A^n(1,\ldots,1)^t$ are exactly the row sums of $A^n$!
stackexchange-math
{ "answer_score": 3, "question_score": 1, "tags": "linear algebra" }
get all lines NOT end with 'rpms' in sed I want to append following line to those lines. If you have any good tips, please let me know. Thanks a lot. I have tried sed -e '/?!(rpms$)/{N;s/\n//}' filename But failed.
I think you are looking for that to put lines that don't end with rpms on a single line: sed -e ':a;/rpms$/!{N;s/\n//;ba}' Instead of trying to negate a pattern, you can negate the test itself putting the negation operator `!` after the pattern. To handle the case where there are more than two lines without rpms at the end, I added the label `:a` and the unconditional jump `ba` to this label.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": -1, "tags": "regex, sed" }
Windows 2008 - Task scheduler information Can anyone let me know if there is any equivalent functionality to JT.EXE to provide the following: A. Windows Scheduled Task information. Data returned must include Application name, app parameters, credentials account name, task type, days interval, weeks interval, days of the week, start time, and whether the job is disabled.
The SCHTASKS command (reference, examples) has been available since XP, and should do everything you need. Specifically, to see all the info you wanted, you can type schtasks /query /v
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "windows server 2008" }
Javascript equivalent of Java's matcher.matches Is there any function in `Javascript` that replicates Java's `matcher.matches()`? Ok, let me narrow it down. JAVA: The matches function in java tries to match the input regex against an entire string, say the regex is "^http" and the string is "< the output is false where as ^http.* returns true. JAVASCRIPT: In js, the function i tried was ".test()" which returned true even when the regex is "^http" for the same input string. I use java in server side and js in client side, and I want to express the same behaviour on both. Is there any other method in js that replicates the matches function in java
> The matches function in java tries to match the input regex against an entire string There is no such function in JavaScript. You'll need to manually anchor your regex to the begin and end of the string. /^http$/.test(" // false
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "javascript" }
Como impedir Python de considerar números muito próximos iguais? Fiz esse algoritmo para testar como Python compara números próximos: x = 2.5 # número arbitrário que escolhi para fazer os testes y = float(input('Insira o Y ')) # print('X > Y = {}'.format(x > y)) # mostra se x>y print('X = Y = {}'.format(x == y)) # mostra se x = y print('X < Y = {}'.format(x < y)) # mostra se x < y Para y = 2.50000000000000001, por exemplo, Python retorna que X = Y. Insira o Y 2.50000000000000001 X > Y = False X = Y = True X < Y = False Process finished with exit code 0 Como fazer o Python perceber que X é menor que Y, parando de arredondar?
Isso parece ser um problema de precisão do `float`. Ao executar o termninal do Python e colar o valor `2.50000000000000001`, é retornado `2.5`. Para solucionar, utilize a classe `Decimal`. from decimal import Decimal x = 2.5 y = Decimal(input('Insira o Y ')) print('X > Y = {}'.format(x > y)) # false print('X = Y = {}'.format(x == y)) # false print('X < Y = {}'.format(x < y)) # true
stackexchange-pt_stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "python" }
Permissions to Create DB's and be able to perform any function only on those DB's I am looking for a way to allow users to create databases which only they and SA accounts will have access to (Perform any function; creating/deleteing tables, deleting the DB, etc). For example, User1 creates DB1 and User2 creates DB2. User1 must have full access to DB1 but no access to DB2 and User2 will have full access to DB2 but no access to DB1. Thanks
I think you need to clear up the distinction between _logins_ (security entities at the server level) and _users_ (security entities at the database level, which may be associated with a server-level login). What you want to do here is grant `CREATE ANY DATABASE` to the server-level login. For example: CREATE LOGIN foo WITH PASSWORD = N'bar', CHECK_POLICY = OFF; GO GRANT CREATE ANY DATABASE TO foo; GO Now, log in as `foo` in another window, and note that they can do this: CREATE DATABASE foo_1; GO USE foo_1; GO CREATE TABLE dbo.bar_1(foo_what INT); GO But as soon as they try to use a database they did not create: USE AdventureWorks2014; GO They are blocked: > Msg 916, Level 14, State 1 > The server principal "foo" is not able to access the database "AdventureWorks2014" under the current security context.
stackexchange-dba
{ "answer_score": 1, "question_score": 1, "tags": "sql server 2008 r2, permissions" }
Is a field extension $L/K$ finite if and only if $L$ is a finitely-generated $K$-algebra? I recently started learning commutative algebra from Atiyah-MacDonald. This means that for the next few months, I'll be posting some (mostly silly) questions to check my understanding. (Thank you all in advance for your patience.) > **My understanding:** Let $L/K$ be a field extension. Then the following are equivalent: > > (1) $L$ is a finitely-generated $K$-algebra > > (2) $L/K$ is a finite extension > > (3) $L$ is a finite $K$-algebra (i.e. finitely generated as a $K$-vector space) My understanding is that $(2) \iff (3)$ is immediate, as is the implication $(3) \implies (1)$. However, the implication $(1) \implies (2)$ is non-trivial, and is a form of the weak Nullstellensatz. Is everything I've said correct?
Yes. ${}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}$
stackexchange-math
{ "answer_score": 7, "question_score": 4, "tags": "commutative algebra" }
Reading new file with change in folder in python I am using the `import os` library to work with all the folders in the current directory. However, I need the program to ask for a file name or path every time it starts to walk through a new folder within the directory. Example: Assuming that There are two folders in a directory namely: 1. Level Control 2. Level Change. when the program walks through Level Control folder, it should read file `a.txt`. And when walking through Level Change folder, it should read file `b.txt`. Also assuming that both the files are in the same directory.
By looking at your description, the following code should work (Python 3.x), but some case are not mentioned in your description (e.g. how to handle folders with folder and file), so you may need to do some modifications. import os def walk(root): dirs = [] for item in os.listdir(root): if os.path.isdir(os.path.join(root,item)): dirs.append(item) if len(dirs) > 0: for n,d in enumerate(dirs): print(f'[{n}] : {d}') folder = input('which folder ? ') path = os.path.join(root, folder) if os.path.isdir(path): walk(path) print('Invalid path') else: for file in os.listdir(root): print(f'read : {file}') walk('.') Instead of os.walk(), you may use os.listdir() as you need to do action according to the content in the current directory.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "python, os.walk" }
Как задать выравнивание полей эмбеда по вертикали вместо горизонтали в discord.py? Я хочу сделать так, чтобы поля эмбеда выравнивались как на картинке 1: ![Картинка 1]( ..А не как у меня: ![Картинка 2]( Подскажите, как так сделать?
Тебе нужно добавить параметр `inline`. Вот **пример кода** : embed.add_field(name='Information', value='Описание', inline=False) По дефолту параметр `inline` равен `True`, из-за этого происходит так, как ты показал на втором скрине. Вот ссылка на документацию: <
stackexchange-ru_stackoverflow
{ "answer_score": 4, "question_score": 1, "tags": "python, bot, discord py" }
What is the meaning of this php line of code? (codeigniter) So today i play with the < source code and i found this line: $id = ($this->input->get_post('id')) ? (int) $this->input->get_post('id') : $this->uri->segment(3); I already understand the basic syntax use in codeigniter but hope someone can tell me what is the use of this symbol (?) between the two syntax? If it some kind of technique, what is the name of the technique? What is he trying to achieve with this line of code? Thanks.
`Ternary` operator; same as if(($this->input->get_post('id')) == true) { $id =(int) $this->input->get_post('id') } else { $id=$this->uri->segment(3); }
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "php, codeigniter" }
Combobox query in Access 03 database showing on some pc's limited data I have a combobox which looks at a table and displays it's 5 columns of data via a query to be used like a search, on most pc's all 5 columns populate with data but on some only the last 3 columns populate and it displays blank FirstName and Surname columns, any idea how this could happen or how to fix it? Also the combobox isn't used to select just to confirm that searched for people are in the database so there are no events and it is all setup in the combobox properties. Edit- I bet a post topic like this could stack up those tumbleweed badges if one could get more than 1 of em.
There could be two causes. One possibility is that the number of rows being returned in a query is not the same as the combo box Column Count property. If you are changing the combo box Row Source property make sure the updates have the same number of columns. MS fixed this bug but I'm not sure when it was fixed. More likely though is that the PCs in question don't have the following hotfix installed. Description of the Access 2003 post-Service Pack 3 hotfix package: December 18, 2007
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "ms access, ms access 2003" }
What would be the most common one word or phrase to describe the name of a group that people work in a business organization? I work in a research institute where we have operation groups called in many different names such as _Office, Branch Office, Group, Unit, Center, Division, Department, Project Team, Section_ , etc. I'm now drafting a kind of questionnaire asking everyone in the organization to answer it, and one of the entry items included in it is "Your xxxxxx: ___________." In the blank, I would like the answers to write the name of the group they belong to, and what I'm looking for is a word or phrase that could best fit in the "xxxxxx" part. Is there any such one word or phrase? One of my colleagues has suggested "Affiliation." Do you agree?
There probably isn't a single word or phrase that will capture all of these without any ambiguity or confusion. You might want to include some examples in your questionnaire along with that question. " **Organizational Unit** " is used in a similar setting to address the problem you are describing. More info & examples here: <
stackexchange-ell
{ "answer_score": 1, "question_score": 0, "tags": "word choice, word request, phrase request, phrase choice" }
Is my dimmer switch failing or is it bad wiring? A few days ago my wife mentioned that there was a "burning smell" near the kitchen, but it went away before I could investigate. Today I turned on the dimmer switch in my kitchen, and the lights began flickering. I turned off the switch, but not before a smell had started coming from the dimmer switch (pictured below). We've used the lights in my kitchen a bunch of times since my wife first had the issue, so it isn't consistent. Is it likely the problem is faulty wiring or could the dimmer unit simply be going bad? I'd like to know my options before I replace it or pay for an electrician. !Dimmer switch
If wires spark enough to generate a burning smell, you'll hear the arc and it's also possible the breaker would go as well. From the symptoms you describe it sounds like the dimmer itself is going. Since it has a burning smell, I would say it's unsafe to use and you should replace it immediately. Of course, if you see any nicked wires, or any of the wire nuts are loose then you should fix those problems. Be sure to turn off the power at the panel when you're doing this (you should check with a non-contact voltage detector just to be safe).
stackexchange-diy
{ "answer_score": 5, "question_score": 3, "tags": "electrical, wiring, switch" }
Monotonic function that is not of bounded variation Are all monotonic of bounded variation, or would there exist a counterexample of a function that is monotonic but not of bounded variation?
A function defined on a closed interval which is monotonic is indeed of bounded variation. If $f$ is monotonic increasing on $[a,b]$ then the total variation is always $f(b)-f(a).$ Indeed, there is a characterization that a function on $[a,b]$ is of bounded variation if and only if it can be written as a difference of two monotonic increasing functions. For other intervals, you need to add the condition that the function is bounded. For example, on $(0,1)$ the function $g(x)=-\frac1x$ is monotonic increasing, but not of bounded variation. On $\mathbb R,$ $h(x)=x$ is increasing and not of bounded variation.
stackexchange-math
{ "answer_score": 3, "question_score": 0, "tags": "real analysis, integration, measure theory, derivatives" }
java.lang.ArrayIndexOutOfBoundsException error displayed when run soapUI testsuite through jenkins When i am running testsuite through jenkins, 'java.lang.ArrayIndexOutOfBoundsException' error displayed in logs. The line where error occurred. def randomuserserial = Long.toUnsignedString(new Random().nextLong().abs(), 16).toUpperCase() No error occurred when i run the same suite in my local machine.
The problem is with SoapUI(5.3.0) version installed in Jenkins Server. After updated to latest version (5.4.0), it works fine.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "jenkins, groovy, soapui" }
How to execute sh for all the files in current directory sh checkemp.sh * It will just check for one file everytime this command is executed. where checkemp.sh has only one variable which is filename=$1
You could do: for file in checkemp.sh *; do sh $file; done If you want to run them all concurrently, try: for file in checkemp.sh *; do $file & done This executes the command `sh $file` where file iterates over the values `checkemp.sh` and all the other files in the directory. It's not clear to me exactly what you are tyring to do with `checkemp.sh`. Perhaps you are looking for: for file in *; do sh checkemp.sh $file; done Honestly, though, you'd be better off writing `checkemp.sh` with an interpreter line and doing: checkemp.sh * and iterate over the arguments within the script.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "sh" }
Audience targeting the navigation with SharePoint Group I want to hide specific navigation links on a communication site for viewers but keep them visible for owner. I stumbled upon audience targeting and the possibility to use SharePoint Groups. I then created a group called **M365_Publisher** on the site but I can't select it in the target group box under the navigation link options. Am I understanding target audience wrong or do I have to activate something else?
SharePoint Groups are not supported for audience targeting in SharePoint online. > Azure Active Directory (Azure AD) groups (including Security groups and Microsoft 365 groups) are supported. **Source** : Target navigation, news, and files to specific audiences If you want Microsoft to allow using SharePoint groups, considering voting on below related UserVoice: 1. Navigation audience targeting support SharePoint groups 2. Allow using SharePoint groups to target audiences in quick links web part
stackexchange-sharepoint
{ "answer_score": 1, "question_score": 0, "tags": "sharepoint online, navigation, modern experience, audience targeting, communication site" }
Premium ASP.NET hosting I know there are a million ASP.NET hosting options, but what are the premium options if you have some money to spend and want maximum performance and uptime? We currently use MaximumASP and they are generally great. I know another good option is Rackspace. Does anyone have any other suggestions? This is one of those things that is hard to Google, because everyone calls their hosting option premium or professional.
I'd say Rackspace is a good choice, but I use discountasp.net because I needed .NET 3.5 SP1 hosting with SQL 2008 and they delivered.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 7, "tags": "asp.net, hosting" }
SQL PHP - How to get records of specific day by timestamp I have a SQL database that has a column "A" that has timestamps in it. How do I return all values that have a timestamp that doesnt fall under the current day. So say for example its Monday, i want to return all values that are not this Monday. ![enter image description here](
Use **DATE()** or **CURDATE()** MySQL function:- Return all values that are **current date** :- select * from table where DATE(emailsend)=CURDATE() Return all values that are **not current date** :- select * from table where DATE(emailsend) !=CURDATE() > Or use MySQL WEEKDAY() returns the index of the day in a week for a given date ( **0 for Monday** , 1 for Tuesday and ......6 for Sunday) select * from table where WEEKDAY(emailsend) !=0 //Return all values where day not is monday
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "mysql" }
PWM in H-Brigde for Low-Frequency Inverter I'm trying to make an H-bridge for a low-frequency inverter circuit using this reference implementation from Texas Instruments: 650-W Power Stage Without Heat Sink Ref Design or Low-Frequency Offline UPS (Rev. B) But I'm having trouble in understanding the switching waveforms of the H-bridge. Let's talk about the first half cycle of 10 ms, according to this reference, the FETs from the right side of the half-bridge are both switching at PWM frequency with complementary pulses, if this is true then we need to insert dead-time in every pulse of these signals to avoid any shoot-through condition. **Am I getting it right?** Any guidance would be greatly appreciated! ![enter image description here](
You are correct. Dead time is necessary to prevent shoot-through. The upper FET is switched on to provide a low resistance current path for the inductive current. This maintains the current. It bypasses the body diode. However the body diode will turn on during the dead time.
stackexchange-electronics
{ "answer_score": 1, "question_score": 0, "tags": "pwm, inverter, h bridge" }
Проблема импорта товаров из 1с в ручном режиме (через файл bx_1c_import.php) Всем доброго времени суток. Столкнулся с проблемой импорта товаров в битрикс (версия 16.0.13). На сайте уже сформирована структура разделов и залиты товары, мне нужно обновить товары , делаю я это как написано в название темы через скрипт bx_1c_import.php процесс импорта идет нормально , ошибок не выдает. Настройки импорта на сайте * Что делать с товарами, отсутствующими в файле импорта: деактивировать, * Что делать с группами, отсутствующими в файле импорта: ничего стоит галочка: Использовать контрольные суммы элементов для оптимизации обновления каталога Время БД и сервера совпадают Но после импорта абсолютно все товары деактивированы. А если я меняю настройку "Что делать с товарами, отсутствующими в файле импорта" с деактивировать на нечего то после импорта все товары активны. Проверил файлы выгрузки те товары которые деактивируются присутствуют в файле. Почему так может происходить ?
С 4 версии обмена поддержка флагов «Что делать с товарами, отсутствующими в файле импорта» не используются, точнее могут использоваться, но работать при полной выгрузке может некорректно. В связи с тем что в полной выгрузке это не работало, и обмен происходит пакетами — лучше не использовать данный функционал. Принято после обмена удалять товары лишние или в 1С помечать их и на сайте удалять.
stackexchange-ru_stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "битрикс, 1с" }
Piano song played with three hands, heard in romantic films I'm currently looking for a piano song which is heard in multiple films. I can't remember the name of those films although. The piano song is played with three hands. The song is often played in a romantic scene where the man play the piano with two hands and a girl will just play some notes with the right hand (one finger should be enough though). I can't exactly remember the tones but for the girl the three first notes are the same. So I'm looking for the name of this song and the name of some movies where the song is played.
Pretty confident you're looking for Heart And Soul. I remember they played it on an episode of Lost, and at least on Stuart Little.
stackexchange-musicfans
{ "answer_score": 2, "question_score": 3, "tags": "identify this song, piano" }
Наложить картинку на другую по не целочисленной координате Сейчас наложение одной картинки на другую происходит с помощью `PIL`, `Image.paste`: from PIL import Image img0 = Image.open("foo.jpg") img1 = Image.open("bar.jpg") img0.paste(img1, (x, y)) Но `Image.paste` не позволяет задавать не целочисленные координаты. Каким образом наложить одну картинку на другую по не целочисленным координатам (с антиалиасингом). (округление/преобразование позиции наложения к `int` не дает приемлемых результатов)
Пока решил таким костылем: * обе картинки увеличиваются в 10 раз * координаты для наложения умножаются в 10 раз и округляются до целого * одна картинка накладываются на другую по полученным целочисленным координатам * итоговая картинка уменьшается в 10 раз (с антиалисингом) Таким образом будет учитываться дробная часть координат до десятых, что на глаз уже вполне приемлемо. Из минусов - дополнительные манипуляции, требующие времени и расхода памяти.
stackexchange-ru_stackoverflow
{ "answer_score": 2, "question_score": 3, "tags": "python" }
I need to generate records for current week based on today's date I need to generate records for date, In time and out time for current week based on todays date and empcode(Sql server 2008 r2),when a user clicks Current week in dropdownlist in asp.net web application. I have stored procedure like this: select @empcode as empcode, min(eventdate) as firstIn, max(eventdate) as lastout from eurevents where empcode = @empcode and convert(Varchar,logdate,110) = convert(Varchar, @searchdate, 110); I am a trainee newly joined. so please help me out
This bit of code will bring you back all records within the current week. If you only want the working week (without weekends) change the *7 and +7 to *5 and +5 BETWEEN dateadd(dd,(datediff(dd,-53684,getdate())/7)*7,-53684) AND dateadd(dd((datediff(dd,-53684,getdate())/7)*7)+7,-53684)
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "sql, datetime, sql server 2008 r2" }
How to get an error on VSC if the signature of a Typescript Function doesn't return a type Hi I would like to know if there is a way to force TSLint (I guess) in order to get an error if a fucntion does't return a type (at least any). e.g. cont myFunc(par: string) { // somthing here } I would like to have an error there in order to force me to do this cont myFunc(par: string): number { <--This! // somthing here }
In `tslint.json`, `"call-signature"` must be present under `typedef:` > > tslint.json > ... "typedef": [true, "call-signature", "property-declaration"] ...
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "visual studio code, tslint" }
Trying to find the name of a really old UI design book by Apple This morning, I was reading a news article on Apple (either Snow Leopard or FCC), and I came across a part that referred to an old book by Apple (IIRC), that had two parts, and the first part was just on UI design. I was trying to get a copy of that book, but it seems I lost the link to the article. Does this book ring a bell with anyone, and if so, what's the title? (This book was published before 2000, maybe even before 1990, so if anyone recalls this book, congrats!, you have a great memory).
I'm going to take a punt at either of these books. Apple Computer Inc. (1985). Chapter Two: The Macintosh User-Interface Guidelines. In Inside Macintosh: Volume I Apple Computer Inc. (1991). Chapter Two: User Interface Guidelines. In Inside Macintosh: Volume IV
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "user interface, mac classic" }
Net Core: access to appsettings.json values from Autofac Module AspNet core app 1) Autofac module like that public class AutofacModule : Module { protected override void Load(ContainerBuilder builder) { //Register my components. Need to access to appsettings.json values from here } } 2) Module from step№1 registered into `Startup.cs` public void ConfigureContainer(ContainerBuilder builder) { builder.RegisterModule(new AutofacModule()); } How to access to `appsettings.json` values from `AutofacModule`? I need that for create my objects inside `AutofacModule` and using it for DI.
Need to change step №2 public void ConfigureContainer(ContainerBuilder builder) { //get settigns as object from config var someSettings= Configuration.GetSection(typeof(SomeSettings).Name).Get<SomeSettings>(); //put settings into module constructor builder.RegisterModule(new AutofacModule(someSettings)); } I don't know is "best practise" way or not, but it works.
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": 11, "tags": "dependency injection, .net core, autofac, autofac module" }
How can `firebase.functions().httpsCallable` submit files to `functions.https.onCall`? **Background:** 1. We want to allow users to upload files onto our website 2. The files need to be validated and modified before they are written to Cloud Storage 3. We also need to authenticate the user before we allow them to upload files 4. And, we need to do some Firestore calls before the files are written to Cloud Storage **Specifications:** * We're calling Cloud Functions from the front-end using `firebase.functions().httpsCallable` * The backend uses `functions.https.onCall` **Question:** How can `firebase.functions().httpsCallable` submit files to `functions.https.onCall`? Thank you in advance. ABC.
That's not really an intended use case for callable functions. Callables are meant to send a JSON payload to the server, not a file. If you really want to send a (small) file to a function, you'll need to base64 encode it as a string, and put that string in the JSON payload, then decode it in the function. Instead, consider allowing the client to upload directly to storage, then use a function to validate it with a storage trigger, and delete it if it's not valid.
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 7, "tags": "firebase, google cloud functions" }
Starting Android service already running? Sure this is a trivial question. What happens if I start a `Service`, using the following code: startService(new Intent(this,myService.class)); and then I accidentally recall the above code, while the `Service` is yet running? I'm afraid that the second call to `startservice` can create a new `Service` in order to have two different process executing at same time.
> I'm afraid that that the second call to startservice can create a new service in order to have two different process executing at same time. No, on multiple counts: * No, it will not create a new service. If the service is already running, it will be called with `onStartCommand()` again, to deliver the new `Intent`, but a second copy is not created. * No, it will not "have two different process executing at same time", because a service runs in the same process as the rest of your app, by default.
stackexchange-stackoverflow
{ "answer_score": 79, "question_score": 46, "tags": "android, service, android intent" }
How do you open (actually open) a text file in Excel using VBA? I know how to read/write from/to a text file. But those routines don't actually visibly open the text file. I want to be able to open the text file so I can make edits directly (in the Notepad application), rather than through a macro. To clarify - I am not looking to import the data from the text file into Excel. I just want to open the text file from within Excel - but the actual edit of the text file will be in Notepad.
Have you tried it like this: Sub OpenTextFile() On Error GoTo 1 ActiveWorkbook.FollowHyperlink "C:\Windows\test.txt", NewWindow:=True Exit Sub 1: MsgBox Err.Description End Sub Source: < _P.S. Sorry, I'm currently on a machine without excel installed, so I can't test it until monday...so please try it_
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": -1, "tags": "vba, excel" }
How to add list property values I have the following code. How can I add values to this properties? APIKarhoBookingProperties objbooking = new APIKarhoBookingProperties(); objbooking.currency = "USD"; objbooking.price_components = ??? //how to add values this section class APIKarhoBookingProperties { public string currency { get; set; } public List<PriceComponent> price_components { get; set; } } public class PriceComponent { public string component_name { get; set; } public double value { get; set; } public string description { get; set; } public string currency { get; set; } }
Read some c# basics, List price_components.Add(new PriceComponent(){ component_name = "name", value = 2, description = "dgfdgf", currency = "USD" });
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -6, "tags": "c#, winforms" }
Java HotSpot Enum overhead Suppose you have a "simple" enum: public enum Day { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY } And then you use it somewhere: Day day = Day.SUNDAY; ... if(day==Day.SUNDAY) {...} How does this compare performance wise (memory and time) with using ints? int day = Day.SUNDAY; ... public class Day { public static final int SUNDAY=0; public static final int MONDAY=1; } We have the JIT HotSpot compiler enabled along with other "standard" optimization.
There may be a slight performance loss for the enum whenever you reference Day.SUNDAY, because the `int` constant is a compile-time constant and so can be inlined, whereas the `enum` constant requires a `getstatic`. Comparing two ints or two references is of course identical in terms of time required, since you are comparing the references (addresses), not calling `.equals()`. Of course, the performance hit here is minuscule; the only reason to worry about this would be if this is in a performance-critical part of your application and profiling shows that using ints is better. The benefits of enums for maintainability and code correctness far outweigh a slight inefficiency like this.
stackexchange-stackoverflow
{ "answer_score": 7, "question_score": 7, "tags": "java, performance, enums" }
Video thumbnails in WPF I'm trying to add videos to my WPF project, but I can't find a proper solution for generating previews/thumbnails of the video. A lot of solutions on the internet mention you should play and then pause the video in code behind. I don't really like that solution especially because it gets very messy in combination with the MVVM structure of our project. Another solution I thought of is generating a screenshot from the video and display that screenshot instead of the video, but I also have no success in creating the screenshots. How do you guys show thumbnails of your videos?
You do this by setting the **MediaPlayer** 's property of **ScrubbingEnabled** to true and still you need to move forward to capture any movie at real time. For more samples, please read this nice blog entry by Clint Rutkas: <
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "wpf, video, mvvm, mediaelement" }
Loop and check if integer I have an exercise: > Write code that asks the user for integers, stops loop when 0 is given. Lastly, adds all the numbers given and prints them. So far I manage this: a = None b = 0 while a != 0: a = int(input("Enter a number: ")) b = b + a print("The total sum of the numbers are {}".format(b)) However, the code needs to check the input and give a message incase it is not an integer. Found that out while searching online but for the life of me I cannot combine the two tasks. while True: inp = input("Input integer: ") try: num = int(inp) except ValueError: print('was not an integer') continue else: total_sum = total_sum + num print(total_sum) break I suspect you need an `if` somewhere but cannot work it out.
Based on your attempt, you can merge these two tasks like: a = None b = 0 while a != 0: a = input("Enter a number: ") try: a = int(a) except ValueError: print('was not an integer') continue else: b = b + a print("The total sum of the numbers are {}".format(b))
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "python" }
How to display static (shared) object's properties in a PropertyGrid? I would like to display static (shared) objects at runtime in a PropertyGrid but if I try to set the selected object property of the grid like this: _propertyGrid.SelectedObject = System.Windows.Forms.Application I get a compilation error: > 'Application' is a type and cannot be used as an expression. Is there a way to display a static (shared) object or the object's properties in the PropertyGrid?
That assignment statement really doesn't make sense from an OO-perspective because a static object really isn't an object -- it's just a collection of methods and properties without any kind of coherence except for the class name. I see what you're trying to do, though. You need to give it an object instance. I would suggest creating a wrapper class (possibly a singleton) that exposes the properties you need from the `Application` object and using that as a data source instead.
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 1, "tags": "c#, vb.net, winforms, static, propertygrid" }
Equation of line from PPM vs Voltage for sensor. I have an Electrochemical Hydrogen sensor that I am trying to convert its analogue values to PPM values. I am attempting to follow the datasheet and come up with an equation of the line so I can get a formula into which I put the voltage, and out the other side comes PPM. I have tried interpolating using Wolphram Mathematica but what is produced is a lengthy polynomial that hits all the points I plotted based on the graph shown, although it is wildly off-track in between the points because it makes a line that waves up and down instead of a sort of single curve like is on the graph. This is the graph that I am attempting to turn into a formula: MQ8 Graph And this is the full datasheet: Datasheet Link Winsen MQ-8
The fitting of a model such as $y=a+b\:e^{p\:x}$ is not accurate. A much better result is achieved with two exponentials : $$y=a+b\:e^{p\:x}+c\:e^{q\:x}$$ The numerical calculus below leads to an asymptote : $y_{max}= a\simeq 3.51$ The existence of a minimum value $\quad y_{min}= a+b+c\simeq 0.28\quad$ at $x=0\quad$ appears consistent with the fact that, even without hydrogen in the sensor, a residual output remains due to other gaz and/or other heat conduction phenomena. The data used consists in 12 points $(x_k,y_k)$ taken in scanning the graph provided by user2385411. ![enter image description here]( Drawn on the original graph, the fitted curve appears in red : ![enter image description here]( The very good fitting was carried out thanks to the method from the paper < , pp.71-74. From this paper, the procedure is : ![enter image description here](
stackexchange-math
{ "answer_score": 0, "question_score": 0, "tags": "regression" }
Help with select statement with one to many relationship what is the best way to write a select statement with two table that have a one to many relation ship? I have a table called broker with these fields id companyname then another table called brokerContact that has a foreign key to the broker table with these fields id brokerid contact name phone How can I write a select statement that will get all the records from the brokertable as well as all of the brokercontacts for each brokerid, Without selecting all the brokers in my C# code then enuerating over them to get the brokerContacts for each, or is this the only way? If that doesn't make sense or more clarification is needed please let me know. Thank you also, this will be in a stored procedure
To get all the records from the Broker table, along with all the BrokerContacts, you could use an `INNER JOIN`: SELECT B.ID ,B.companyname ,BC.ID ,BC.contact ,BC.[name], ,BC.phone FROM Broker AS B INNER JOIN BrokerContact AS BC ON BC.BrokerID = B.ID ORDER BY B.companyname If you have multiple contacts, you'll see one row for each contact, with the `companyname` repeated.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 2, "tags": "c#, sql, tsql" }