Q: indicator of mosfet switch, optimized? I want a visual indicator of my MOSFET's switching state, so I've designed this circuit with fairly generic smd parts and simulated it a bit to see if it performs as I've expected. It seems okay up to 4khz or so (and the usefulness of an LED breaks down at a few hertz anyhow).
Before I commit this to traces, is it designed appropriately? I'm not confident in my EE abilities.

simulate this circuit – Schematic created using CircuitLab
version two
resistor on base and LED on other side of NPN

simulate this circuit

A: You are using an NPN transistor as a high-side switch, which is generally not a good idea. The NPN transistor should be between the LED's cathode and ground. You also need a resistor in series with the NPN base to limit the base current to a few milliamperes.
An easier approach would be to just put a 1k resistor and LED in parallel with the lamp. No need to add the NPN transistor at all.

A: It depends on what the gate voltage range is.  You show a square wave, but not the voltage levels.
If the highest goes much more than the 3 V supply for the LED, then that supply will be back-driven via the B-C junction.  That's probably not what you want.
Also, what's the maximum current the LED can handle?  Let's say that's 20 mA.  That means the maximum voltage across R_LED can be 2 V.  Let's say the LED drops 2.1 V, so that means the emitter should never go higher than 4.1 V, and therefore the base not higher than 4.8 or so.  However, as pointed out above, at about 3.7 V the 3 V power supply starts being back-driven.
In any case, you have to start with proper specs.  Jumping in an deciding on a topology doesn't make sense until you know what the job is that the circuit is supposed to perform.  Go back and do it right, starting with some real specs.


Q: Best way to get properties from html and use as global variable in Angular 2+ What is the best way to get properties from html and use as global variable in Angular 2+?
index.html
...
<script>
    window.properties = {
        'variable1': 'string 1',
        'variable2': 'string 2'
    };
</script>
...

A: @Injectable()
class MyGlobalService {
  properties$:Subject = new BehaviorSubject();

  constructor() {
    this.properties.next(window.properties);
  }
}

@NgModule({
  providers: [MyGlobalService],
  ...
 })
 class AppModule()

class MyComponent {
  constructor(private myGlobals:MyGlobalService) {
    myGlobals.properties$.subscribe(val => console.log(val));
  }
}


Q: SQL join on one-to-many relation where none of the many match a given value Say I have two tables
User
-----
id
first_name
last_name

User_Prefs
-----
user_id
pref

Sample data in User_Prefs might be
user_id | pref
  2     |  SMS_NOTIFICATION
  2     |  EMAIL_OPT_OUT
  2     |  PINK_BACKGROUND_ON_FRIDAYS

And some users might have no corresponding rows in User_Prefs.
I need to query for the first name and last name of any user who does NOT have EMAIL_OPT_OUT as one of their (possibly many, possibly none) User_Pref rows.
SELECT DISTINCT u.* from User u
LEFT JOIN User_Prefs up ON (u.id=up.user_id)
WHERE up.pref<>'EMAIL_OPT_OUT'

gets me everyone who has at least one row that isn't "EMAIL_OPT_OUT", which of course is not what I want.  I want everyone with no rows that match "EMAIL_OPT_OUT".
Is there a way to have the join type and the join conditions filter out the rows I want to leave out here?  Or do I need a sub-query?

A: I personally think a "where not exists" type of clause might be easier to read, but here's a query with a join that does the same thing.
select distinct u.* from User u
left join User_Prefs up ON u.id = up.user_id and up.pref = 'EMAIL_OPT_OUT'
where up.user_id is null

A: Why not have your user preferences stored in the user table as boolean fields? This would simplify your queries significantly.
SELECT * FROM User WHERE EMAIL_OPT_OUT = false


Q: Exception on "add_roles" function for discord.py I'm trying to add roles to users by listening for Reaction. Although it will succeed, there will always be errors after execution. I want to ask how to solve this problem?
Codes there:
@client.event
async def on_raw_reaction_add(payload: discord.RawReactionActionEvent):
    if payload.message_id == 0000:
        guild: discord.Guild = client.get_guild(payload.guild_id)
        if payload.emoji.name == "someEmoji":
            role0: discord.Role = guild.get_role(1111)
            await payload.member.add_roles(role0)
        elif payload.emoji.name == "someEmoji":
            role1: discord.Role = guild.get_role(2222)
            await payload.member.add_roles(role1)

Logs(With pysnooper):
19:50:26.101973 line        54                 await member.add_roles(role1)
19:50:26.104641 return      54                 await member.add_roles(role1)
Return value:.. <Future pending>
Starting var:.. payload = <RawReactionActionEvent message_id=1111...d=None> event_type='' member=None>
Starting var:.. guild = <Guild id=1111 name='' shard_id=0 chunked=True member_count=0>
Starting var:.. member = <Member id=00000 name='member'>
Starting var:.. role1 = <Role id=11111 name='role1'>
19:50:26.588117 call        54                 await member.add_roles(role1)
19:50:26.590784 exception   54                 await member.add_roles(role1)
Exception:..... StopIteration
[2022-12-20 19:50:26] [ERROR   ] discord.client: Ignoring exception in on_raw_reaction_remove
Traceback (most recent call last):
  File "C:\Users\****\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\client.py", line 409, in _run_event
    await coro(*args, **kwargs)
  File "main.py", line 54, in on_raw_reaction_remove
    await member.remove_roles(en_role)
  File "C:\Users\****\AppData\Local\Programs\Python\Python38\lib\site-packages\pysnooper\tracer.py", line 367, in __exit__
    start_time = self.start_times.pop(calling_frame)
KeyError: <frame at 0x000001A1014E6DD0, file 'main.py', line 54, code on_raw_reaction_remove>


Q: Tablelayout with massive data android What is the best way to create a table layout or recyclerview/listview/gridview  in android that can pull a lot of data around 1000 rows and around 50 columns each row without to crash ?
I want to show it like excel sheet nothing special just show data of course with scrolling both ways.

A: TableFixHeaders project on github has an implementation with both Adapter an Recycling of views, plus handles scrolling wery nicely. And is quite easy to modify to suit your needs.

This is not so uncommon request, so it has been done numerous times. I am sure you can find other implementations if this one is not right for you.

A: I saw a similar question on SO a few months ago, and I was interested to see if I could develop a solution.
My concept was to start with a ListView for vertical scrolling and view recycling.  Each list item is a HorizontalScrollView to show a table row with many columns.  The trick here is to listen to each HorizontalScrollView for swipe events and then scroll every HorizontalScrollView in sync with the view being swiped.
I have a proof-of-concept project on Github here:
 klarson2/android-table-test
Downsides: The project was set up for Eclipse, so you can't open it directly with Android Studio.  There is still a small bug with event handling that I haven't got around to fixing.  Another limitation is that each cell view in the horizontal LinearLayout must be a fixed size so that the columns will line up correctly.
However, the example uses a 4MB .csv file with 50 columns and over 10,000 rows for a data source proving that it is possible to display an enormous table in an Android app with responsive two-way scrolling.


Q: Can I convexify this mixed integer optimization problem? I have a mixed integer optimization problem that has linear objective function and two constraints, one is linear but one is not. The non-linear constraint has the form
$$x_{kn}f(\mathbf{y})\geqslant x_{kn}\sum_{j=1}^Kx_{jn},$$ for all $k,n$ in $\{1,\ldots,K\}$ and $\{1,\ldots,N\}$.
Where $x_{kn}$ are Booleans and $\mathbf{y}$ is a vector in $[0,1]^N$. The only way I have $x_{kn}$ in both sides of the above inequality is to say that the constraints is active only when $x_{kn}=1$.
Assuming that $f(\mathbf{y})$ is convex or concave, can I solve this problem efficiently through convex optimization?
I can remove the $x_{kn}$ from the right hand side of the above inequaluty by introducing a large number $M$ but that would keep the product $x_{kn}f(\mathbf{y})$.

A: Suppose that $f(y)$ has a known lowerbound $L$. Note that $\sum_{j=1}^K x_{jn}$ is bounded above by $K$. You can also deactivate the constraint by writing it as:
$$f(y) \geq \sum_{j=1}^K x_{jn} + x_{kn}(L-K)$$
This constraint is convex when $f(y)$ is concave. When $x_{kn}=0$ you obtain the constraint $f(y) \geq \sum_{j=1}^K x_{jn}$, whereas when $x_{kn}=1$, the right hand side is at most $L$, so the constraint does not put any restriction on $y$ or $x_{kn}$.


Q: How to read the range indicator in IL-2 Sturmovik 1946 How do I read the range indicator that is placed next to aircraft? It says 5.03, or 1.23, or 0.54. In what units are they? Feet, meters, miles, kilometers? Or does 1.00 mean that it's the optimum gun range?

A: The distances are in Kilometres.
www.mission4today.com has an excellent beginners tutorial which also goes into optimum gun range, or convergence number.


Q: How to get a page not redirect to the main I'm absolute beginner at JSP and Spring framework and annotations. I've built a standard CRUD application, but have one issue. Whenever i want add, edit or delete a user, application redirects me to main "user" page, if i'm on a page, with an index more than 1. How can i make it stay still on a page, where i do all actions above?
For example, when i want to edit "Tom Hanks"(14, page number 2)
It redirects me to the 1st page
But i want it to be still on the same page, where i add, edit or delete
UserController class is below
@Controller
public class UserController
{
    private UserService userService;

    @Autowired
    public void setUserService(UserService userService)
    {
        this.userService = userService;
    }

    @RequestMapping(value = "users", method = RequestMethod.GET)
    public String listUsers(@RequestParam(value="page", required = false) Long page, Model model) {
        if (null == page)
            page = 1L;
        model.addAttribute("user", new User());
        model.addAttribute("searcheduser", new User());
        model.addAttribute("listUsers", userService.getUsers(page));
        model.addAttribute("page", page);

        return "users";
    }

    @RequestMapping(value = "/users/add", method = RequestMethod.POST)
    public String addUser(@ModelAttribute("user") User user) {
        if(user.getId() == 0)
        userService.addUser(user);
        else
            {
                userService.updateUser(user);
            }
        return "redirect:/users";
    }

    @RequestMapping("/remove/{id}")
    public String removeUser(@PathVariable("id") int id)
    {
        userService.removeUser(id);
        return "redirect:/users";
    }

    @RequestMapping("edit/{id}")
    public String editUser(@PathVariable("id") int id, @RequestParam(value="page", required = false) Long page, Model model) {
        if (null == page) page = 1L;
        model.addAttribute("user", userService.getUser(id));
        model.addAttribute("searcheduser", new User());
        model.addAttribute("listUsers", userService.getUsers(page));
        model.addAttribute("page", page);

        return "users";
    }

    @RequestMapping("userdata/{id}")
    public String userData(@PathVariable("id") int id, Model model) {
        model.addAttribute("user", userService.getUser(id));

        return "userdata";
    }

    @RequestMapping(value="searchresults", method = RequestMethod.POST)
    public String searchResults(@ModelAttribute("searcheduser") User user, Model model) {
        List<User> searchResult = userService.getUsers(user.getName());
        model.addAttribute("listUsers", searchResult);

        return "searchresults";
    }
}

A: Add the page as a parameter on redirect for remove and edit :
@RequestMapping("edit/{id}")
public String editUser(@PathVariable("id") int id, @RequestParam(value="page", required = false) Long page, Model model) {
    if (null == page) page = 1L;
    model.addAttribute("user", userService.getUser(id));
    model.addAttribute("searcheduser", new User());
    model.addAttribute("listUsers", userService.getUsers(page));
    model.addAttribute("page", page);

    return "redirect:/users?page="+page;
}

The same for remove .


Q: Как правильно сократить деление в математике) Я играю и экспериментирую CSS коды, и сейчас наблюдаю на такую классную штуку в css calc(). Недавно поигрался с золотым сечением, стоко делением там понаписал)
height: calc(var(--g100) / 1.618033 / 1.618033 / 1.618033 / 1.618033);

Пытаюсь красиво сократить, и сейчас ищу решение с калькулятором, вот только правильную формулу не могу найти. Есть предложения?
Demo CodePen

A: Есть вариант не с поиском формулы, а с вынесением вычислений в переменные. При желании можно воспользоваться препроцессором less или scss, чтобы генерировать переменные кодом.
Также переменная --gold: 1.618033 позволит вам дать понимание того, что за странное число у вас есть и для чего оно нужно.

document.body.onclick = function() {
  this.classList.toggle('clr');
}
:root {
  --black: #000;
  --white: #fff;
  --g100: 50vmin;
  --gold: 1.618033;
  --level1: calc(var(--gold));
  --level2: calc(var(--gold) * var(--level1));
  --level3: calc(var(--gold) * var(--level2));
  --level4: calc(var(--gold) * var(--level3));
  --level5: calc(var(--gold) * var(--level4));
  --level6: calc(var(--gold) * var(--level5));
  --level7: calc(var(--gold) * var(--level6));
  --level8: calc(var(--gold) * var(--level7));
  --level9: calc(var(--gold) * var(--level8));
  --level10: calc(var(--gold) * var(--level9));
}

*,
html,
body {
  box-sizing: border-box;
  font-size: 0;
  margin: 0;
  padding: 0;
}

body {
  background: var(--black);
  display: grid;
  height: 100vh;
  place-items: center;
}

body.clr {
  background: var(--white);
}

#gld {
  box-shadow: 0 0 0 .2vmin var(--white) inset;
  display: flex;
  position: relative;
  height: var(--g100);
  width: calc(var(--g100) * var(--level1));
}

.clr #gld {
  box-shadow: 0 0 0 .2vmin var(--black) inset;
}

#gld span {
  border: .1vmin solid var(--white);
  height: var(--g100);
  position: absolute;
  width: var(--g100);
}

.clr #gld span {
  border: .1vmin solid var(--black);
}

#gld span:nth-child(2) {
  height: calc(var(--g100) / var(--level1));
  right: 0;
  width: calc(var(--g100) / var(--level1));
}

#gld span:nth-child(3) {
  bottom: 0;
  height: calc(var(--g100) / var(--level2));
  right: 0;
  width: calc(var(--g100) / var(--level2));
}

#gld span:nth-child(4) {
  bottom: 0;
  height: calc(var(--g100) / var(--level3));
  right: calc(var(--g100) / var(--level2));
  width: calc(var(--g100) / var(--level3));
}

#gld span:nth-child(5) {
  bottom: calc(var(--g100) / var(--level3));
  height: calc(var(--g100) / var(--level4));
  left: var(--g100);
  width: calc(var(--g100) / var(--level4));
}

#gld span:nth-child(6) {
  height: calc(var(--g100) / var(--level5));
  right: calc(var(--g100) / var(--level2));
  top: calc(var(--g100) / var(--level1));
  width: calc(var(--g100) / var(--level5));
}

#gld span:nth-child(7) {
  bottom: calc(var(--g100) / var(--level3));
  height: calc(var(--g100) / var(--level6));
  right: calc(var(--g100) / var(--level2));
  width: calc(var(--g100) / var(--level6));
}

#gld span:nth-child(8) {
  bottom: calc(var(--g100) / var(--level3));
  height: calc(var(--g100) / var(--level7));
  left: calc(var(--g100) + var(--g100) / var(--level4));
  width: calc(var(--g100) / var(--level7));
}

#gld span:nth-child(9) {
  bottom: calc(var(--g100) / var(--level3) + var(--g100) / var(--level7));
  height: calc(var(--g100) / var(--level8));
  left: calc(var(--g100) + var(--g100) / var(--level4));
  width: calc(var(--g100) / var(--level8));
}

#gld span:nth-child(10) {
  bottom: calc(var(--g100) / var(--level3) + var(--g100) / var(--level7) + calc(var(--g100) / var(--level10)));
  height: calc(var(--g100) / var(--level9));
  left: calc(var(--g100) + var(--g100) / var(--level4) + calc(var(--g100) / var(--level8)));
  width: calc(var(--g100) / var(--level9));
}

При желании можно еще некоторые конструкции вынести в переменные.

document.body.onclick = function() {
  this.classList.toggle('clr');
}
:root {
  --black: #000;
  --white: #fff;
  --g100: 50vmin;
  --gold: 1.618033;
  --gold1: calc(var(--gold));
  --gold2: calc(var(--gold) * var(--gold1));
  --gold3: calc(var(--gold) * var(--gold2));
  --gold4: calc(var(--gold) * var(--gold3));
  --gold5: calc(var(--gold) * var(--gold4));
  --gold6: calc(var(--gold) * var(--gold5));
  --gold7: calc(var(--gold) * var(--gold6));
  --gold8: calc(var(--gold) * var(--gold7));
  --gold9: calc(var(--gold) * var(--gold8));
  --gold10: calc(var(--gold) * var(--gold9));
  --level1: calc(var(--g100) / var(--gold1));
  --level2: calc(var(--g100) / var(--gold2));
  --level3: calc(var(--g100) / var(--gold3));
  --level4: calc(var(--g100) / var(--gold4));
  --level5: calc(var(--g100) / var(--gold5));
  --level6: calc(var(--g100) / var(--gold6));
  --level7: calc(var(--g100) / var(--gold7));
  --level8: calc(var(--g100) / var(--gold8));
  --level9: calc(var(--g100) / var(--gold9));
  --level10: calc(var(--g100) / var(--gold10));
}

*,
html,
body {
  box-sizing: border-box;
  font-size: 0;
  margin: 0;
  padding: 0;
}

body {
  background: var(--black);
  display: grid;
  height: 100vh;
  place-items: center;
}

body.clr {
  background: var(--white);
}

#gld {
  box-shadow: 0 0 0 .2vmin var(--white) inset;
  display: flex;
  position: relative;
  height: var(--g100);
  width: calc(var(--g100) * var(--gold1));
}

.clr #gld {
  box-shadow: 0 0 0 .2vmin var(--black) inset;
}

#gld span {
  border: .1vmin solid var(--white);
  height: var(--g100);
  position: absolute;
  width: var(--g100);
}

.clr #gld span {
  border: .1vmin solid var(--black);
}

#gld span:nth-child(2) {
  height: var(--level1);
  right: 0;
  width: var(--level1);
}

#gld span:nth-child(3) {
  bottom: 0;
  height: var(--level2);
  right: 0;
  width: var(--level2);
}

#gld span:nth-child(4) {
  bottom: 0;
  height: var(--level3);
  right: var(--level2);
  width: var(--level3);
}

#gld span:nth-child(5) {
  bottom: var(--level3);
  height: var(--level4);
  left: var(--g100);
  width: var(--level4);
}

#gld span:nth-child(6) {
  height: var(--level5);
  right: calc(var(--g100) / var(--gold2));
  top: calc(var(--g100) / var(--gold1));
  width: calc(var(--g100) / var(--gold5));
}

#gld span:nth-child(7) {
  bottom: calc(var(--g100) / var(--gold3));
  height: calc(var(--g100) / var(--gold6));
  right: calc(var(--g100) / var(--gold2));
  width: calc(var(--g100) / var(--gold6));
}

#gld span:nth-child(8) {
  bottom: calc(var(--g100) / var(--gold3));
  height: calc(var(--g100) / var(--gold7));
  left: calc(var(--g100) + var(--level4));
  width: calc(var(--g100) / var(--gold7));
}

#gld span:nth-child(9) {
  bottom: calc(var(--level3) + var(--level7));
  height: var(--level8);
  left: calc(var(--g100) + var(--level4));
  width: var(--level8);
}

#gld span:nth-child(10) {
  bottom: calc(var(--level3) + var(--level7) + var(--level10));
  height: var(--level9);
  left: calc(var(--g100) + var(--level4) + var(--level8));
  width: var(--level9);
}

A: Разделить на fi=1.618033 в четвертой степени
Или умножить на 1-fi=0.618033 в четвёртой степени  (свойство этого самого золотого сечения)


Q: How to save a file name in my DB when I download or add a file into my local machine download folder in Laravel. any idea for this thing I want to save a file name into DB when it is downloaded or added into my local system folder.How can I perform this logic. any idea..... thanks for advance

A: you could just use the php function glob() to get all filenames from the download directory. then setup a cronjob for every 5m or whatever interval you want where you save the names to your database.


Q: About soldering wire for sophicated instruments What kind of soldering wire is used for soldering sophisticated instruments Like Transmission electron Microscopy (TEM) or electrochemical instruments? Is any high quality or alloy free wire required?

A: TL;DR - Use 63/37 Tin-Lead solder whenever possible. It has been extensively tested for reliability and is the preferred alloy for aerospace and military applications.

To answer this fully and correctly we would need to know a great deal more about the specific components used, operational conditions, and needs for ROHS compliance. Base metals, solder working temperature, and operational temperature/conditions can all play a part.
In general terms, you will want to select a eutectic alloy for any high reliability need. Without getting too bogged down in technicals, "eutectic" means it transitions directly between solid and liquid at a single temperature. This improves reliability by dramatically limiting the chances of inconsistencies and micro-fractures in the joint.
Assuming there is nothing that would exclude the use of leaded solder (e.g. ROHS compliance, high operational temp) or otherwise require special alternative alloys (e.g. silver or gold base metal), 63/37 Sn/Pb is almost always the best choice. It's eutectic, relatively low cost, has a low working temperature, and has extremely low odds of tin whisker formation.
The field of lead-free solder is a rapidly developing one and too broad to approach recommendations without far more info. Since it is a relatively young field, reliability testing documentation is limited and often contradictory. Suffice to say if you don't need it, don't use it. If you do need it, you will need to do some research as to which of near countless alloy choices will be best suited for your application. 95.6/3.5/0.9 Sn/Ag/Cu is determined by NIST to be truly eutectic, so it may be a good place to start.


Q: What is the meaning of "comprising the system" In a thermodynamics book, I came across the following sentence:

An extrinsic property is a property that is independent of the nature
  of the media comprising the system.

However, what does that mean by "the media comprising the system". Is it the media that the system lives, or the type of the media that the system has ?
Edit:
Media means medium in here.

A: An extrinsic property is a property that is independent of the nature of the media comprising the system.
means: the nature of the media that makes up the system.
or: the nature of the media that the system is comprised of, or made up of.
The process consists of two steps. [Merriam Webster for consist]
The process is made up of two steps. [Merriam Webster made up of]
In English, learners can be confused about the active and passive here:
the media comprises the system.
the system is comprised of the media.
They mean the same thing.
So in this:
An extrinsic property is a property that is independent of the nature of the media comprising the system.
The nature of the medium is properties A, B and C: they make up the system. Anything (any property) outside of that is an extrinsic property.


Q: Reading off only a certain part of the argument of a newcommand I am using the glossaries-extra package for my list of symbols. For some reason not relevant here I have defined a new command
\newcommand{\symb}[3][]{%
\glsxtrnewsymbol[#1]{#2}{#3}%
 }

such that my glossary entries are in the form:
\symb[description={Set of Smooth Vector Fields}]{vfs}{\ensuremath{\mathfrak{X}}}

I would like to "transfer" these to my university's thesis template, where they don't use the glossaries package, instead they define an environment where symbols should be entered as:
\begin{symbols}

\sym{\ensuremath{\mathfrak{X}}}{Set of Smooth Vector Fields}

\end{symbols}

This is simply a tabbing environment, it directly prints whatever you write down in the arguments of the command \sym. So my plan was to define something like
\renewcommand{\symb}[3][]{%
\glsxtrnewsymbol[#1]{#2}{#3}%
\sym{#3}{\glsdesc{#2}}%
}

This works except that using glossaries package somehow messes with another part of the university's style file. Because of this I would like to define
 \renewcommand{\symb}[3][]{%
            \sym{#3}{#1}%
    }

However I do not want to have "description={Set of Smooth Vector Fields}" for the second argument, I want to have "Set of Smooth Vector Fields". Is there a way to extract only the part "Set of Smooth Vector Fields" from the second argument of \symb?
Solution: A simplified version of @Schrödinger's cat's solution is working for me:
\newcommand{\symb}[3][]{%
\def\mysplit##1=##2{\sym{#3}{##2}}%
\expandafter\mysplit#1%
}

A: This is something that does that. Obviously I do not have your \sym command, so I use something for it which shows that it got the arguments right.
\documentclass{article}
\usepackage{amsfonts}
\def\forgetit{}
\newcommand{\symb}[3][]{%
\glsxtrnewsymbol[#1]{#2}{#3}%
}
\newcommand{\sym}[2]{first argument=\ensuremath{#1},second argument=#2}
\renewcommand{\symb}[3][\forgetit]{%
\def\mysplit##1=##2;{\def\mylast{##2}}%
\ifx#1\forgetit
\sym{#3}{empty}%
\else
\expandafter\mysplit#1;%
\sym{#3}{\mylast}%
\fi
}
\begin{document}
\symb[description={Set of Smooth Vector Fields}]{vfs}{\ensuremath{\mathfrak{X}}}

\symb{vfs}{\ensuremath{\mathfrak{X}}}
\end{document}

This assumes that, whenever the first argument is nonempty, it contains an = sign. You can make it immune against that, but then I would recommend using some key management system. For instance, if you are already loading pgf it will be very simple.

A: With the following code, the redefined routine \symb acts as follows:
Arguments are passed to \glsxtrnewsymbol untouched/as they are.
Arguments are passed to \sym after extracting the description from \symb's optional argument as follows:
In case that argument does not contain the leading phrase "description=", it is passed as is. (Space-tokens surrounding the entire phrase and/or a space-token between "description" and "=" are taken into account.)
In case that argument does contain the leading phrase "description=", that phrase gets removed.

*

*In case the remainder consists only of space-tokens or nothing, the extraction-result will be empty/will not consist of any tokens at all.

*In case the remainder consists of a single non-delimited argument, i.e., either of a single non-brace-token or of a set of tokens nested in braces, one level of braces surrounding the entire remainder will be removed if present, then space-tokens surrounding the entire remainder will be removed.

*In case the remainder consists of something else than just a single non-delimited argument, no braces will be removed but spaces surrounding the entire remainder will be removed.

As \sym and \glsxtrnewsymbol are not available to me, I provided "dummy-definitions" which do nothing but deliver their arguments in detokenized fashion, nested in angle brackets.
I did all this off the cuff, so no warranties. ;-)
Please also notice my comment about your non-redefined \symb-routine and about nesting arbitrary material in curly braces { and } when passing it to another macro where it forms an optional argument.
The whole "mechanism" is implemented without using whatsoever \if.....\else...\fi. Therefore the meachnism will not be confused by macro-arguments that contain unmatched \if or \else or \fi.
\documentclass{article}
\makeatletter
%%=============================================================================
%% Check whether argument is empty:
%%=============================================================================
%% \UD@CheckWhetherNull{<Argument which is to be checked>}%
%%                     {<Tokens to be delivered in case that argument
%%                       which is to be checked is empty>}%
%%                     {<Tokens to be delivered in case that argument
%%                       which is to be checked is not empty>}%
%%
%% Due to \romannumeral0-expansion the result is delivered after two
%% expansion-steps/after two "hits" by \expandafter.
%%
%% The gist of this macro comes from Robert R. Schneck's \ifempty-macro:
%% <https://groups.google.com/forum/#!original/comp.text.tex/kuOEIQIrElc/lUg37FmhA74J>
%%
\newcommand\UD@CheckWhetherNull[1]{%
  \romannumeral0\expandafter\@secondoftwo\string{\expandafter
  \@secondoftwo\expandafter{\expandafter{\string#1}\expandafter
  \@secondoftwo\string}\expandafter\@firstoftwo\expandafter{\expandafter
  \@secondoftwo\string}\@firstoftwo\expandafter{} \@secondoftwo}%
  {\@firstoftwo\expandafter{} \@firstoftwo}%
}%
%%=============================================================================
%% Check whether argument is blank (empty or only spaces):
%%=============================================================================
%% -- Take advantage of the fact that TeX discards space tokens when
%%    "fetching" _un_delimited arguments: --
%% \UD@CheckWhetherBlank{<Argument which is to be checked>}%
%%                      {<Tokens to be delivered in case that
%%                        argument which is to be checked is blank>}%
%%                      {<Tokens to be delivered in case that argument
%%                        which is to be checked is not blank}%
\newcommand\UD@CheckWhetherBlank[1]{%
  \romannumeral\expandafter\expandafter\expandafter\@secondoftwo
  \expandafter\UD@CheckWhetherNull\expandafter{\@firstoftwo#1{}.}%
}%
%%=============================================================================
%% Exchange two arguments. (From each argument an outermost level of
%% surrounding braces will be removed if present.)
%%=============================================================================
\newcommand\UD@Exchange[2]{#2#1}%
%%=============================================================================
%% Check whether argument's leading tokens form a specific
%% token-sequence that does not contain explicit character tokens of
%% category code 1 or 2:
%%=============================================================================
%% \UD@CheckWhetherLeadingTokens{<argument which is to be checked>}%
%%                              {<a <token sequence> without explicit
%%                                character tokens of category code
%%                                1 or 2>}%
%%                              {a <single non-space token> that does
%%                                _not_ occur in <token sequence> >}%
%%                              {<internal token-check-macro>}%
%%                              {<tokens to be delivered in case
%%                                <argument which is to be checked> has
%%                                <token sequence> as leading tokens>}%
%%                              {<tokens to be delivered in case
%%                                <argument which is to be checked>
%%                                does not have <token sequence> as
%%                                leading tokens>}%
\newcommand\UD@CheckWhetherLeadingTokens[4]{%
  \romannumeral0\UD@CheckWhetherNull{#1}%
  {\UD@Exchange{ }\expandafter\@secondoftwo}%
  {\expandafter\@secondoftwo\string{\expandafter
   \UD@@CheckWhetherLeadingTokens#4#3#1#2}{}}%
}%
\newcommand\UD@@CheckWhetherLeadingTokens[1]{%
  \expandafter\UD@CheckWhetherNull\expandafter{\@firstoftwo{}#1}%
  {\UD@Exchange{\@firstoftwo}}{\UD@Exchange{\@secondoftwo}}%
  {\UD@Exchange{ }{\expandafter\expandafter\expandafter\expandafter
   \expandafter\expandafter\expandafter}\expandafter\expandafter
   \expandafter}\expandafter\@secondoftwo\expandafter{\string}%
}%
%%=============================================================================
%% \UD@internaltokencheckdefiner{<internal token-check-macro>}%
%%                              {<token sequence>}%
%% Defines <internal token-check-macro> to snap everything
%% until reaching <token sequence>-sequence and spit that out
%% nested in braces.
%%=============================================================================
\newcommand\UD@internaltokencheckdefiner[2]{%
  \@ifdefinable#1{\long\def#1##1#2{{##1}}}%
}%
%%=============================================================================
\UD@internaltokencheckdefiner{\UD@ExtractDescriptionEqual}{description=}%
\UD@internaltokencheckdefiner{\UD@ExtractDescriptionSpaceEqual}{description =}%
\UD@internaltokencheckdefiner{\UD@ExtractDescriptionEqualSpace}{description= }%
\UD@internaltokencheckdefiner{\UD@ExtractDescriptionSpaceEqualSpace}{description = }%
\UD@internaltokencheckdefiner{\UD@ExtractSpaceDescriptionEqual}{ description=}%
\UD@internaltokencheckdefiner{\UD@ExtractSpaceDescriptionSpaceEqual}{ description =}%
\UD@internaltokencheckdefiner{\UD@ExtractSpaceDescriptionEqualSpace}{ description= }%
\UD@internaltokencheckdefiner{\UD@ExtractSpaceDescriptionSpaceEqualSpace}{ description = }%
\UD@internaltokencheckdefiner{\UD@ExtractSpace}{ }%
%%=============================================================================
%% Trim all leading and trailing spaces:
%%=============================================================================
\newcommand\UD@RemoveSpaces[1]{%
   \romannumeral0\@firstofone{\UD@TrimTrailSpaceLoop{#1}.#1\UD@Bizarre} \UD@Bizarre\relax\UD@Bizarre
}%
\@ifdefinable\UD@TrimTrailSpaceLoop{%
  \long\def\UD@TrimTrailSpaceLoop#1#2 \UD@Bizarre#3\relax\UD@Bizarre{%
     \UD@CheckWhetherNull{#3}{%
       \UD@TrimLeadSpaceLoop{#1}%
     }{%
       \@firstofone{\expandafter\UD@TrimTrailSpaceLoop\expandafter{\@gobble#2}#2\UD@Bizarre} \UD@Bizarre\relax\UD@Bizarre
     }%
  }%
}%
\@ifdefinable\UD@gobblespace{%
  \@firstofone{\def\UD@gobblespace} {}%
}%
\newcommand\UD@TrimLeadSpaceLoop[1]{%
  \UD@CheckWhetherLeadingTokens{#1}{ }{.}{\UD@ExtractSpace}{\expandafter\UD@TrimLeadSpaceLoop\expandafter{\UD@gobblespace#1}}{ #1}%
}%
%%=============================================================================
%% Extract description:
%%=============================================================================
\newcommand\UD@ExtractDescription[1]{%
  \romannumeral0%
  \UD@CheckWhetherLeadingTokens{#1}{ description = }{.}{\UD@ExtractSpaceDescriptionSpaceEqualSpace}{%
    \expandafter\UD@ExtractDescriptionCheckArgAmount\expandafter{\UD@ExtractSpaceDescriptionSpaceEqualSpace#1}%
  }{%
    \UD@CheckWhetherLeadingTokens{#1}{ description= }{.}{\UD@ExtractSpaceDescriptionEqualSpace}{%
      \expandafter\UD@ExtractDescriptionCheckArgAmount\expandafter{\UD@ExtractSpaceDescriptionEqualSpace#1}%
    }{%
      \UD@CheckWhetherLeadingTokens{#1}{ description =}{.}{\UD@ExtractSpaceDescriptionSpaceEqual}{%
        \expandafter\UD@ExtractDescriptionCheckArgAmount\expandafter{\UD@ExtractSpaceDescriptionSpaceEqual#1}%
      }{%
        \UD@CheckWhetherLeadingTokens{#1}{ description=}{.}{\UD@ExtractSpaceDescriptionEqual}{%
          \expandafter\UD@ExtractDescriptionCheckArgAmount\expandafter{\UD@ExtractSpaceDescriptionEqual#1}%
        }{%
          \UD@CheckWhetherLeadingTokens{#1}{description = }{.}{\UD@ExtractDescriptionSpaceEqualSpace}{%
            \expandafter\UD@ExtractDescriptionCheckArgAmount\expandafter{\UD@ExtractDescriptionSpaceEqualSpace#1}%
          }{%
            \UD@CheckWhetherLeadingTokens{#1}{description= }{.}{\UD@ExtractDescriptionEqualSpace}{%
              \expandafter\UD@ExtractDescriptionCheckArgAmount\expandafter{\UD@ExtractDescriptionEqualSpace#1}%
            }{%
              \UD@CheckWhetherLeadingTokens{#1}{description =}{.}{\UD@ExtractDescriptionSpaceEqual}{%
                \expandafter\UD@ExtractDescriptionCheckArgAmount\expandafter{\UD@ExtractDescriptionSpaceEqual#1}%
              }{%
                \UD@CheckWhetherLeadingTokens{#1}{description=}{.}{\UD@ExtractDescriptionEqual}{%
                  \expandafter\UD@ExtractDescriptionCheckArgAmount\expandafter{\UD@ExtractDescriptionEqual#1}%
                }{ #1}%
              }%
            }%
          }%
        }%
      }%
    }%
  }%
}%
\newcommand\UD@ExtractDescriptionCheckArgAmount[1]{%
  \expandafter\UD@CheckWhetherBlank\expandafter{\@gobble#1}{ }{%
    \expandafter\UD@CheckWhetherBlank\expandafter{\@gobbletwo#1}{%
       \UD@Exchange{ }{\expandafter\expandafter\expandafter\expandafter\expandafter\expandafter\expandafter}%
       \expandafter\UD@RemoveSpaces\expandafter{\@secondoftwo#1}%
    }{%
      \UD@Exchange{ }{\expandafter\expandafter\expandafter\expandafter\expandafter\expandafter\expandafter}%
      \expandafter\UD@RemoveSpaces\expandafter{\@firstoftwo{}#1}%
    }%
  }%
}%
%%=============================================================================
%% Your definition of \symb with a modification:
%% When passing arbitrary arguments as optional arguments, I strongly recommend
%% nesting them in braces for ensuring that nesting of square brackets won't
%% lead to problems:
%%=============================================================================
\newcommand{\symb}[3][]{%
  \glsxtrnewsymbol[{#1}]{#2}{#3}%  <- Here the content of #1 is arbitrary.
}%                              %     Problems due to nested square brackets
                                %     might occur in case #1 contains
                                %     [ or ].
                                %     Some day someone might do something like
                                %     \symb[{description=optional\macro[macro's optional]}]{...}{...}.
                                %     Therefore nest #1 in braces.
                                %     These braces will be removed by LaTeX
                                %     when processing \glsxtrnewsymbol's
                                %     optional argument.
                                %     They prevent confusion when it comes
                                %     to nesting optional arguments within
                                %     optional arguments.
%%=============================================================================
%% Redefinition of  \symb:
%%=============================================================================
\renewcommand{\symb}[3][]{%
  \romannumeral0%
  \expandafter\expandafter\expandafter\UD@Exchange
  \expandafter\expandafter\expandafter{%
  \expandafter\expandafter\expandafter{\UD@ExtractDescription{#1}}}{ \sym{#3}}%
  \glsxtrnewsymbol[{#1}]{#2}{#3}%
}%
%%=============================================================================
%% Dummy-definition for \glsxtrnewsymbol which displays the arguments verbatim
%%=============================================================================
\newcommand\glsxtrnewsymbol[3][]{%
  \par\noindent
  \texttt{\string\glsxtrnewsymbol}'s optional argument: $\langle$\texttt{\detokenize{#1}}$\rangle$
  \par\noindent
  \texttt{\string\glsxtrnewsymbol}'s mandatory argument 1: $\langle$\texttt{\detokenize{#2}}$\rangle$
  \par\noindent
  \texttt{\string\glsxtrnewsymbol}'s mandatory argument 2: $\langle$\texttt{\detokenize{#3}}$\rangle$
  \par
}%
%%=============================================================================
%% Dummy-definition for \sym which displaysthe arguments verbatim
%%=============================================================================
\newcommand\sym[2]{%
  \par\noindent
  \texttt{\string\sym}'s mandatory argument 1: $\langle$\texttt{\detokenize{#1}}$\rangle$
  \par\noindent
  \texttt{\string\sym}'s mandatory argument 2: $\langle$\texttt{\detokenize{#2}}$\rangle$
  \par
}%
\makeatother

\begin{document}
\vspace*{-1in}%
\noindent
\texttt{\detokenize{\symb[description={Set of Smooth Vector Fields}]{vfs}{\ensuremath{\mathfrak{X}}}}}:

\smallskip

\symb[description={Set of Smooth Vector Fields}]{vfs}{\ensuremath{\mathfrak{X}}}

\bigskip

\noindent\null\hrulefill\null

\bigskip

\noindent
\texttt{\detokenize{\symb[ description = { Set of Smooth Vector Fields } ]{vfs}{\ensuremath{\mathfrak{X}}}}}:

\smallskip

\symb[ description = { Set of Smooth Vector Fields } ]{vfs}{\ensuremath{\mathfrak{X}}}

\bigskip

\noindent\null\hrulefill\null

\bigskip

\noindent
\texttt{\detokenize{\symb[description = Set of Smooth Vector Fields ]{vfs}{\ensuremath{\mathfrak{X}}}}}:

\smallskip

\symb[description = Set of Smooth Vector Fields ]{vfs}{\ensuremath{\mathfrak{X}}}

\bigskip

\noindent\null\hrulefill\null

\bigskip

\noindent
\texttt{\detokenize{\symb{vfs}{\ensuremath{\mathfrak{X}}}}}:

\smallskip

\symb{vfs}{\ensuremath{\mathfrak{X}}}

\bigskip

\noindent\null\hrulefill\null

\bigskip

\noindent
\texttt{\detokenize{\symb[whatsoever]{vfs}{\ensuremath{\mathfrak{X}}}}}:

\smallskip

\symb[whatsoever]{vfs}{\ensuremath{\mathfrak{X}}}

\end{document}


Q: date format is not working monthpicker I have a month picker in my form in laravel 4.2. While changing the month, the month and year are shown like 05/2015. But i need it to be in the format May, 2015.
{{ HTML::style('public/asset/css/smoothness/jquery-ui.css') }}
{{ HTML::style('public/asset/css/MonthPicker.css') }}
{{ HTML::script('http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js') }}
{{ HTML::script('http://code.jquery.com/ui/1.10.2/jquery-ui.js') }}
{{ HTML::script('public/asset/js/MonthPicker.min.js') }}
{{ HTML::script('public/asset/js/MonthPicker.js') }}
Query(document).ready(function() {
$("#SearchVal").val('');

var currentYear = (new Date).getFullYear();

var _picker = jQuery('#SearchVal').MonthPicker({

    ShowIcon: false

            });

A: You can do that manually on change event :
var monthsLabels = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'June', 'July', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']

var picker = jQuery('#SearchVal').MonthPicker({
    ShowIcon: false,
    OnAfterChooseMonth: function(){
        var elts = picker.val().split('/');
        picker.val(monthsLabels[parseInt(elts[0])-1]+', '+elts[1]);
    }
});

jsFiddle

A: hello bro try to see this will help you it's about Datepicker


Q: Probability density function of max(0, z) Question
The full question is from Exercise 4.6 in Statistical Inference (Casella, Berger). It is

A and B agree to meet at certain place between 1 PM to 2 PM. Suppose they arrive at meeting place independently and randomly during the hour. Find the distribution of the length of time that A waits for B (If B arrives before A, define A's waiting to be 0)

My answer
Here we can assume $A$ and $B$ to be uniform (that is $U(0,1)$) and we are interested to find the PDF of $T = max(0, B-A)$ where
$$
f(a, b) = 1
$$
To solve this, what I did is that first find out the PDF of $C = B - A$ as shown below
Define $D = B + A$, then joint distribution of (C, D) will be
$$
g(c, d) = f\left(\frac{d-c}{2}, \frac{d+c}{2}\right)\left|\begin{vmatrix}\frac{-1}{2}&\frac{1}{2}\\\frac{1}{2}&\frac{1}{2}\end{vmatrix}\right|
$$
that is $g(c,d) = \frac{1}{2}$ where $-1<c<0$ and $-c<d<c+2$, $0<c<1$ and $c<d<2-c$
Now the marginal distribution of $C$ will be
$$
h(c) =
\begin{cases}
1 + c & \text{if $-1 < c < 0$} \\
1 - c & \text{if $0 < c < 1$}
\end{cases}
$$
Now our required variable $T$ will be $T = \max(0, C)$ and this is where I am stuck that is how to find out the distribution of $T$.

A:
To solve this, what I did is that first find out the PDF of C=B−A as shown below

Indeed, or you could do $$\begin{align}f_{A,B-A}(a,c) &=\begin{vmatrix}\partial a/\partial a&\partial a/\partial c\\\partial (a+c)/\partial a&\partial(a+c)/\partial c\end{vmatrix} f_{A,B}(a, a+c)\\f_{B-A}(c) &=\int_\Bbb R f_A(a)f_B(a+c)\,\mathrm d a\\[1ex]&=\int_\Bbb R \mathbf 1_{0<a<1, 0<a+c<1}\,\mathrm d a\\[1ex]&= \int_{-c}^1 \mathbf 1_{-1\leqslant c<0}\,\mathrm d a+\int_0^{1-c}\mathbf 1_{0\leqslant c\leqslant 1}\,\mathrm d a\\[1ex]&=(1+c)\,\mathbf 1_{-1\leqslant c<0}+(1-c)\,\mathbf 1_{0\leqslant c\leqslant 1} \end{align}$$

Now our required variable $T$ will be $T=max(0,C)$ and this is where I am stuck that is how to find out the distribution of $T$.

The issue is that $T=0$ is the event $C\leq 0$, which will not have a probability density.  Rather it will have a probability mass of $1/2$ .
You might use the Dirac Delta generalised function for this.
$$f_T(t) = \tfrac 12\delta(t)+(1-t)\,\mathbf 1_{0<t\leqslant 1}$$


Q: Google Apps Script: Server error occurs when using a UiApp and a server handler in new sheets AND there is a library I converted my sheets from the old to the new sheets as the code started creating sheets in the new version which was causing it to fail. After converting, I am now getting another error which I cannot find a solution for.
The error seems to be when using UiApp which calls a server handler and there is a library attached to the project. The error occurs even when there is no code in the library. The error occurring is:
Server Error: We're sorry, a server error occurred. Please wait a bit and try again.
Steps to reproduce
(1). Create 2 new sheets, use one as the library and one as the test sheet
(2). In the library, add a new version to the project then add the project as a library in the test sheet. There should be no code in the library (doesn't really matter either way).
(3). In the test sheet, add the following code:
function test() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var app = UiApp.createApplication();

  // create a button and handler
  var buttonHandler = app.createServerHandler("buttonTest");
  var button = app.createButton("Button Test");
  button.addClickHandler(buttonHandler)

  app.add(button)
  ss.show(app); // Display the app
}
function buttonTest(e) {
  // nothing here is executed
}

(4). Run the test code
The following error is displayed:
Server Error: We're sorry, a server error occurred. Please wait a bit and try again.
If the library is removed then it will run as expected

A: The UiApp is deprecated. That would be creating the server error. Sometimes the UiApp functions still work (like the chart service) but the output crashes. The googlescript library functionality should still work.
https://developers.google.com/apps-script/reference/ui/ui-app?hl=en
The html service should be a replacement for the UiApp but unfortunately it does not cover all the same functionality.
https://developers.google.com/apps-script/guides/html/


Q: Trigonometry in the DE Just a simple undergrad physics student asking them mathematicians.
I have a very simple 2nd order homogeneous DE of the form:
$$y''=-a^2y$$
So, a solution will be of the form $$y(t)=c_1 e^{+iat}+c_2 e^{-iat} \quad (1)$$
which you can rewrite to $$y(t)=d_1\cos(at)+d_2 \sin(at) \quad (2)$$
The final answer of the problem has the form of $C \sin(at+d)$, where $d$ is a phase term. No initial conditions are given.
My question is, can eq. (2) be rewritten in some way that only a sine term emerges, with a constant $d$ appearing in there? I looked at some trig. relations and couldn't see a quick way. I think the initial conditions have to be used. What do you think?
(A teaching assistent told me it could be done, but I distrust her advice a little since she has given me wrong answers before)

A: Expand on the trig expression you get from the answer:
$$\sin(at+d) = \sin(at) \cos(d) + \cos(at) \sin(d)$$
So you can take eqn.(2) and factor out the constant $C = \sqrt{d_1^2 + d_2^2}$ and then pick $d$ so that $\cos(d) = d_1/C$ and $\sin(d) = d_2/C$.

A: As far as I know for a suitable $\eta$, we can have $a\sin(x)+b\cos(x)=\sqrt{a^2+b^2}\sin(x+\eta)$


Q: How to split/cut till specific path (directory path )of string in perl Input : "/abcd/prod/Cid/1234/Did" or "/abcd/prod/Cid/1234/Did/Pid/234"
Output: "/abcd/prod/Cid/1234/"  (Only till 4th word, considering '/' is the delimiter)
How to slice and get above using perl

A: As one-liner :
$ perl -F'/' -lane 'print join "/", @{F[0..4]}' <<< "/abcd/prod/Cid/1234/Did"

As a script :
while (<>) {
    chomp $_;
    my @F = split(m[/], $_, 0);
    print join('/', @F[0..4]), "\n";
}

 Output :
/abcd/prod/Cid/1234


Q: Subscripting a string in Javascript I have a data in the object section_data.title and i am trying to use str.sup() where str=section_data.title; and str holds following data:

str="Not less than 30 net ft2 (2.8 net m2) per patient in a
  hospital or nursing    home, or not less than 15 net ft2 (1.4 net
  m2) per resident in a limited care facility, shall be provided within the aggregated area of corridors, patient rooms, treatment
  rooms, lounge or dining areas, and other similar areas on each side of
  the horizontal exit. On stories not housing bed or litterborne
  patients, not less than 6 net ft2 (0.56 net m2) per occupant
  shall be provided on each side of the horizontal exit for the total
  number of occupants in adjoining compartments."

Now I want to add superscript for the bold words indicated above (e.g ft2). How can I do this using str.sup() or are there any other alternative method to do so in javascript? Or any other tricks?

A: String in javascript is not formatted. You can only do that when you output to HTML. So basically you must write it like this
var str = "Not less than 30 net ft2 (2.8 net m2)";
document.write(str);

You can do a find and replace for all string contain ft2 and m2 turn them into ft2 and m2
str.replace(/ft2/g,"ft2");  //But it not safe...


Q: how to apply constraint by Stored procedures that ID should start with 'E' and has 2 numerics aftarwards? EID should only be inserted if it starts with 'E' and has 2 numerics aftarwards ....
i was trying to write a procedure for the purpose like:
create proc emp_checks(@eid varchar(20), @name varchar(20),@age int, @salary int, @city varchar(20))
AS
Begin
Declare @citycount int= (select count(*) from employee where @city=city)

if (@citycount < 2 and @eid like 'E--%')
insert into employee values(@eid,@name,@age,@salary,@city)
else
print 'city exceeded'
End

here the issue is that -- or spaces would insert non-numerics also
here this code also includes few extras *just homework things :)

A: Why would you write a stored procedure?  MySQL now supports check constraints:
alter table employee add constraint chk_employee_eid
    check (eid regexp '^E[0-9]{2}')

Note that this allows anything after the first 3 characters.  If you don't want anything, then add $ to the pattern:
alter table employee add constraint chk_employee_eid
    check (eid regexp '^E[0-9]{2}$')


Q: TCP messages - Durable and fast solution tips? We use Spring integration for TCP socket communication with the hardware.
The client would be sending a sequence number to uniquely identify a message.
My requirement is to store these sequence numbers part of the socket message and validate them for non repetitive sequence numbers.
I went thru IdempotentReceiver, sounds like what i wanted.
But I need a durable and faster mechanism to store it, before unexpected shutdown of service and use the in memory cache for retrieving the latest sequence number.
Thank you in advance.!

A: You can use PropertiesPersistingMetadataStore for idempotent receiver:

The PropertiesPersistingMetadataStore is backed by a properties file and a PropertiesPersister.
By default, it only persists the state when the application context is closed normally. It implements Flushable so you can persist the state at will, be invoking flush().

See more in its JavaDocs.


Q: Contentflow auto resize not working Im using:
Contentflow 1.0.2
jquery 1.6.1
I'm trying use Contentflow using reflection and with maximum width/height so it covers all the screen without any scroll bar vertically or horizontally.
This example shows exactly what I wanna do, but it uses ImageFlow (another plugin)
http://themes.themegoods.com/keres_wp/?page_id=459
At this point my config is like this and everything works fine except that Contentflow doesn't resize when I change the browser size.
var cf = new ContentFlow('contentFlow', {
                    reflectionColor: "#000000",
                    circularFlow: false,
                    startItem: 0,
                    fixItemSize: true,
                    scaleFactor:1.5
                });


Q: ValidateUser of Forms Authentication issue I am using SharePoint 2007 Enterprise + Publishing portal template + Windows Server 2008. And I am developing using ASP.Net + C# + .Net 3.5 + VSTS 2008 on SharePoint Server 2007.  I am developing a custom Forms authentication based on Forms authentication interface. I am learning using Forms Authentication with SharePoint and my confusion is about this method -- ValidateUser of Forms Authentication, here is MSDN link,
http://msdn.microsoft.com/en-us/library/system.web.security.membershipprovider.validateuser.aspx
My confusions are about which component will call ValidateUser method?

*

*Do I need to call ValidateUser by myself (my application code), or depends on my needs (not always needed, depends on my application scenario);

*Is ValidateUser is called by SharePoint code (not my own application code), if yes, when (i.e. in what situations will SharePoint calls ValidateUser method, or say in other words, what operation in SharePoint will trigger invocation of this method)?

A: The ValidateUser will be called by the Login control on the SharePoint forms login page, so you do not have to call this method yourself, unless you are customizing the login page or creating some kind of login handler.

A: My confusions are about which component will call ValidateUser method?

It is called by the Login Control
  present in the page C:\Program
  Files\Common Files\microsoft
  shared\Web Server
  Extensions\12\TEMPLATE\LAYOUTS\login.aspx

Do I need to call ValidateUser by myself (my application code), or depends on my needs (not always needed, depends on my application scenario);

IF you want to Authenticate the user to SharePoint then ValidateUser has to be called/will be called.

Is ValidateUser is called by SharePoint code (not my own application code), if yes, when (i.e. in what situations will SharePoint calls ValidateUser method, or say in other words, what operation in SharePoint will trigger invocation of this method)?

To be exact SharePoint does not do
  authentication by itself it depends on
  the provider/ By default it  is
  configured to validate the user based
  on the Active Directory Windows
  authentication. Where as you can also
  configure it to validate aganist
  different store ( FBA as you have
  done).
Being said that ValidateUser method is
  automatically called by Login Control
  when you click on the Sign In
  button.Once the user has been
  validated it drops a cookie so that
  the further request form the browser
  goes to the Server as the
  authenticated request.

[Update : To answer your comment]My question is, if I customize SharePoint login page and not using ASP.Net Login control, and for anonymous user, if the anonymous user access specific content which is blocked for anonymous users, will ValidateUser be called automatically?

No, Only Case when the ValidateUser
  will be called is when you have a
  ASP.NET Login Control and when you
  click sign in button in it. Login
  control is nothing but a Custom
  Control that has Two TextBox, one
  Button and a Check Box, and if you
  don't want to use the default login
  control then you will have to somehow
  take the user name and password from
  the user and use the Validate method
  to authenticate him/her.

And to answer your second point ,

if you try to access  a item that is
  blocked for anonymous user then
  SharePoint will contact the provide to
  authenticate the user (Provider will
  provide you the Login Screen) to put
  it simple you will be redirected Login
  Page.

On a Side note : Do not attempt to customize the Login.aspx present it the Layouts folder, because it is not recommended to do any changes to the SharePoint files.


Q: Numba and KeyboardInterrupt Exception conflict I'm having a problem compiling KeyboardInterrupt exception using Continuum Numba module. Here's my data acquisition code:
@jit
def lockinmeasurement(x):
    Measurement=np.empty((0,5))
    XMeas=np.empty((0,2))
    event_handler = LoggingEventHandler()
    observer = Observer()
    observer.schedule(event_handler, path_to_watch, recursive=True)
    observer.start()
    try:
       while x:
           SQData=pd.read_csv(path_to_watch,sep=',',skiprows=14)
           Temp=SQData['Temperature (K)']
           Field=SQData['Field (Oe)']
           XMeas=np.append(XMeas,[[time.clock(),lockin.x]],axis=0)
           Measurement=np.append(Measurement,[[a,b,c,d,e]])
           p1.plot(XMeas,clear=True,label='Lockin X',pen='y')
           pg.QtGui.QApplication.processEvents()
           rd=pd.DataFrame(Measurement)
           rd.to_csv('fileout.csv',sep='\t',index=False)
           time.sleep(0.2)
    except KeyboardInterrupt:
       print('interrupted!')

lockinmeasurement(True)

The code compiles perfectly fine without '@jit', however when I'm trying to use numba it returns an error:
Traceback (most recent call last):
  File "C:\Anaconda3\lib\site-packages\numba\bytecode.py", line 231, in next
    info = BYTECODE_TABLE[opcode]
KeyError: 121

During handling of the above exception, another exception occurred:

lockinmeasurement(True)

  File "C:\Anaconda3\lib\site-packages\numba\dispatcher.py", line 165, in _compile_for_args
    return self.compile(sig)

  File "C:\Anaconda3\lib\site-packages\numba\dispatcher.py", line 303, in compile
    flags=flags, locals=self.locals)

  File "C:\Anaconda3\lib\site-packages\numba\compiler.py", line 595, in compile_extra
    return pipeline.compile_extra(func)

  File "C:\Anaconda3\lib\site-packages\numba\compiler.py", line 316, in compile_extra
    raise e

  File "C:\Anaconda3\lib\site-packages\numba\compiler.py", line 311, in compile_extra

    bc = self.extract_bytecode(func)
  File "C:\Anaconda3\lib\site-packages\numba\compiler.py", line 303, in extract_bytecode

    bc = bytecode.ByteCode(func=self.func)

  File "C:\Anaconda3\lib\site-packages\numba\bytecode.py", line 333, in __init__
    table = utils.SortedMap(ByteCodeIter(code))

  File "C:\Anaconda3\lib\site-packages\numba\utils.py", line 109, in __init__
    for i, (k, v) in enumerate(sorted(seq)):

  File "C:\Anaconda3\lib\site-packages\numba\bytecode.py", line 235, in next
    raise NotImplementedError(ts % tv)

NotImplementedError: offset=80 opcode=0x79 opname=SETUP_EXCEPT

Is there any way I can overcome this issue ?

A: Thanks to Travis' innovation teams' efforts numba is a great and powerful tool for scientific computing. One shall however take a due care to use it where feasible and where jit-compilation can bring some fruit to our hard and fast lives.
Numba Documentation states this explicitly, saying:

2.4.1.1. Constructs
  Numba strives to support as much of the Python language as possible, but some language features are not available inside Numba-compiled functions:- Function definition-
  Class definition-
  Exception handling (try .. except, try .. finally)-
  Context management (the with statement)-
  Comprehensions (either list, dict, set or generator comprehensions)-
  Generator delegation (yield from)
  The raise statement is supported in several forms:
raise (to re-raise the current exception)
raise SomeException
raise SomeException(<arguments>): in nopython mode, constructor arguments must be compile-time constants
  Similarly, the assert statement is supported with or without an error message.


Q: Material sidenav causing problem with translate and flex css properties So, currently working with my electron app having a sidenav structure like this:

<mat-drawer-container>
  <mat-drawer>parent sidenav</mat-drawer>

  <mat-drawer-content>
    parent content
    <mat-drawer-container>
      inside child container
      <mat-drawer>inside child sidenav</mat-drawer>
      <mat-drawer-content>
        inside child content
        <app-route>current problem occurs here</app-route>
      </mat-drawer-content>
    </mat-drawer-container>
  </mat-drawer-content>

</mat-drawer-container>

So, suppose at first route I'm having Html like this:

info

Nothing to show you here as your specified folders for checking music files are currently empty

Add new music search directories

Also scss:

@mixin widthheight100{
   width: 100%;
   height: 100%
}

.box-empty-container{
      position: relative;
      @include widthheight100() ;

      .box-empty-msg{
         position: absolute ;
         left: 50% ;
         top: 45% ;
         transform: translate(-50%, -50%);
         text-align: center;
       .box-empty-logo{
            span.material-icons{
               font-size: 2.5rem;
            }
       }

       .box-empty-title{
            font-family: 'jost-bold';
            font-size: 12pt;
       }

       .box-empty-subtitle{
            font-family: 'jost-regular';
            font-size: 10pt;
       }
}

I have tried to centralize div.box-empty-msg with both flex and translate method in scss and they are still not at center. When page loads this div is at center but when i open & close the sidenav it's position gets displaced form center. How can I solve this problem ?
Edit: Currently changed the scss style to postion: absolute strategy. Link here for similar code in stackblitz. It seems to work fine in stackblitz but in my actual project when screen size is large or medium the div.box-empty-msg is actually shifted some distance away from center. Also I think somehow in my project the sidenav is pushing the div tag away from center.

A: @ReneVanDerLende After thoroughly checking my project due to css properties set for mat-drawer-content as { width: 100% ; height: 100% } it interfered with the styles of box-empty-container, hence shifting that slightly towards right.


Q: Variable assigned in dispatch block coming back null I'm trying to make a network call run in a background thread so it doesn't freeze my app while it's waiting.
The call happens when I do:
nextTime = [myObj getNextTime];

I do an NSLog as soon as I get it, and that one works.
However, when I'm outside of the dispatch block, the same
NSLog prints out null.
myObj *current = ((myObj *)sortedArray[i]);
__block NSString *nextTime;
dispatch_queue_t queue =     dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0ul);
dispatch_async(queue, ^{
    nextTime = [myObj getNextTime];
    NSLog(@"inside%@",nextTime);
    dispatch_sync(dispatch_get_main_queue(), ^{

    });
});

NSLog(@"outside%@",nextTime);

Any ideas why the outer log is printing null? Am I doing something horribly wrong and I just missed it? Thanks!

A: That's because you're setting it inside an asynchronous block, and asynchronous blocks return immediately. If you look at the time stamps of the two logs, you'll see that the outer log is actually being posted before both the inner log, and the setting of the variable.
From the GCD docs on dispatch_async():

This function is the fundamental mechanism for submitting blocks to a
  dispatch queue. Calls to this function always return immediately after
  the block has been submitted and never wait for the block to be
  invoked. The target queue determines whether the block is invoked
  serially or concurrently with respect to other blocks submitted to
  that same queue. Independent serial queues are processed concurrently
  with respect to each other.

A: Your "outside" NSLog statement should actually go in that inner dispatch_async block that is set to run on the main thread, because that block will execute after you've set the value of nextTime. Any code you place below your asynchronous block call will likely execute way before the code inside the block.


Q: Trying to remove duplicates from large list of objects, keep certain one I have a large list of objects in Python that I'm storing in a text file (for lack of knowledge of how to use any other database for the present).
Currently there are 40,000 but I expect the list length eventually may exceed 1,000,000. I'm trying to remove duplicates, where duplicates are defined as different objects having the same value for a text string attribute, but keep the most recent version of that object (defined as having the highest value in another attribute).
What I want to make is a function that returns only objects 2 and 3 from the following list, reliably:
Object 1: text="hello"            ID=1
Object 2: text="hello"            ID=2
Object 3: text="something else"   ID=3

Doing this manually (looping through the list each time for each object) is too slow already and will get slower with O(l^2), so I need a smarter way to do it. I have seen hashing the objects and using the set function recommended multiple times, but I have two questions about this that I haven't found satisfactory answers to:

*

*How does hashing improve the efficiency to the degree it does?

*How can I do this and retain only the most recent such object? The examples I have seen all use the set function and I'm not sure how that would return only the most recent one.
EDIT: I can probably find good answers to question 1 elsewhere, but I am still stuck on question 2. To take another stab at explaining it, hashing the objects above on their text and using the set function will return a set where the objects chosen from duplicates are randomly chosen from each group of duplicates (e.g., above, either a set of (Object 2, Object 3) or (Object 1, Object 3) could be returned; I need (Object 2, Object 3)).

A: change to using a database ...
import sqlite3
db = sqlite3.connect("my.db")
db.execute("CREATE TABLE IF NOT EXISTS my_items (text PRIMARY KEY, id INTEGER);")
my_list_of_items = [("test",1),("test",2),("asdasd",3)]
db.execute_many("INSERT OR REPLACE INTO my_items (text,id) VALUES (?,?)",my_list_of_items)
db.commit()

print(db.execute("SELECT * FROM my_items").fetchall())

this may have maginally higher overhead in terms of time ... but you will save in RAM

A: Hashing is a well-researched subject in Computer Science. One of the standard uses is for implementing what Python calls a dictionary. (Perl calls the same thing a hash, for some reason. ;-) )
The idea is that for some key, such as a string, you can compute a simple numeric function - the hash value - and use that number as a quick way to look up the associated value stored in the dictionary.
Python has the built-in function hash() that returns the standard computation of this value. It also supports the __hash__() function, for objects that wish to compute their own hash value.
In a "normal" scenario, one way to determine if you have seen a field value before would be to use the field value as part of a dictionary. For example, you might stored a dictionary that maps the field in question to the entire record, or a list of records that all share the same field value.
In your case, your data is too big (according to you), so that would be a bad idea. Instead, you might try something like this:
seen_before = {}    # Empty dictionary to start with.

while ... something :
    info = read_next_record()   # You figure this out.
    fld = info.fields[some_field]  # The value you care about

    hv = hash(fld)     # Compute hash value for field.

    if hv in seen_before:
        print("This field value has been seen before")

    else:
        seen_before[hv] = True  # Never seen ... until NOW!

A: Could use a dict with the text as key and the newest object for each key as value.
Setting up some demo data:
>>> from collections import namedtuple
>>> Object = namedtuple('Object', 'text ID')
>>> objects = Object('foo', 1), Object('foo', 2), Object('bar', 4), Object('bar', 3)

Solution:
>>> unique = {}
>>> for obj in objects:
        if obj.text not in unique or obj.ID > unique[obj.text].ID:
            unique[obj.text] = obj

>>> unique.values()
[Object(text='foo', ID=2), Object(text='bar', ID=4)]


Q: How to run the backend server/code in re-frame template? Using lein re-frame template I see that there's a -main function that runs a jetty server for the backend code located in clj/. Using emacs I've been able to cider-jack-in-cljs and get the frontend running in the browser, hot reload works and all but I've tried to add routes to the routes function in handler.clj inside the clj/ and haven't been able to figure out how to get that "backend side" of things to work.

I found this other question sort of related but in that case the user just wanted to know why the clj/ folder was there, not how to run that code. I haven't been able to find any documentation so far, any help is greatly appreciated.
PD: I know that having the backend and frontend in the same project/repo is not recommended (it's mentioned in the other question I linked above) but I just want to get a simple "first app" working and running first and then hopefully get the backend out into another project/repo.

A: Assuming you created the project with something like lein new re-frame myapp +handler the code to start the server is on the file src/clj/myapp/server.clj
You can open the file and run cider-jack-in-clj, which will ask if you want to launch lein or shadow-cljs. Since it's a CLJ file, choose lein. Once CIDER starts, you can evaluate the -main function (eg. (-main)) to start the server.
You can open the URL at http://localhost:3000 and Jetty will serve the resources that are already compiled by shadow-cljs, so you'll see the same output as viewing the other port from CLJS directly.
Note that the backend code from the template starts the Jetty server but won't help with reloading the backend. To see how enable hot reloading for the backend, check https://github.com/ring-clojure/ring/wiki/Setup-for-development


Q: Bamboo Failing To Run Task - Null Pointer Exception I have had a set of Bamboo plans running for quite awhile but this morning Bamboo has decided to start throwing an exception when running them.  The instance of Bamboo is on Linux but the plans themselves are ran from a remote agent running Windows.  Specifically these are plans set to build .net framework mvc applications.
The plans fail at different tasks but both with the same error.  The error below fails while trying to restore nuget packages but another plan fails while attempting to run a copy command.  Running the nuget restore outside of Bamboo runs correctly.
I have tried cloning the plan and also reinstalled the remote agent but neither fixed the issue.
Error occurred while running Task 'Nuget(8)' of type com.atlassian.bamboo.plugins.scripttask:task.builder.command.
error   12-Aug-2020 09:40:17    com.atlassian.bamboo.task.TaskException: Failed to execute task
error   12-Aug-2020 09:40:17        at com.atlassian.bamboo.plugins.shell.task.AbstractShellBuildTask.execute(AbstractShellBuildTask.java:65)
error   12-Aug-2020 09:40:17        at com.atlassian.bamboo.plugins.shell.task.AbstractShellBuildTask.execute(AbstractShellBuildTask.java:39)
error   12-Aug-2020 09:40:17        at com.atlassian.bamboo.task.TaskExecutorImpl.lambda$executeTasks$3(TaskExecutorImpl.java:288)
error   12-Aug-2020 09:40:17        at com.atlassian.bamboo.task.TaskExecutorImpl.executeTaskWithPrePostActions(TaskExecutorImpl.java:221)
error   12-Aug-2020 09:40:17        at com.atlassian.bamboo.task.TaskExecutorImpl.executeTasks(TaskExecutorImpl.java:288)
error   12-Aug-2020 09:40:17        at com.atlassian.bamboo.task.TaskExecutorImpl.execute(TaskExecutorImpl.java:110)
error   12-Aug-2020 09:40:17        at com.atlassian.bamboo.build.pipeline.tasks.ExecuteBuildTask.call(ExecuteBuildTask.java:71)
error   12-Aug-2020 09:40:17        at com.atlassian.bamboo.v2.build.agent.DefaultBuildAgent.executeBuildPhase(DefaultBuildAgent.java:203)
error   12-Aug-2020 09:40:17        at com.atlassian.bamboo.v2.build.agent.DefaultBuildAgent.build(DefaultBuildAgent.java:175)
error   12-Aug-2020 09:40:17        at com.atlassian.bamboo.v2.build.agent.BuildAgentControllerImpl.lambda$waitAndPerformBuild$0(BuildAgentControllerImpl.java:122)
error   12-Aug-2020 09:40:17        at com.atlassian.bamboo.variable.CustomVariableContextImpl.withVariableSubstitutor(CustomVariableContextImpl.java:185)
error   12-Aug-2020 09:40:17        at com.atlassian.bamboo.v2.build.agent.BuildAgentControllerImpl.waitAndPerformBuild(BuildAgentControllerImpl.java:117)
error   12-Aug-2020 09:40:17        at com.atlassian.bamboo.v2.build.agent.DefaultBuildAgent$1.run(DefaultBuildAgent.java:126)
error   12-Aug-2020 09:40:17        at com.atlassian.bamboo.utils.BambooRunnables$1.run(BambooRunnables.java:48)
error   12-Aug-2020 09:40:17        at com.atlassian.bamboo.security.ImpersonationHelper.runWith(ImpersonationHelper.java:26)
error   12-Aug-2020 09:40:17        at com.atlassian.bamboo.security.ImpersonationHelper.runWithSystemAuthority(ImpersonationHelper.java:17)
error   12-Aug-2020 09:40:17        at com.atlassian.bamboo.security.ImpersonationHelper$1.run(ImpersonationHelper.java:41)
error   12-Aug-2020 09:40:17        at java.lang.Thread.run(Thread.java:748)
error   12-Aug-2020 09:40:17    Caused by: java.lang.NullPointerException
error   12-Aug-2020 09:40:17        at com.atlassian.bamboo.process.ExternalProcessBuilder.lambda$env$0(ExternalProcessBuilder.java:78)
error   12-Aug-2020 09:40:17        at com.google.common.base.Predicates$CompositionPredicate.apply(Predicates.java:552)
error   12-Aug-2020 09:40:17        at com.google.common.collect.Iterators$7.computeNext(Iterators.java:652)
error   12-Aug-2020 09:40:17        at com.google.common.collect.AbstractIterator.tryToComputeNext(AbstractIterator.java:143)
error   12-Aug-2020 09:40:17        at com.google.common.collect.AbstractIterator.hasNext(AbstractIterator.java:138)
error   12-Aug-2020 09:40:17        at com.google.common.collect.Iterators.size(Iterators.java:191)
error   12-Aug-2020 09:40:17        at com.google.common.collect.Collections2$FilteredCollection.size(Collections2.java:211)
error   12-Aug-2020 09:40:17        at java.util.AbstractMap.size(AbstractMap.java:85)
error   12-Aug-2020 09:40:17        at java.util.HashMap.putMapEntries(HashMap.java:501)
error   12-Aug-2020 09:40:17        at java.util.HashMap.putAll(HashMap.java:785)
error   12-Aug-2020 09:40:17        at com.atlassian.bamboo.process.ExternalProcessBuilder.env(ExternalProcessBuilder.java:78)
error   12-Aug-2020 09:40:17        at com.atlassian.bamboo.process.ProcessServiceImpl.createExternalProcess(ProcessServiceImpl.java:144)
error   12-Aug-2020 09:40:17        at com.atlassian.bamboo.process.ProcessServiceImpl.executeExternalProcess(ProcessServiceImpl.java:195)
error   12-Aug-2020 09:40:17        at com.atlassian.bamboo.process.ProcessServiceImpl.executeExternalProcess(ProcessServiceImpl.java:210)
error   12-Aug-2020 09:40:17        at com.atlassian.bamboo.plugins.shell.task.AbstractShellBuildTask.execute(AbstractShellBuildTask.java:48)
error   12-Aug-2020 09:40:17        ... 17 more

A: I talked with Atlassian support and they helped me work through the issue.  I had setup the remote agent as a windows service which was causing the problems.  I removed the service and started the remote agent via the BambooAgent.bat script.  Mine was located at %InstallDirectory%/bin/BambooAgent.bat


Q: Asp.net WebApi multipart/form-data with id from route definition I'm sending a multipart/form-data request to an action (file upload), but I'm sending it to an action that has the id in the url as specified by the route:
routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{id}/{action}",
    defaults: new {action = "Index", id = RouteParameter.Optional }
);

Url I'm posting to: /api/Contacts/1/Photo
Action:
[HttpPost]
public HttpResponseMessage Photo(int id)
{

    var task = this.Request.Content.ReadAsStreamAsync();
    task.Wait();
    Stream requestStream = task.Result;

    /* ... */

}

With the id parameter, I get this error: No 'MediaTypeFormatter' is available to read an object of type 'Int32' with the media type 'multipart/form-data'. Without the id parameter, it works fine.
I tried a MediaTypeFormatter in this answer here, but it doesn't seem to get the id from the url and crashes when trying to get it using FirstDispositionNameOrDefault("id"). Is there a way to get the id specified in the route url to bind to the id parameter for the action?

A: FirstDispositionNameOrDefault is for reading the values of form controls.
You can use the [FromUri] attribute on the parameter:
public HttpResponseMessage Photo([FromUri] int id)

This tells Web API not to get the parameter from the message body.


Q: how to display data from json with looping javascript? This is my json code structure
This is my javascript:
$('#kurir').change(function(){
var kurirID = $(this).val();
if(kurirID){
    $.ajax({
       type:"GET",
       url:"{{url('checkout/kurir')}}?kurir_id="+kurirID,
       success:function(res){
        if(res){
            $("#ongkir").prop('disabled', false);
            $("#ongkir").empty();
            $("#ongkir").append('<option>--- Pilih Kurir ---</option>'); $.each(res,function(key,value){ $("#ongkir").append('<option value="'+key['service']+'">'+this.value['service']+'</option>'); }); }else{ $("#ongkir").empty();
        }
       }
    });
}else{
     $("#ongkir").prop('disabled', true);
    $("#ongkir").empty();
    $("#ongkir").append('<option>--- Pilih Kurir ---</option>');
}});

This is my controller
public function getKurirList(Request $request)
{$data = RajaOngkir::Cost(['origin'=> 419,'destination'=> 114,'weight'=> 1700,'courier'=> 'jne',])->get(); return response()->json($data); }

I want to show all "service" data and price "value".
How to iterate this json with a 'each' loop and print the data?
Can anyone help me?

A: You should iterate over  $datas['0']['costs']
foreach ($datas['0']['costs'] as $key =$value){

  echo $value['service'] . ' - ' $value['cost'][0]['value'];

}


Q: How to use Google Cloud PubSub with Proxy? I'm working with an application that interacts with Google Cloud PubSub. It works fine in normal scenario but I want to enable proxy support so I was going through Publisher.Builder and Subscriber classes and their APIs to see if there are any APIs available to enable proxy support. I managed to find only the setChannelProvider but I'm not sure whether that will work or not.
The following code snippet is what I'm thinking of using but that doesn't seem to work.
ManagedChannel channel = ManagedChannelBuilder.forAddress(proxyHost, proxyPort).build();
TransportChannelProvider channelProvider = FixedTransportChannelProvider.create(GrpcTransportChannel.create(channel));
publisherBuilder.setChannelProvider(channelProvider);

I wasn't able to successfully publish or pull messages to the cloud service. I get the following error:
java.util.concurrent.ExecutionException: io.grpc.StatusRuntimeException: DEADLINE_EXCEEDED: deadline exceeded after 9978300322ns

So I wanted to know does the PubSub service support proxy through APIs or does it only support the proxy setting i.e. host and port to be provided in the environment path only.

A: You can specify the proxyHost/port directly using JVM args https.proxyHost, https.proxyPort
mvn clean install -Dhttps.proxyHost=localhost -Dhttps.proxyPort=3128  exec:java

then just directly create a client of your choice
TopicAdminSettings topicAdminSettings =   TopicAdminSettings.newBuilder().build();
TopicAdminClient topicAdminClient = TopicAdminClient.create(topicAdminSettings);

FYI- Setting ManagedChannelBuilder.forAddress() here overrides the final target for pubsub (which should be pubsub.googleapis.com 443 (not the proxy)
Here is a medium post i put together as well as a gist specificlly for pubsub and pubsub+proxy that requires basic auth headers

*

*
finally, just note, its https.proxyHost even if you're using httpProxy, ref grpc#9561

A: Proxy authentication via HTTP is not supported by Google Pub/Sub, but it can be configured by using GRPC_PROXY_EXP environment variable.
I found the same error that you got here (that's why I assume you are using HTTP) and it got fixed by using what I said.

A: You need to set JVM args:  https.proxyHost, https.proxyPort
for proxy authentication an additional configration is needed before any client creation:
 Authenticator.setDefault(new Authenticator() {
                        protected PasswordAuthentication getPasswordAuthentication() {
                            return
                                    new PasswordAuthentication(proxyUsername,proxyPassword).toCharArray());
                        }


Q: Is there a way to loop backwards after finding a certain line in a txt doc? I am working with using excel data to edit parts of large txt files. Some of these edits require deleting certain sections, and other require copying, pasting, and slightly editing these sections.
For example, the txt doc takes this basic form:
Monitor 1
Monitor 2
Item1 Item2
End

Monitor 3
Monitor 4
Monitor 5
Item3 Item4
End

Monitor 6
Item4 Item5
End

Say I am needing to delete the second block (that is, delete from after the first end to the line before monitor 6). I am able to find the block using lookups for Item3 and Item4. Is there a way to assign this block to a variable?
with open(longStr1) as old_file:
    lines = old_file.readlines()
    with open(endfile1, "w") as new_file:
        for line in lines:
            if "Item3 Item4" in line:
                #block = from previous End to after next End
                lines.remove(block)
            new_file.write(line)

So ideally, this would allow me to delete the entire block of text to make the txt file then look like this:
Monitor 1
Monitor 2
Item1 Item2
End

Monitor 6
Item4 Item5
End

How can I define this block using python?

A: Iterative approach:
search_item = "Item3 Item4"

with open('input.txt') as f_in, open('output.txt', 'w') as f_out:
    block = ''
    for line in f_in:
        if block:
            block += line
            if line.strip() == 'End':
                if search_item not in block: f_out.write(block + '\n')
                block = ''
        elif line.startswith('Monitor'):
            block = line

output.txt contents:
Monitor 1
Monitor 2
Item1 Item2
End

Monitor 6
Item4 Item5
End

A: You could accumulate the lines to write in a separate string that corresponds to the content of one block. Wait until you reach the end of the block ("end" line) before writing the accumulated lines.  If along the way, you find the text pattern that indicates suppression of the block, set a flag that will prevent writing to the file when the end is reached.
For example (not tested):
with open(longStr1) as old_file:
    lines = old_file.readlines()
    lineBlock = ""
    excluded  = False
    with open(endfile1, "w") as new_file:
        for line in lines:
            lineBlock += line
            if line == "End":
                if not excluded:
                    new_file.write(lineBlock)
                lineBlock = ""
                excluded  = False
            if "Item3 Item4" in line:
                excluded  = True


Q: How to query the print queue on Windows We are developing a critical application and need to have the finest control over the documents printed.  To be sure on which documents are printed or not we want to check the printer queue.
How can we query the print queue on Windows (status, queue list, errors, ...)?

A: EnumPrinters to get the list of printers, EnumJobs to get a list of jobs for that printer. GetJob to get info on a specific job and SetJob to change the settings for that job (pause or cancel it).
See more in the Printing and Print Spooler References.
.NET has the PrintQueue and PrintServer classes.

A: Following URLs may be of interest to you,
http://www.codeproject.com/KB/printing/printwatchvbnet.aspx
and
http://www.codeproject.com/KB/printing/EMFSpoolViewer.aspx


Q: Method chaining to communicate between GUI parts in a MVC in Java I am creating a Java Desktop GUI application using the MVC pattern. For the sake of simplicity, I have divided in GUI application into different panels (Scheme of the GUI application) so that each class takes care of something specific. Now, when I am in the Controller part and want to display something in the DRAW PANEL, I have a method chaining. I mean I am calling several methods in a row:
view.getRightPanel().getDrawPanel().appendText(model.getResults());

I am wondering whether or not I am making a mistake somewhere. Is it normal to do so, or should I change my code to make it more efficient and elegant?
Any information is welcome! Thank you!

A: You are not making a mistake if you are doing this in the controller.
In the MVC pattern, the controller listens for model changes and updates the view. That is what the controller is supposed to do. Here,
view.getRightPanel().getDrawPanel().appendText(model.getResults());

I guess you are changing the text in a draw panel in the view that controller is controlling, which is exactly what the controller is supposed to do.
Do be careful not to change update the model directly from the view, or update the view from the model though. That violates MVC.
I also suggest you to create multiple controllers to control different panels on the screen. I think that way it will be more manageable.


Q: How can I fix: "start-stop-daemon: warning: this system is not able to track process names" when starting springboot as a systemd service? When I start my spring boot app as a systemd service I receive this error:
start-stop-daemon: warning: this system is not able to track process names longer than 15 characters, please use --exec instead of --name.
Spring boot seems to build the process name from the jar name and the directory the jar is contained in.  Is there any way to fix this aside from renaming the jar, and the directory it's contained in, to be shorter than 15 characters?
If I try to edit spring boots startup script to use --exec instead of --name then I get another error:
'start-stop-daemon: unable to stat /opt/program/programname_optprogramname (No such file or directory)

A: It appears that this issue is fixed in Spring boot 2.0.2.  So if you run into this issue upgrading might fix it (not to imply that upgrading is always a simple effort)


Q: Need help aligning my textfields with my radio buttons how it looks like right now

i' m placing all my inputs on the right with float: right; in my css file.
But i'm wondering if there is a way to align my radios
to the left side of my text fields?
so they all align under each other on the left side.

A: I would strongly advocate using the more sophisticated, flexible solution even with great browsers support, the flexbox. You could have used align-self to align specify elements along with default alignment to sibling elements. If you did not know about flexbox, It's worth learning right now.


Q: Clarification regarding odds ratios in logistic regression I am trying to understand odds ratios (OR) in logistic regression. So far what I read says that "OR is a measure of association between exposure and outcome".
I got a kid dental dataset in which the independent variable is disability status, i.e., whether a child has a disability or not (1 for disability and 2 for a normal kid), and the dependent variable is whether a kid gets dental attendance on time or not (1 for on-time dental attendance and 0 for late dental attendance).
If I am not mistaken, in the above case, there are two exposure variables: disabled and normal kid, and the outcome is on-time dental attendance or not.
If I am right, my question is: Do I need to calculate the OR for each type of exposure variable (i.e. one OR for disabled and one for normal) or is it only one OR value for both values of the exposure variable? If it is one single value, then how could we interpret OR=1.5? Could we say that there is 50% more chance that disabled kids do not (or do) get dental attendance on time? Could anyone help me in understanding the concept?

A: Suppose your data looked like
             on-time   late

Disabled       22        5

Other         125       40

Then the odds for disabled children to be treated on time is $\frac{22}{5} =4.4$ and their odds for being treated late is the reciprocal of that, about $0.2273$
While the odds for other children to be treated on time is $\frac{125}{40} =3.125$ and their odds for being treated late is the reciprocal of that, $0.32$
So the odds ratio for disabled children to be treated on time compared to other children is $\frac{4.4}{3.125} = 1.408$.
This is also the odds ratio for other children to be treated late compared to disabled children.  The odds ratio for disabled children to be treated late compared to other children and the odds ratio for other children to be treated on time compared to disabled children are each the reciprocal of that, about $0.7102$.
None of these are how much "more chance that disabled kids do not (or do) get dental attendance on time", as that is a comparison of probabilities rather than odds. The proportion of times disabled children are treated on time ($0.8148$) is about $1.0756$ times the proportion of times other children are treated on time ($0.7639$); the proportion of times disabled children are treated late ($0.1852$) is about $0.7639$ times the proportion of times other children are treated on time ($0.2424$).
While it is easy to move between odds and probabilities, translating from odds ratios to probability ratios needs information about prevalence.


Q: store time from stopwatch Javascript in MySQL database I am using a javascript to start and stop a timer (stopwatch).
What I want is that when the user press the stop button, the data (the time at that moment) will be stored in my MySQL database. Is that possible? And if yes, what do I need to add as code? (I'm just a starter with PHP, if someone can add a small explanation then that would be great so I can learn from it)
The following script is my working javascript code:
var clsStopwatch = function () {

var startAt = 0;
var lapTime = 0;

var now = function () {
    return (new Date()).getTime();
};

this.start = function () {
    startAt = startAt ? startAt : now();
};

this.stop = function () {
    lapTime = startAt ? lapTime + now() - startAt : lapTime;
    startAt = 0;
};

this.time = function () {
    return lapTime + (startAt ? now() - startAt : 0);
};
};

var x = new clsStopwatch();
var $time;
var clocktimer;

function pad(num, size) {
var s = "0000" + num;
return s.substr(s.length - size);
}

function formatTime(time) {
var h = m = s = ms = 0;
var newTime = '';

m = Math.floor(time / (60 * 1000));
time = time % (60 * 1000);
s = Math.floor(time / 1000);
ms = time % 1000;

newTime = pad(m, 2) + ':' + pad(s, 2) + ':' + pad(ms, 2);
return newTime;
}

function show() {
$time = document.getElementById('time');
update();
}

function update() {
$time.innerHTML = formatTime(x.time());
}

function start() {
clocktimer = setInterval("update()", 1);
x.start();
}

function stop() {
x.stop();
clearInterval(clocktimer);
}

The next is my PHP code that I use to store data in my database, it's on a separate page.
define('DB_NAME', 'dbname');
define('DB_USER', 'user');
define('DB_PASSWORD', 'pass');
define('DB_HOST', 'host');

$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);

if (!$link) { die('could not connect: ' . mysql_error()); }

$db_selected = mysql_select_db(DB_NAME, $link);

if (!$db_selected) { die('can not use ' . DB_NAME . ': ' . mysql_error()); }

$sql="INSERT INTO game (name, company, email, time) VALUES
    ('".$_POST['name']."','".$_POST['company']."','".$_POST['email']."','".$_POST['time']."')";

if (!mysql_query($sql)) { die('Error: ' . mysql_error()); }

mysql_close();

and my HTML submit form:

<form action="highscore.php" method="post"/>

name:

<input type="text" name="name"/>

company:

<input type="text" name="company"/>

email:

<input type="text" name="email"/>

Time:

<input type="button" value="start" onclick="start();">
<input type="submit" value="stop" onclick="stop();">

</form>

Maybe a solution could be to post the data in a hidden input field but still i'm struggling to get that one working.

A: Try this:
function stop() {
x.stop();
document.getElementById('counter').value = formatTime(x.time());
clearInterval(clocktimer);
}

On your form:
<input type="hidden" value="" id="counter" name="counter" />

A: Use MySQLi instead of MySQL, because there's some serious security problems with MySQL


Q: How to setup static page with css in subdirectory in rails public directory I'm trying to setup jekyll blog in my public/blog directory.
For this question let say I just want to have public/blog directory with index.html and css/site.css with css for this page.
I'm deploying it using capistrano, so I added public/blog to linked_dirs
index.html:

    <link rel="stylesheet" type="text/css" href="css/site.css">

Hello World

css/site.css:
h1 {
  color: red;
}

Now after cap production deploy I can visit domain.com/blog and see Hello World header, but it does not load css file.
I get Failed to load resource: the server responded with a status of 404 (Not Found) error.
Do you know how can I make it work?

A: It was more a nginx question.
I added this to my site nginx file:
  location ^~ /blog/css/ {
    gzip_static on;
    expires max;
    add_header Cache-Control public;
  }


Q: Can a number be Romanised this way? I know there are a few different ways to Romanise a number, however I'm trying to make up my own and was wondering if this approach is possible.
It returns Null for every iteration and I can't seem to see what I am missing here. Any help would be much appreciated!

var array;
var result = [];

function convertToRoman(num) {
  array = num.toString().split('').reverse();

  roman = ["", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX",
    "", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC",
    "", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"
  ];

  for (i = 0, j = 0; i < array.length; i++, j += 10) {
    var location = array[i] + j;
    result = result.concat(roman[location]);
  }

  return result.reverse().join();
}

console.log(convertToRoman(123));

A: As array contains strings, you have to parse them back to integers when using them in the arithmetic. This is a possible solution:

var roman = ["", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX",
  "", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC",
  "", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"
];

function convertToRoman(num) {
  var result = [];
  var array = num.toString().split('').reverse();

  for (i = 0, j = 0; i < array.length; i++, j += 10) {
    var location = parseInt(array[i]) + j;
    result.push(roman[location]);
  }

  return result.reverse().join('');
}

console.log(convertToRoman(123));

Note that I made some changes regarding variable scope and use of array.push(). I also didn't try the method for multiple inputs. But getting the algorithm correct was not part of your question


Q: Martingale and stopping time expectation I read a book that claims the following: Let $\{X_{n} : n\in\mathbb{N}\}$ be a martingale and $T$ a stopping time.
Then
\begin{equation}
E[X_T 1_{\{T \leq n\}}] = \sum_{j=0}^{n} E[X_j 1_{\{T = j\}}] = \sum_{j=0}^{n} E[X_0 1_{\{T = j\}}] = E[X_0 1_{\{T \leq n\}}]
\end{equation}
I don't see the second equality. And yes, it is really $X_T 1_{\{T \leq n\}}$ and not $X_{T \wedge n}$.
This should be a counter example: For the standard integer random walk with $X_0 = 0$ a.s., $n=1$ and $T = \inf\{n : X_n = 1\}$
\begin{equation}
E[X_T 1_{\{T \leq n\}}] = P(T=1) = 1/2 > 0 = E[X_0 1_{\{T \leq n\}}]
\end{equation}
Still I'm a bit confused. Is there something wrong with my example?
Thanks for your help.


Q: Requiring multiple string conditions in WHERE CLAUSE SELECT stu.First_Name, stu.Last_Name, stu.Phone
FROM Student stu
JOIN Enrollment e
ON stu.Student_Id = e.Student_Id
JOIN Section sec
ON e.Section_Id = sec.Section_Id
JOIN Course c
ON sec.Course_No = c.Course_No
WHERE c.Description = 'Systems Analysis' AND c.Description = 'Project Managment'

Hey all, hopefully the last question for today (I'm so sorry).  I was wondering if there is a way to check for multiple string conditions (being an AND, not OR).  When I use just one my joins work alright, but I can't seem to work past using both.  My textbook wants me to solve it with only using the string keywords for the courses.

A: Use OR and filter only the rows having the same number of instances to the the number of filter specified in the WHERE clause.
SELECT  stu.First_Name,
        stu.Last_Name,
        stu.Phone
FROM    Student stu
        JOIN Enrollment e
            ON stu.Student_Id = e.Student_Id
        JOIN Section sec
            ON e.Section_Id = sec.Section_Id
        JOIN Course c
            ON sec.Course_No = c.Course_No
WHERE   c.Description IN ('Systems Analysis', 'Project Managment') -- two values
GROUP   BY stu.First_Name, stu.Last_Name, stu.Phone
HAVING  COUNT(*)  = 2 -- rows must have 2 instances


Q: Controlling x-axis label format for time series plots - R Is there a way force R to print time stamps as %m/%d/%Y on graphs? When I have short (<7 days) of data it prints as days of the week as below?
plot(station_171$datetime, station_171$stageheight, pch=ifelse(station_171$outcode ==122,24,21), col="black", bg=ifelse(station_171$outcode ==122,"red","NA")
     , xlab = "",xlim = c(min(station_101_7$datetime),max(station_101_7$datetime)), ylab = "")
legend("topright","171", bty = "n", cex=2)

A: You can format the axis using axis.POSIXct as seen below:
axis.POSIXct(1,station_171$datetime, format = '%Y-%m-%d %H:%S')

One should also make sure to include the xaxt='n' in the plot function to avoid double printing the x-axis labels.